1

How can I add columns of two dataframes (A + B), so that the result (C) takes into account missing values ('---')?

DataFrame A

a = pd.DataFrame({'A': [1, 2, 3, '---', 5]})

    A
0   1
1   2
2   3
3   ---
4   5

DataFrame B

b = pd.DataFrame({'B': [3, 4, 5, 6, '---']})

    B
0   3
1   4
2   5
3   6
4   ---

Desired Result of A+B

    C
0   4
1   6
2   8
3   ---
4   ---
2
  • Is it important for the value of your missing value to be indicated by "---"? Commented Apr 11, 2019 at 20:01
  • yes, that's how i get it delivered Commented Apr 11, 2019 at 20:02

1 Answer 1

3

Replace the '---' with np.nan, add the columns and fillna with '---'

(a['A'].replace('---', np.nan)+b['B'].replace('---', np.nan)).fillna('---')

You can assign the result to a new dataframe or an existing one:

df = pd.DataFrame()
df.assign(C = (a['A'].replace('---', np.nan)+b['B'].replace('---', np.nan)).fillna('---'))

OR

a.assign(C = (a['A'].replace('---', np.nan)+b['B'].replace('---', np.nan)).fillna('---'))
Sign up to request clarification or add additional context in comments.

2 Comments

Result is no dataframe anymore
This is a series, the result can be assigned to a new data frame or an existing one

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.