編輯:另一個解決方案是更快的是使用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
這總是值得檢查這些一些timeits:
In [21]: %timeit df1.User.resample('D', how=len)
1000 loops, best of 3: 720 µs per loop
不幸的是,使這更加昂貴:
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