编辑:另一个更快的解决方案是使用value_counts
(和normalize):
In [41]: %timeit df1 = df.set_index('Time'); pd.value_counts(df1.index.normalize(), sort=False)
1000 loops, best of 3: 586 µs per loop
resample
我原以为如果你使用 DatetimeIndex的话,这更简洁地写成:
但是它似乎要慢得多,而且(令人惊讶的是)Counter 解决方案是最快的!
In [11]: df1 = df.set_index('Time')
In [12]: df1.User.resample('D', how=len)
Out[12]:
Time
2013-01-01 59
2013-01-02 58
2013-01-03 3
Freq: D, Name: User, dtype: int64
总是值得为这些检查一些时间:
In [21]: %timeit df1.User.resample('D', how=len)
1000 loops, best of 3: 720 µs per loop
不幸的是,set_index
这使得这更加昂贵:
In [22]: %timeit df1 = df.set_index('Time'); df1.User.resample('D', how=len)
1000 loops, best of 3: 1.1 ms per loop
比较:
In [23]: %%timeit
....: grouped_dates = df.groupby(df['Time'].apply(lambda x : x.date()))
....: grouped_dates['Time'].aggregate(len)
....:
1000 loops, best of 3: 788 µs per loop
In [24]: %%timeit
....: counted_dates = Counter(df['Time'].apply(lambda x: x.date()))
....: counted_series = pd.Series(counted_dates)
....: counted_series.index = pd.to_datetime(counted_series.index)
....:
1000 loops, best of 3: 568 µs per loop
我曾怀疑对于更多的日期会有所不同......
In [31]: df = pd.DataFrame({'User' : ['A', 'B', 'C'] * 400,
'Value' : np.random.randn(1200),
'Time' : [np.random.choice(pd.date_range(datetime.datetime(1992,1,1,0,0,0),datetime.datetime(2014,1,1,0,0,0),freq='H')) for i in range(1200)]})
In [32]: %timeit df1 = df.set_index('Time'); df1.User.resample('D', how=len)
10 loops, best of 3: 28.7 ms per loop
In [33]: %%timeit
....: grouped_dates = df.groupby(df['Time'].apply(lambda x : x.date()))
....: grouped_dates['Time'].aggregate(len)
....:
100 loops, best of 3: 6.82 ms per loop
In [34]: %%timeit
....: counted_dates = Counter(df['Time'].apply(lambda x: x.date()))
....: counted_series = pd.Series(counted_dates)
....: counted_series.index = pd.to_datetime(counted_series.index)
....:
100 loops, best of 3: 3.04 ms per loop
但是计数器仍然赢了......!
编辑:但被value_counts粉碎:
In [42]: %timeit df1 = df.set_index('Time'); pd.value_counts(df1.index.normalize(), sort=False)
1000 loops, best of 3: 989 µs per loop