如何使用barcode_x列填充barcode_y列的NaN与空值?
barcode_y with barcode_x Values Hey there! Let's tackle this data cleaning task you've got. You want to fill in the missing (NaN or empty) values in your barcode_y column using the corresponding values from barcode_x—this is a really common job in pandas, and it's totally straightforward with a couple of reliable methods.
Method 1: Use fillna() (Most Direct)
The fillna() method in pandas is built exactly for this kind of task. It lets you replace NaN values in a column with values from another column directly.
Here's how to do it:
import pandas as pd # Assuming your data is loaded into a DataFrame called df df['barcode_y'] = df['barcode_y'].fillna(df['barcode_x'])
If your "empty values" are actually empty strings ("") instead of pandas NaNs, just convert those to NaNs first, then fill:
# Convert empty strings to NaN df['barcode_y'] = df['barcode_y'].replace("", pd.NA) # Now fill the missing values df['barcode_y'] = df['barcode_y'].fillna(df['barcode_x'])
Method 2: Use combine_first()
Another great option is combine_first(), which works by taking values from the specified column to fill gaps in the target column. The result is identical to using fillna() here:
df['barcode_y'] = df['barcode_y'].combine_first(df['barcode_x'])
Let's Test with Your Sample Data
Let's walk through applying this to your exact data to get the expected result:
First, construct the original DataFrame (fixing the minor formatting issue in your input):
data = { 'id': [7068, 7068, 7068, 7116, 7154, 7342], 'barcode_x': [38927887, 38927895, 39111141, 73094237, 37645215, 86972909], 'barcode_y': [38927895, 38927895, 38927895, pd.NA, 37645215, pd.NA], 'A': [0, 0, 0, 18, 0, 7], 'B': [12, 1, 4, 309, 9, 25] } df = pd.DataFrame(data)
Run the fill operation:
df['barcode_y'] = df['barcode_y'].fillna(df['barcode_x'])
Now if you print the DataFrame, you'll get exactly the output you're looking for:
id barcode_x barcode_y A B 0 7068 38927887 38927895 0 12 1 7068 38927895 38927895 0 1 2 7068 39111141 38927895 0 4 3 7116 73094237 73094237 18 309 4 7154 37645215 37645215 0 9 5 7342 86972909 86972909 7 25
Extra Note
If your data has other placeholder values for missing data (like the string "NA" or "missing"), just use replace() to turn those into pandas NaNs first before running the fill operation—this ensures all gaps get covered.
内容的提问来源于stack exchange,提问作者Nabih Bawazir

