32
votes

In the following, male_trips is a big pandas data frame and stations is a small pandas data frame. For each station id I'd like to know how many male trips took place. The following does the job, but takes a long time:

mc = [ sum( male_trips['start_station_id'] == id ) for id in stations['id'] ]

how should I go about this instead?


Update! So there were two main approaches: groupby() followed by size(), and the simpler .value_counts(). I did a quick timeit, and the groupby approach wins by quite a large margin! Here is the code:

from timeit import Timer
setup = "import pandas; male_trips=pandas.load('maletrips')"
a  = "male_trips.start_station_id.value_counts()"
b = "male_trips.groupby('start_station_id').size()"
Timer(a,setup).timeit(100)
Timer(b,setup).timeit(100)

and here is the result:

In [4]: Timer(a,setup).timeit(100) # <- this is value_counts
Out[4]: 9.709594964981079

In [5]: Timer(b,setup).timeit(100) # <- this is groupby / size
Out[5]: 1.5574288368225098

Note that, at this speed, for exploring data typing value_counts is marginally quicker and less remembering!

5
How big is the data frame? Do you have enough memory? I don't see anything wrong with it speed wise. - myusuf3
@myusuf3 just for comparison, my approach above takes more than a minute (I got bored counting) whereas Dani's solution below would be measured in ms. - Mike Dewar
This is really surprising since there is a specific value count function in algorithms.py and I doubt Wes would have added this if it wasn't faster than groupby and then size. I get different results for a DataFrame I just loaded : In [20]: timeit df.groupby(df.columns[8]).size() 100 loops, best of 3: 13.4 ms per loop In [22]: timeit df[df.columns[8]].value_counts() 100 loops, best of 3: 5.62 ms per loop. - Arthur G
Be sure to run timing tests multiple times (10 or more) and in multiple orders (a before b, a after b). If you only did two tests, it is possible the first run loaded the data from disk into a disk buffer, and the second run read it directly from the buffer, avoiding the disk access time. - BobC

5 Answers

50
votes

I'd do like Vishal but instead of using sum() using size() to get a count of the number of rows allocated to each group of 'start_station_id'. So:

df = male_trips.groupby('start_station_id').size()
21
votes

My answer below works in Pandas 0.7.3. Not sure about the new releases.

This is what the pandas.Series.value_counts method is for:

count_series = male_trips.start_station_id.value_counts()

It should be straight-forward to then inspect count_series based on the values in stations['id']. However, if you insist on only considering those values, you could do the following:

count_series = (
                male_trips[male_trips.start_station_id.isin(stations.id.values)]
                    .start_station_id
                    .value_counts()
               )

and this will only give counts for station IDs actually found in stations.id.

3
votes

how long would this take:

df = male_trips.groupby('start_station_id').sum()
2
votes

edit: after seeing in the answer above that isin and value_counts exist (and value_counts even comes with its own entry in pandas.core.algorithm and also isin isn't simply np.in1d) I updated the three methods below

male_trips.start_station_id[male_trips.start_station_id.isin(station.id)].value_counts()

You could also do an inner join on stations.id: pd.merge(male_trips, station, left_on='start_station_id', right_on='id') followed by value_counts. Or:

male_trips.set_index('start_station_id, inplace=True)
station.set_index('id, inplace=True)
male_trips.ix[male_trips.index.intersection(station.index)].reset_index().start_station_id.value_counts()

If you have the time I'd be interested how this performs differently with a huge DataFrame.