我希望根据不同行中的类似price
和family
列平均city
,假设我有以下数据框,
df1 = [ID, name, family, city, price
1, a, g, u, 25
2, f, b, c, 20
3, i, b, c, 15
4, k, b, c, 10
5, r, b, c, 15
6, d, r, t, 20
7, q, x, s, 11]
我的预期数据框是:
df1 = [ID, name, family, city, price
1, a, g, u, 25
2, f, b, c, 15
3, i, b, c, 15
4, k, b, c, 15
5, r, b, c, 15
6, d, r, t, 20
7, q, x, s, 11]
我使用groupby
,但效果不好,
shareg1 = df1[['ID','name','family','city','price']].groupby(['family','city']).mean().reset_index()`
答案 0 :(得分:1)
通常的技巧
df1['avg_price']= df1[['ID','name','family','city','price']].groupby(['family','city']).price.transform('mean')