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

问题描述

是否有一种使用类似于pd.concat([df1, df2, df3, df4])的语法对多个熊猫DataFrame求和的方法.我从文档中了解到我可以做到df1.sum(df2, fill_value=0),但是我有一长串需要汇总的DataFrame,并且想知道是否可以在不编写循环的情况下做到这一点.

Is there a way to sum multiple pandas DataFrames using syntax similar to pd.concat([df1, df2, df3, df4]). I understand from documentation that I can do df1.sum(df2, fill_value=0), but I have a long list of DataFrames I need to sum and was wondering if I could do it without writing a loop.

一些相关的问题/答案:熊猫对多个数据帧求和(堆栈溢出)

Somewhat related question/answer: Pandas sum multiple dataframes (Stack Overflow)

结果应为以下示例:

idx1 = pd.MultiIndex.from_tuples([('a', 'A'), ('a', 'B'), ('b', 'A'), ('b', 'D')])
idx2 = pd.MultiIndex.from_tuples([('a', 'A'), ('a', 'C'), ('b', 'A'), ('b', 'C')])
idx3 = pd.MultiIndex.from_tuples([('a', 'A'), ('a', 'D'), ('b', 'A'), ('b', 'C')])

np.random.seed([3,1415])
df1 = pd.DataFrame(np.random.randn(4, 1), idx1, ['val'])
df2 = pd.DataFrame(np.random.randn(4, 1), idx2, ['val'])
df3 = pd.DataFrame(np.random.randn(4, 1), idx3, ['val'])

df1

df2

df3

结果应类似于:

推荐答案

reduce add ,参数为fill_value=0:

np.random.seed(12)

a = pd.DataFrame(np.random.randint(3, size=(5,3)), columns=list('abc'))
b = pd.DataFrame(np.random.randint(3, size=(5,2)), columns=list('ab'))
c = pd.DataFrame(np.random.randint(3, size=(5,2)), columns=list('ac'))
print(a)
   a  b  c
0  2  1  1
1  2  0  0
2  2  1  0
3  1  1  1
4  2  2  2

print(b)
   a  b
0  0  1
1  0  0
2  1  2
3  1  2
4  0  1

print(c)
   a  c
0  2  0
1  2  2
2  2  0
3  0  2
4  1  1


from functools import reduce

dfs = [a,b, c]
d = reduce(lambda x, y: x.add(y, fill_value=0), dfs)
print (d)
   a    b    c
0  4  2.0  1.0
1  4  0.0  2.0
2  5  3.0  0.0
3  2  3.0  3.0
4  3  3.0  3.0

这篇关于对 pandas 数据框列表求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 03:23