Python中多列出生日期(DOB)比对并返回重复值的简化实现方案咨询
Great question! Your current np.select approach works perfectly for 3 DOB columns, but it quickly becomes unwieldy if you ever need to add more columns. Here's a flexible, scalable method that works no matter how many DOB columns you have:
Step 1: Define your target columns
First, we'll identify all the DOB columns in your DataFrame (adjust the matching logic if your column names follow a different pattern):
import pandas as pd # Identify all columns starting with "DOB_" dob_cols = [col for col in df.columns if col.startswith('DOB_')]
Step 2: Create a row-wise processing function
We'll write a function that checks each row to find values that appear at least twice, ignoring invalid entries like NaN or "Did not report":
def get_valid_dob(row): # Filter out nulls and non-report entries valid_dobs = [val for val in row[dob_cols] if pd.notna(val) and val != "Did not report"] # Count how often each valid DOB appears dob_counts = pd.Series(valid_dobs).value_counts() # Grab the first value that occurs 2+ times (if any) frequent_dobs = dob_counts[dob_counts >= 2] return frequent_dobs.index[0] if not frequent_dobs.empty else "To check manually"
Step 3: Apply the function to your DataFrame
Finally, we'll apply this function to every row to create the DOB_Check column:
df['DOB_Check'] = df.apply(get_valid_dob, axis=1)
Why this works better
- Scalability: Add as many DOB columns as you want—no need to update conditional logic.
- Robustness: Automatically handles
NaNand "Did not report" entries without extra conditionals. - Readability: The logic is straightforward, making it easier to modify later (e.g., if you need to adjust what counts as an invalid entry).
Verification
Running this code on your sample dataset will produce exactly the output you're expecting:
| Name | DOB_1 | DOB_2 | DOB_3 | DOB_Check |
|---|---|---|---|---|
| Ann | 20.05.19 | 20.05.19 | 20.05.19 | 20.05.19 |
| Ben | 31.10.16 | 30.10.16 | 30.10.16 | 30.10.16 |
| Clara | 28.04.16 | 22.04.16 | 29.05.16 | To check manually |
| Des | NaN | 09.06.20 | 09.06.20 | 09.06.20 |
| Ein | Did not report | 09.07.97 | 09.07.97 | 09.07.97 |
内容的提问来源于stack exchange,提问作者Melon123

