Russell Comer
Russell Comer

Reputation: 23

Merging columns within a dataframe with pandas

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|

Upvotes: 0

Views: 57

Answers (1)

Caleb Courtney
Caleb Courtney

Reputation: 346

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
"""

Upvotes: 1

Related Questions