pandas 数据帧列表的元素均值 [英] Element-wise mean of a list of pandas DataFrames

查看:54
本文介绍了 pandas 数据帧列表的元素均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种规范的方法来计算具有相同列和索引的 DataFrame 列表的元素均值?

Is there a canonical way to compute the element-wise mean of a list of DataFrames with identical columns and indices?

我能想到的最好方法是

from functools import reduce

dfs = [df1, df2, df3, df4, df5]  
reduce(lambda x, y: x.add(y), dfs) / len(dfs)

推荐答案

使用 concatmean 每个索引值:

df1 = pd.DataFrame({
         'C':[7,8,9],
         'D':[1,3,5],

})
df2 = pd.DataFrame({
         'C':[4,2,3],
         'D':[7,1,0],

})
df3 = pd.DataFrame({
         'C':[9,4,2],
         'D':[1,7,1],

})

from functools import reduce

dfs = [df1, df2, df3]  
df = reduce(lambda x, y: x.add(y), dfs) / len(dfs)
print (df)
          C         D
0  6.666667  3.000000
1  4.666667  3.666667
2  4.666667  2.000000

df = pd.concat(dfs).mean(level=0)
print (df)
          C         D
0  6.666667  3.000000
1  4.666667  3.666667
2  4.666667  2.000000

这篇关于 pandas 数据帧列表的元素均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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