pandas 数据框:按两列分组,然后对另一列取平均值 [英] Pandas dataframe: Group by two columns and then average over another column

查看:431
本文介绍了 pandas 数据框:按两列分组,然后对另一列取平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个具有以下值的数据框:

Assuming that I have a dataframe with the following values:

df:
col1    col2    value
1       2       3
1       2       1
2       3       1

我想首先根据前两列(col1和col2)对我的数据框进行分组,然后对thirs列的值(值)进行平均.因此,所需的输出将如下所示:

I want to first groupby my dataframe based on the first two columns (col1 and col2) and then average over values of the thirs column (value). So the desired output would look like this:

col1    col2    avg-value
1       2       2
2       3       1

我正在使用以下代码:

columns = ['col1','col2','avg']
df = pd.DataFrame(columns=columns)
df.loc[0] = [1,2,3]
df.loc[1] = [1,3,3]
print(df[['col1','col2','avg']].groupby('col1','col2').mean())

出现以下错误:

ValueError: No axis named col2 for object type <class 'pandas.core.frame.DataFrame'>

任何帮助将不胜感激.

推荐答案

您需要将列列表传递给groupby,您传递的内容被解释为

You need to pass a list of the columns to groupby, what you passed was interpreted as the axis param which is why it raised an error:

In [30]:
columns = ['col1','col2','avg']
df = pd.DataFrame(columns=columns)
df.loc[0] = [1,2,3]
df.loc[1] = [1,3,3]

print(df[['col1','col2','avg']].groupby(['col1','col2']).mean())
           avg
col1 col2     
1    2       3
     3       3

这篇关于 pandas 数据框:按两列分组,然后对另一列取平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆