python - 对 pandas 数据框进行分组,同时对某些列中的值进行平均

标签 python pandas

Country                        Region           Hemisphere     Crop Years  \
18  United States Of America  Temperate  Northern hemisphere    Maize  2011   
22  United States Of America  Temperate  Northern hemisphere    Maize  2015   
7                  Argentina  Temperate  Southern hemisphere  Soybean  2010   
2                  Argentina  Temperate  Southern hemisphere  Soybean  2002   
5                  Argentina  Temperate  Southern hemisphere    Maize  2010   
11  United States Of America  Temperate  Northern hemisphere  Soybean  2010   

                    Actual                             Predicted      error  \
18                      8.856633                         8.709798   1.657906   
22                     10.277621                        10.646027   3.584548   
7                       2.903666                         2.528243  12.929296   
2                       2.604214                         2.308457  11.356881   
5                       7.787116                         6.045908  22.360111   
11                      2.898108                         2.833479   2.230042   

     f-score  
18  0.574185  
22  0.711111  
7   0.189560  
2   0.269231  
5   0.709091  
11  0.627960  

我想按裁剪总结上面的示例数据框,同时按年份求平均值。我正在这样做:

df[['Actual', 'Predicted']].groupby(df[['Crop', 'Years']]).mean()

但是,我收到此错误: *** ValueError: '' 的石斑鱼不是一维的

如何解决这个问题?

最佳答案

df[['Actual', 'Predicted']] 只有两列(ActualPredicted),因此您无法分组该数据框由 CropYears 组成。

我认为您首先需要按裁剪和年份进行分组,然后选择要计算平均值的列:

df.groupby(['Crop', 'Years'])[['Actual', 'Predicted']].mean()

关于python - 对 pandas 数据框进行分组,同时对某些列中的值进行平均,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48194545/

相关文章:

python - 使图表更大

python - 为什么我用setup.py安装ansible找不到?

python - Elasticsearch 无法将来自 pymongo 的日期时间字段解析为对象

python - PyImport_ImportModule,可以从内存中加载模块吗?

python - 在 PyDev 中执行默认的 .py 文件

比较字符串和 strftime 值时,运算符中的 Python 无法按预期工作

python - 基于列名在 pandas 数据框的 lambda 表达式上使用 if else 语句

python - 视频流变得失真的QImage

python - 何时在 Pandas 中使用 .count() 和 .value_counts()?

python - 基于每个组在 pandas 列中填充值的高效而优雅的方法