2 回答
TA贡献1909条经验 获得超7个赞
GroupBy.transform与rolling和一起使用mean:
df['mean'] = (df.groupby('user')['profit']
.transform(lambda x: x.rolling(len(x), min_periods=1).mean()))
print (df)
user profit mean
0 Anna 1.0 1.0
1 Bell 2.0 2.0
2 Anna 2.0 1.5
3 Chad 5.0 5.0
4 Bell 4.0 3.0
5 Anna 3.0 2.0
TA贡献1802条经验 获得超5个赞
我认为到目前为止,我们可以使用cumsum()并除以计数。
g = df.groupby('user')['profit']
df['mean'] = g.cumsum() / (g.cumcount() + 1)
完整的例子
import pandas as pd
import numpy as np
df = pd.DataFrame({
"user": ("Anna", "Bell", "Anna", "Chad", "Bell", "Anna"),
"profit": (1.0, 2.0, 2.0, 5.0, 4.0, 3.0)
})
g = df.groupby('user')['profit']
df['mean'] = g.cumsum() / (g.cumcount() + 1)
print(df)
返回值:
user profit mean
0 Anna 1.0 1.0
1 Bell 2.0 2.0
2 Anna 2.0 1.5
3 Chad 5.0 5.0
4 Bell 4.0 3.0
5 Anna 3.0 2.0
添加回答
举报