Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 获取每个分区中每列的平均值_Python_Pandas_Mean_Partition - Fatal编程技术网

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()
试试这个?