Pandas:根据不同列中的类别对多个列的值进行分组。然后根据该类别的分组计算平均值[

问题描述 投票:0回答:2

我有一个类似这样的数据集。

Country  Continent    1970   ....   2000 .... 2011
abc        Asia        0.8   ....    0.9 .... 1.1
def        Europe      0.9   ....    1.6 .... 0.6
asd        Oceania     1.2   ....    2.3 .... 1.5
.            .
.            .          .             .         .
.            .          .             .         .

我想实现的是基于大洲列的2000年及以上(仅某些列)的组数据。因此,将2000-2011年亚洲的数据分组,将欧洲的数据分组,依此类推,然后计算该分组的平均值。我的预期输出是这样的。

Avg of Asia from 2000-2011 is: val
Avg of Europe from 2000-2011 is: val
Avg of North America from 2000-2011 is: val

我对python和pandas相当陌生。到目前为止,这是我尝试过的。这给了我那几年的价值平均值。如何通过按大陆分组年度值来做到这一点。

data_set = pd.read_csv('dataset.csv')
data_columns_needed = data_set[['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011']]
mean = data_columns_needed.mean()
print(mean)

我知道groupby方法,但是我还没有弄清楚如何实现它来实现此目的的解决方案。非常感谢帮助!

python pandas
2个回答
0
投票
您可以做:

# don't forget to add the 'Country' AND 'Continent' key here: data_columns_needed = data_set[['Country', 'Continent', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011']] # average over a row: data_columns_needed['row_mean'] = data_columns_needed[['2000', '2001' ... ]].mean(axis=1) # average over a group, grouped by continents and countries: data_columns_needed.groupby(['Continent', 'Country']).mean()


0
投票
检查数据框后,您实际上不需要groupby。您只需要mean()公式并传递参数axis=0

尝试以下操作:

data_columns_needed['Mean'] = data_columns_needed.mean(axis=0) new_data = pd.concat([data_set[['Country','Continent']],data_columns_needed[['Mean']]],ignore_index=True,axis=1) new_data = new_data.groupby('Continent')['Mean'].mean()

© www.soinside.com 2019 - 2024. All rights reserved.