我试图获得DataFrame的每个分区的每列平均值,例如:
country city sales stock
0 UK London 1 34
1 UK Leeds 2 20
2 UK Leeds 3 21
3 RO Cluj 4 24
4 RO Cluj 5 25
5 RO Bucharest 6 25
也就是说,我希望获得sales
和stock
的平均值,并将这些值汇总为country
和city
的唯一组合。因此,生成的DataFrame应为:
country city sales stock
0 UK London 1 34
1 UK Leeds 2.5 20.5
2 RO Cluj 4.5 24.5
3 RO Bucharest 6 25
我的国家/地区城市分区的重复行已汇总到一行,并带有平均值。
我研究了pandas.DataFrame.mean()
上的文档和SO问题&诸如this one之类的答案,但没有一个能以直截了当的方式帮助我。任何帮助赞赏。
答案 0 :(得分:1)
groupby
df.groupby(['country', 'city']).mean()
sales stock
country city
RO Bucharest 6.0 25.0
Cluj 4.5 24.5
UK Leeds 2.5 20.5
London 1.0 34.0
设置索引
df.set_index(['country', 'city']).mean(level=[0, 1])
不设置索引
df.groupby([' country',' city'],as_index = False,sort = False).mean()
country city sales stock
0 UK London 1.0 34.0
1 UK Leeds 2.5 20.5
2 RO Cluj 4.5 24.5
3 RO Bucharest 6.0 25.0