0

I'm trying to merge two different columns within a data frame. So if you have columns A and B, and you want A to remain the default value unless it is empty. If it is empty you want to use the value for B.

pd.merge looks like it only works when merging data frames, not columns within an existing single data frame.

| A     | B    |

| 2     | 4    |
| NaN   | 3    | 
| 5     | NaN  |
| NaN   | 6    | 
| 7     | 8    |

Desired Result:

|A|

|2|
|3|
|5|
|6|
|7|
3
  • 2
    df['A'].fillna(df['B']) ? Add some data to this question and expected output. Commented Jun 9, 2020 at 20:46
  • 2
    I think your looking for this Commented Jun 9, 2020 at 20:47
  • I added a data table to illustrate what I'm trying to accomplish. Thank you for taking the time to answer! Commented Jun 9, 2020 at 21:15

1 Answer 1

1

Credit to Scott Boston for the comment on the OP:

import pandas as pd

df = pd.DataFrame( 
    {
        'A': [2, None, 5, None, 7], 
        'B': [4, 3, None, 6, 8] 
    } 
)

df.head()
"""
     A    B
0  2.0  4.0
1  NaN  3.0
2  5.0  NaN
3  NaN  6.0
4  7.0  8.0
"""

df['A'] = df['A'].fillna(df['B'])

df.head()
"""
     A    B
0  2.0  4.0
1  3.0  3.0
2  5.0  NaN
3  6.0  6.0
4  7.0  8.0
"""
Sign up to request clarification or add additional context in comments.

2 Comments

So question about this, it works but what do I use if the cell's value is "-"?
You could do something along the lines of df.loc[df['A'] == '-', 'A'] = df.loc[df['A'] == '-', 'B'] In short, wherever A == '-', it will replace with the value in column B`.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.