我有一个看起来像这样的数据框:
Name Col1 Col2 Col3 DownIndicator
A 0
A 1
B 0
C 0
C 1
C 1
我想创建显示 DownIndicator 列的扩展平均值的列
所以期望的输出是
Name Col1 Col2 Col3 DownIndicator MeanDown
A 0 0
A 1 0.5
B 0 0
C 0 0
C 1 0.5
C 1 0.66
你能帮忙吗? 我正在研究expanding_mean,但无法在实践中应用它
最佳答案
使用Expanding.mean
与groupby
,但因为创建MultiIndex
是必要的,通过reset_index(level=0, drop=True)
删除第一级:
df['new'] = (df.groupby('Name')['DownIndicator']
.expanding()
.mean()
.reset_index(level=0, drop=True))
print (df)
Name DownIndicator new
0 A 0 0.000000
1 A 1 0.500000
2 B 0 0.000000
3 C 0 0.000000
4 C 1 0.500000
5 C 1 0.666667
关于python - 扩展 groupby 对象的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58851802/