首页 > 解决方案 > 在 pandas Dataframe 上获取具有多个条件(按列)的平均值

问题描述

我最近开始使用熊猫,但找不到答案。(也许只是因为我不知道要搜索的查询词)

这是示例代码

test1 = {'col1' : ["A","A","A","A","B","B","B","B"],
         'col2' : ["C","D","C","D","C","D","C","D"],
         'year' :["2012","2012","2013","2013","2012","2012","2013","2013"],
         'value' : [3,4,25,1,3,2,1,3]}
df_t = pd.DataFrame(data=test1)
df_t

在这个 DataFrame 中,我想在某些条件下计算值的平均值。col1 和 col2 应该耦合(因为它是贸易数据),所以我想要得到的是

Mean value of years of 'A(col1)', 'C(col2)'
Mean value of years of 'A', 'D'
Mean value of years of 'B', 'C'
...
etc.

因此,我想要一个带有 'col1'、'col2'、'mean_value' 列的新 DataFrame。但我想如果有人教我如何在上述条件下获得平均值,我可以处理它。

如果有人能启发我,那将不胜感激。

感谢您的兴趣!

有一个美好的一天。

标签: python-3.xpandasdataframe

解决方案


尝试df_t.groupby(['col1', 'col2'])['value'].mean().reset_index()

  col1 col2  value
0    A    C   14.0
1    A    D    2.5
2    B    C    2.0
3    B    D    2.5

推荐阅读