pandas :当列相等时获取不同行的均值 [英] Pandas: Get mean of different rows when columns are equal

查看:78
本文介绍了 pandas :当列相等时获取不同行的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找不同行中的值的均值,并按其他列中的相似性进行分组.示例:

I'm trying to find the mean of values in different rows, grouped by similarities in other columns. Example:

In [14]: pd.DataFrame({'col1':[1,2,1,2], 'col2':['A','C','A','B'], 'col3':[1, 5, 6, 9]})
Out[14]: 
   col1 col2  col3
0     1    A     1
1     2    C     5
2     1    A     6
3     2    B     9

我想为col1和col2组合匹配的所有行添加带有col3方式的列.所需的输出:

What I would like is to add a column with the means of col3, for all rows where the combination of col1 and col2 match. Desired output:

Out[14]: 
   col1 col2  col3   mean
0     1    A     1    3.5
1     2    C     5    5
2     1    A     6    3.5
3     2    B     9    9

我曾尝试将groupbyapply结合使用,但无法获得正确的结果.

I have tried several things with groupby in combination with apply but couldn't get proper results.

推荐答案

它是transform我的男人

df['mean'] = df.groupby(['col1','col2']).col3.transform('mean')

这篇关于 pandas :当列相等时获取不同行的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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