python - 使用 pandas 一周中每天的平均 Action 次数

标签 python pandas dataframe

假设我对每小时的事件数进行了如下统计:

np.random.seed(42)
idx = pd.date_range('2017-01-01', '2017-01-14', freq='1H')
df = pd.DataFrame(np.random.choice([1,2,3,4,5,6], size=idx.shape[0]), index=idx, columns=['count'])
df.head()

Out[3]:
                     count
2017-01-01 00:00:00      4
2017-01-01 01:00:00      5
2017-01-01 02:00:00      3
2017-01-01 03:00:00      5
2017-01-01 04:00:00      5

如果我想知道一周中每天的事件数,我可以执行以下任一操作:

df.pivot_table(values='count', index=df.index.dayofweek, aggfunc='sum')

df.groupby(df.index.dayofweek).sum()

两种 yield :

Out[4]:
   count
0    161
1    170
2    164
3    133
4    169
5     98
6    172

但是,如果我想计算每个工作日的平均事件数,则如下

df.pivot_table(values='count', index=df.index.dayofweek, aggfunc='mean') # [#1]

错误!!此方法使用总和(如上计算),并将其除以一周中每一天出现的小时数。

我找到的解决方法是:

df_by_day = df.resample('1d').sum()
df_by_day.pivot_table(values='count', index=df_by_day.index.dayofweek, aggfunc='mean')

也就是说,首先重新采样到天数,然后旋转它。不知何故,[#1] 中的方法对我来说很自然。有没有更pythonic的方式来实现我想要的?为什么没有重采样的均值计算错误?

最佳答案

Resample first using df.resample and then df.groupby :

df = df.resample('1d').sum()
print(df)

            count
2017-01-01     92
2017-01-02     86
2017-01-03     86
2017-01-04     90
2017-01-05     64
2017-01-06     82
2017-01-07     97
2017-01-08     80
2017-01-09     75
2017-01-10     84
2017-01-11     74
2017-01-12     69
2017-01-13     87
2017-01-14      1

out = df.groupby(df.index.dayofweek)['count'].mean()
print(out)

1    85.0
2    82.0
3    66.5
4    84.5
5    49.0
6    86.0
Name: count, dtype: float64

关于python - 使用 pandas 一周中每天的平均 Action 次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45922291/

相关文章:

python - 或者重新排列 Dataframe 的行

python - 使用 HyperlinkedModelSerializer 强制 https?

python - Python 中使用 Pandas.series.str.contains 进行字符串替换时出现模式匹配错误

python - 如何通过 Python 3.5.1 创建永久性 MS Access 查询?

python - 有没有办法加快以下 pandas for 循环?

python - 如何使用列名列表对数据框进行排序

r - 选择特定列,其中列名在r中的另一个df中

python - 在 Pandas/Python 中使用 loc 和仅使用方括号过滤列有什么区别?

Python:提高for循环的性能,内部函数调用仅取决于循环索引

python - Python字典理解中的多重赋值