如何用Pandas将DataFrame中phone1-phone7列的前置0替换为91
Solution for Formatting Phone Numbers in Pandas DataFrame
Hey there, let's solve this phone number formatting problem step by step. The goal is to replace the single leading 0 in columns phone1 through phone7 with 91, while keeping numbers with multiple leading zeros (like 00601731) unchanged.
Step 1: Identify Target Columns
First, let's define the list of phone columns we need to process:
import pandas as pd # Assuming your DataFrame is already loaded as df phone_columns = [f"phone{i}" for i in range(1, 8)]
Step 2: Process the Columns with Regex Replacement
We'll use a regular expression to target only numbers that start with a single 0 (not followed by another 0). Here's the cleanest approach:
# Convert columns to string type to handle numeric values properly df[phone_columns] = df[phone_columns].astype(str) # Use regex to replace single leading 0 with 91 df[phone_columns] = df[phone_columns].replace(r"^0(?!0)", "91", regex=True)
Regex Explanation:
^0: Matches a0at the start of the string(?!0): Negative lookahead, ensures the next character is not another0
This way, only numbers starting with exactly one0get modified—values like00601731are left untouched.
Step 3: Handle NaN Values (Optional)
If your DataFrame has NaN values, converting to string will turn them into the literal string "NaN". To preserve actual NaN values, use this adjusted code:
for col in phone_columns: # Only process non-null values mask = df[col].notna() df.loc[mask, col] = df.loc[mask, col].astype(str).replace(r"^0(?!0)", "91", regex=True)
Original vs. Expected Output
Original Data:
kac play_id phone1 phone2 phone3 phone4 phone5 phone6 phone7 0 0 5004490 20002075 0900031349 090891349 NaN NaN NaN NaN 1 1 5003807 00601731 088235311 NaN NaN NaN NaN NaN 2 2 5003808 00601731 088235311 NaN NaN NaN NaN NaN
After Processing:
kac play_id phone1 phone2 phone3 phone4 phone5 phone6 phone7 0 0 5004490 20002075 91900031349 9190891349 NaN NaN NaN NaN 1 1 5003807 00601731 9188235311 NaN NaN NaN NaN NaN 2 2 5003808 00601731 9188235311 NaN NaN NaN NaN NaN
内容的提问来源于stack exchange,提问作者Tilo
相关产品推荐
相关产品推荐

