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)
Example of what the result should look like:
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
The result should look like:
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…