简体   繁体   中英

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|

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM