如何使用mask(掩码)合并Phone 1与Phone 2两列数据?
Got it! Since you already have that 0/1 mask column, merging your Phone1 and Phone2 columns into a single phone column is totally straightforward. We can use the mask to conditionally pick values from either column—let's use pandas (the go-to tool for tabular data) to walk through this with your simulated data.
Step 1: Set up sample data
First, let's replicate your scenario with some mock data:
import pandas as pd # Simulate your dataset df = pd.DataFrame({ 'Phone1': ['123-456-7890', None, '987-654-3210', None], 'Phone2': [None, '555-1234', None, '555-4321'], 'mask': [1, 0, 1, 0] # Assume mask=1 means use Phone1, mask=0 means use Phone2 })
Step 2: Merge columns with the mask
You have two simple, clean ways to do this:
Option 1: Use numpy.where
This is super intuitive—it works like an inline if-else:
import numpy as np # When mask is 1, take Phone1; else take Phone2 df['phone'] = np.where(df['mask'] == 1, df['Phone1'], df['Phone2'])
Option 2: Use pandas' built-in where method
Pandas has its own where function that does the same thing, with a slightly different syntax:
# Keep Phone1 where mask is 1, otherwise replace with Phone2 df['phone'] = df['Phone1'].where(df['mask'] == 1, df['Phone2'])
Step 3: Check the result
Running either of the above will give you your desired phone column:
print(df) # Output: Phone1 Phone2 mask phone 0 123-456-7890 None 1 123-456-7890 1 None 555-1234 0 555-1234 2 987-654-3210 None 1 987-654-3210 3 None 555-4321 0 555-4321
Bonus: Handle edge cases (optional)
If you want to fall back to the other phone number when your selected column is empty, you can add a fillna layer:
# Use mask to pick primary column, then fill empty values with the other column df['phone'] = np.where( df['mask'] == 1, df['Phone1'].fillna(df['Phone2']), df['Phone2'].fillna(df['Phone1']) )
Just adjust the mask condition (e.g., df['mask'] == 0) if your mask logic is reversed (0 means use Phone1 instead of 1).
内容的提问来源于stack exchange,提问作者Yun Tae Hwang

