gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:52:14 29 4
gpt4 key购买 nike

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

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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com