Lets say i have a dataframe with two columns: OldValue and NewValue
i want to do some plotting and i want to combine values. If OldValue is empty, NewValue is filled, and the other way around. There is not a single instance both or neither are filled. Lets say my dataframe looks like this:
OldValue NewValue
0 14.0 NaN
1 NaN 7.0
2 3.0 NaN
3 NaN 3.0
I found that i could fillna(0) and then do something along the lines of
df["AllValue"] = df["NewValue"] df["OldValue"]
Is this the most efficient way?
CodePudding user response:
Your solution should be change with Series.add
and fill_value=0
:
df["AllValues"] = df["Newvalues"].add(df["OldValues"], fill_value=0)
Or use Series.fillna
:
df["AllValue"] = df["NewValue"].fillna(df["OldValue"])
CodePudding user response:
I think this will work:
df["AllValue"] = df["OldValue"] # make a copy
df.loc[df["AllValue"].isna(), "AllValue"] = df.loc[~df["NewValue"].isna(), "NewValue"]