python - Pandas DataFrame Groupby 两列并添加移动平均列
问题描述
我有一个数据框,我想使用多列进行分组,然后根据分组添加一个计算列(平均值)。有人可以帮帮我吗?
我已经尝试过分组并且效果很好,但是添加计算的(滚动平均值)列被证明是一种麻烦
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 列。
推荐阅读
- sql - 异步查询状态功能仅在同一会话中可用?
- c - 使用 sscanf 解析字符串
- sql - Db2 decimal 打印零而不是四舍五入到小数位
- oracle - 将 Varchar2 转换为日期 - 使用 Case/Decode/IIF 语句并在 1 个条件中设置空值
- javascript - 覆盖 redux-form-validators 中的默认消息
- ios - 是否可以在测试运行期间检测 AutoLayout 约束问题?
- c# - CodedUI,如何将其他控件添加到先前映射的层次结构/页面中
- javascript - 来自表单输入字段的JS关联数组
- azure - Azure 函数无法发布并出现“PackageDependencyResolution.targets”错误
- html - 如何从 CMS 动态更改背景图像 SVG 的填充值