python - 当日期不唯一时,在 Pandas 中按日期分组后计算观察结果

标签 python pandas datetime pandas-groupby

当时间戳不唯一时,在 Pandas DataFrame 中按日期计算观察值的最佳方法是什么?

df = pd.DataFrame({'User' : ['A', 'B', 'C'] * 40,
                   'Value' : np.random.randn(120),
                   'Time' : [np.random.choice(pd.date_range(datetime.datetime(2013,1,1,0,0,0),datetime.datetime(2013,1,3,0,0,0),freq='H')) for i in range(120)]})

理想情况下,输出将提供每天(或其他一些更高阶的时间单位)的观察次数。然后,这可用于绘制随时间变化的事件。

2013-01-01     60
2013-01-02     60

最佳答案

编辑:另一种更快的解决方案是使用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

但是 Counter 还是赢了...!

编辑:但被 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

关于python - 当日期不唯一时,在 Pandas 中按日期分组后计算观察结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21343401/

相关文章:

java - java中基于日期间隔的子列表

python - Python 和 GO 之间的通信媒介?

python - pandas如何计算仅给定月份和日期的增量

PHP 日期时间函数

python - to_excel() 没有索引布局

excel - 同时将 pandas DataFrame 写入 xlsx

java 日期值显示不正确

python - openpyxl.load_workbook(file, data_only=True 不起作用?

python - 如何使用 tkinter 创建菜单栏?

python - 在Python中通过UDP发送CAN帧