python - 在 Python 中按月和年分组并对所有列求和

标签 python pandas resampling

我有一个包含 10 列日常观察数据的数据框,然后有一个日期列。我想总结每天的观察结果并按月和年进行分组。

数据看起来与此类似:

    ds          c1         c2          c3          c4          c5          c6 
2019-05-27  285.029066  56.891208   404.848509  172.780268  391.853462  -47.865271  
2019-05-28  284.742624  83.432062   419.062742  172.039440  391.919534  -38.753380  
2019-05-29  284.456182  79.556789   413.650187  171.003154  391.985605  -36.871281  
2019-05-30  284.169740  63.251651   406.679183  170.160845  392.174533  -38.606698          
2019-05-31  283.883298  99.122362   441.525001  169.359221  392.463681  -7.067061   

我期望的输出是

   ds    c1  c2  c3  c4  c5  c6
2019-05 xx1 xx2 xx3 xx4 xx5 xx6

其中 xx1xx62019-05-272019-05-31 之间观察值的总和。

提前致谢。

最佳答案

使用DataFrame.resampleMS 表示 月份 的开始:

#datetimeindex
df['ds'] = pd.to_datetime(df['ds'])
df = df.set_index('ds')

df = df.resample('MS').sum()
print (df)
                    c1          c2           c3          c4           c5  \
ds                                                                         
2019-05-01  1422.28091  382.254072  2085.765622  855.342928  1960.396815   

                    c6  
ds                      
2019-05-01 -169.163691  

或使用月份:

df['ds'] = pd.to_datetime(df['ds'])

df2 = df.groupby(df['ds'].dt.to_period('m')).sum()
print (df2)
                 c1          c2           c3          c4           c5  \
ds                                                                      
2019-05  1422.28091  382.254072  2085.765622  855.342928  1960.396815   

                 c6  
ds                   
2019-05 -169.163691  

关于python - 在 Python 中按月和年分组并对所有列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57425148/

相关文章:

python - Anaconda (Python) - Windows 10 上的 Cmder 集成

python - 无法在 GroupBy 之后重命名列

python - 如何添加交错行作为排序/组的结果?

Python Pandas 库按截断日期重新采样

python - Pandas 使用其他不规则时间列表对不规则时间序列进行重新采样和插值

python - 不明白为什么这不能正确总结

python - python 中的元组列表

php - PHP 作为进程生成时未找到 ROS catkin_init_workspace

python - 使用位码减少/过滤冗余样本数据的优雅方法

通过簇替换重新采样