Element-wise mean of a list of pandas DataFrames

感情迁移 提交于 2021-02-10 06:29:06

问题


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

The best way I can think of is

from functools import reduce

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

回答1:


Use concat with mean per index values:

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


来源:https://stackoverflow.com/questions/58485109/element-wise-mean-of-a-list-of-pandas-dataframes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!