python - Pandas DataFrame 按两列分组并添加移动平均列

标签 python pandas

我有一个数据框,我想使用多个列进行分组,然后根据分组添加计算列(平均值)。有人可以帮我吗?

我已经尝试过分组,效果很好,但添加计算的(滚动平均值)列被证明是一件很麻烦的事情

import pandas as pd
import numpy as np
df = pd.DataFrame([[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16], list('AAAAAAAABBBBBBBB'), ['RED','BLUE','GREEN','YELLOW','RED','BLUE','GREEN','YELLOW','RED','BLUE','GREEN','YELLOW','RED','BLUE','GREEN','YELLOW'], ['1','1','1','1','2','2','2','2','1','1','1','1','2','2','2','2'],[100,112,99,120,105,114,100,150,200,134,167,150,134,189,172,179]]).T
df.columns = ['id','Station','Train','month_code','total']
df2 = df.groupby(['Station','Train','month_code','total']).size().reset_index().groupby(['Station','Train','month_code'])['total'].max()

查看与下面类似的结果

Station  Train   month_code total   average
A   BLUE        1       112 
                2       114       113
    GREEN       1       99        106.5
                2       100       99.5
    RED         1       100       100
                2       105       102.5
    YELLOW      1       120       112.5
                2       150       135
B   BLUE        1       134       142
                2       189       161.5
    GREEN       1       167       178
                2       172       169.5
    RED         1       200       186
                2       134       167
    YELLOW      1       150       142
                2       179       164.5

最佳答案

更改您的初始 groupby 以保留列名称 'total' 怎么样。

df3 = df.groupby(['Station','Train','month_code']).sum()

>>> df3.head()
                          id  total
Station Train month_code           
A       BLUE  1            2    112
              2            6    114
        GREEN 1            3     99
              2            7    100
        RED   1            1    100

然后对total 列进行滚动平均值。

df3['average'] = df3['total'].rolling(2).mean()

>>> df3.head()
                          id  total  average
Station Train month_code                    
A       BLUE  1            2    112      NaN
              2            6    114    113.0
        GREEN 1            3     99    106.5
              2            7    100     99.5
        RED   1            1    100    100.0

如果您不需要,您仍然可以删除 id 列。

关于python - Pandas DataFrame 按两列分组并添加移动平均列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56134726/

相关文章:

python - PayPal Adaptive Payments API 因多个接收者而失败

Python套接字接收 - 传入的数据包总是有不同的大小

python - 如果显示元素,则查找元素的选择器无效

python - 从pandas数据帧过滤时如何进行精确的字符串匹配

python - 我可以将 Sprite 的 x 位置增加 -0.01,但不是 0.01?

python - 使用 NLTK 导入外部树库式 BLLIP 语料库

python - Pandas:具有多种功能的分组和聚合

python - 如何将列添加到 pandas 中的数据框

python - 如何在Python数据框中将一些值剪切到不同的列中?

pandas - 更改 seaborn 直方图(或 plt)中数据选择条的颜色