2

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?

1

2 Answers 2

4

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"])
Sign up to request clarification or add additional context in comments.

Comments

1

I think this will work:

df["AllValue"] = df["OldValue"]  # make a copy
df.loc[df["AllValue"].isna(), "AllValue"] = df.loc[~df["NewValue"].isna(), "NewValue"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.