'Adding three dataframes with the same amount of columns and rows to each other (NOT merge) in python pandas

I have three dataframes that have the same format and I want to simply add the three respective values on top of each other, so that df_new = df1 + df2 + df3. The new df would have the same amount of rows and columns as each old df.

But doing so only appends the columns. I have searched through the docs and there is a lot on merging etc but nothing on adding values. I suppose there must be a one liner for such a basic operation?



Solution 1:[1]

Possible solution is the following:

# pip install pandas

import pandas as pd

#set test dataframes with same structure but diff values
df1 = pd.DataFrame({"col1": [1, 1, 1], "col2": [1, 1, 1],})
df2 = pd.DataFrame({"col1": [2, 2, 2], "col2": [2, 2, 2],})
df3 = pd.DataFrame({"col1": [3, 3, 3], "col2": [3, 3, 3],})

enter image description here

df_new = pd.DataFrame()

for col in list(df1.columns):
    df_new[col] = df1[col].map(str) + df2[col].map(str) + df3[col].map(str)

df_new

Returns

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1