Python 获取每个分区中每列的平均值
我试图为数据帧(如以下数据帧)获取每个分区每列的平均值:Python 获取每个分区中每列的平均值,python,pandas,mean,partition,Python,Pandas,Mean,Partition,我试图为数据帧(如以下数据帧)获取每个分区每列的平均值: 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 Buchare
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
也就是说,我想得到销售
和库存
的平均值,并将它们聚合为国家
和城市
的独特组合。因此,生成的数据帧应为:
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()
等问题和答案的文档,但没有一个能直接帮助我。谢谢你的帮助 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.set_index(['country', 'city']).mean(level=[0, 1])
groupby(['country','city',as_index=False,sort=False).mean()
准确地说,
df.groupby(['country','city'],如索引=False,排序=False)。mean()
试试这个?