按 pandas 中相同的列名称分组 [英] Grouping on identical column names in pandas

查看:102
本文介绍了按 pandas 中相同的列名称分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

time       A1    A1    A2    A2     A2    A3   A3 
2017-01    a1    a2    b1    b2      c    .....
2017-02    a3    a4    b3    b4      c
2017-03    a5    a6    b5    b6      c
....

有一个如上所述的数据框.如何获得具有相同名称的列的平均值(如下所示)?

There is a dataframe as shown above. How to get mean value of the columns which have the same name( as shown below)?

time            A1             A2           A3
2017-01    (a1+a2)/2       (b1+b2+c)/3      c
2017-02     .....
2017-03 

推荐答案

groupbylevel=0axis=1一起使用.

df.groupby(level=0, axis=1).mean()


np.random.seed(0)
df = pd.DataFrame(np.random.choice(10, (3, 5)), columns=list('AAABB'))

df

   A  A  A  B  B
0  5  0  3  3  7
1  9  3  5  2  4
2  7  6  8  8  1

df.groupby(level=0, axis=1).mean()

          A    B
0  2.666667  5.0
1  5.666667  3.0
2  7.000000  4.5

这篇关于按 pandas 中相同的列名称分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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