trob
trob

Reputation: 407

Pandas: operations with nans

Suppose I produce the following using pandas:

df = pd.DataFrame(np.ones(25).reshape((5,5)),index = ['A','B','C','D','E'])
df1 = pd.DataFrame(np.ones(25).reshape((5,5))*2,index = ['A','B','C','D','E'])
df[2] = np.nan
df1[3] = np.nan
df[4] = np.nan
df1[4] = np.nan
df2 = df+df1
print(df2)

     0    1   2   3   4
A  3.0  3.0 NaN NaN NaN
B  3.0  3.0 NaN NaN NaN
C  3.0  3.0 NaN NaN NaN
D  3.0  3.0 NaN NaN NaN
E  3.0  3.0 NaN NaN NaN

What do I have to do to get this instead?

    0   1   2   3     4
A   3   3   2   1   NaN
B   3   3   2   1   NaN
C   3   3   2   1   NaN
D   3   3   2   1   NaN
E   3   3   2   1   NaN

Upvotes: 1

Views: 254

Answers (1)

user2285236
user2285236

Reputation:

Use the fill_value argument of the DataFrame.add method:

fill_value : None or float value, default None Fill missing (NaN) values with this value. If both DataFrame locations are missing, the result will be missing.

df.add(df1, fill_value=0)
Out: 
     0    1    2    3   4
A  3.0  3.0  2.0  1.0 NaN
B  3.0  3.0  2.0  1.0 NaN
C  3.0  3.0  2.0  1.0 NaN
D  3.0  3.0  2.0  1.0 NaN
E  3.0  3.0  2.0  1.0 NaN

Upvotes: 3

Related Questions