Pandas row-wise addition with another column

Viewed 116

I have a dataframe df

A   B   C
0.1 0.3 0.5
0.2 0.4 0.6
0.3 0.5 0.7
0.4 0.6 0.8
0.5 0.7 0.9

For each row I would I would like to add a value to each element from dataframe df1

X  
0.1
0.2
0.3
0.4
0.5

Such that the final result would be

 A   B   C
 0.2 0.4 0.6
 0.4 0.6 0.8
 0.6 0.8 1.0
 0.8 1.0 1.2
 1.0 1.2 1.4

I have tried using df_new =df.sum(df1, axis=0), but got the following error TypeError: stat_func() got multiple values for argument 'axis' I would be open to numpy solutions as well

4 Answers

You can use np.add:

df = np.add(df, df1.to_numpy())
print(df)

Prints:

     A    B    C
0  0.2  0.4  0.6
1  0.4  0.6  0.8
2  0.6  0.8  1.0
3  0.8  1.0  1.2
4  1.0  1.2  1.4
import pandas as pd

df = pd.DataFrame([[0.1,0.3, 0.5],
                   [0.2, 0.4, 0.6],
                   [0.3, 0.5, 0.7],
                   [0.4, 0.6, 0.8],
                   [0.5, 0.7, 0.9]], 
                  columns=['A', 'B', 'C'])

df1 = [0.1, 0.2, 0.3, 0.4, 0.5]

# In one Pandas instruction
df = df.add(pd.Series(df1), axis=0)

results :

     A    B    C
0  0.2  0.4  0.6
1  0.4  0.6  0.8
2  0.6  0.8  1.0
3  0.8  1.0  1.2
4  1.0  1.2  1.4

Try concat with .stack() and .sum()

df_new = pd.concat([df1.stack(),df2.stack()],1).bfill().sum(axis=1).unstack(1).drop('X',1)

     A    B    C
0  0.2  0.4  0.6
1  0.4  0.6  0.8
2  0.6  0.8  1.0
3  0.8  1.0  1.2
4  1.0  1.2  1.4
df= pd.DataFrame([[0.1,0.3, 0.5],
                   [0.2, 0.4, 0.6],
                   [0.3, 0.5, 0.7],
                   [0.4, 0.6, 0.8],
                   [0.5, 0.7, 0.9]], 
                  columns=['A', 'B', 'C'])

df["X"]=[0.1, 0.2, 0.3, 0.4, 0.5]

columns_to_add= df.columns[:-1]

for col in columns_to_add:
    df[col]+=df['X'] #this is where addition or any other operation can be performed

df.drop('X',axis=0)
Related