DataFrame手机号列空格替换求助:将第6位空格替换为数字8
Let's break down what went wrong and how to fix your mobile number issue:
Why Your Original Code Failed
Your code df["Mobile No"] = df["Mobile No"].str.replace(' ', ' ') does two unhelpful things:
- It replaces spaces with identical spaces—so no actual change happens to your data.
- If your "Mobile No" column wasn't stored as a string type (e.g., it was an integer), using the
.straccessor would convert all values toNaN, since numeric types don't support string operations directly.
Step-by-Step Solution
First, ensure your column is treated as string data to avoid NaN issues:
# Convert the column to string type df["Mobile No"] = df["Mobile No"].astype(str)
Then, use one of these methods to replace the 6th-position space with an 8:
Method 1: Regular Expression (Clean & Concise)
This regex targets exactly the pattern you described: 5 characters, followed by a space, then 4 characters. It replaces the space with an 8:
df["Mobile No"] = df["Mobile No"].str.replace(r'^(.{5}) (.{4})$', r'\18\2', regex=True)
^(.{5}): Captures the first 5 characters: Matches the space at the 6th position(.{4})$: Captures the last 4 characters\18\2: Replaces the match with the first captured group, an 8, then the second captured group
Method 2: Custom Function (More Explicit)
If you prefer clearer control over the logic, use apply() with a function that checks for the space and fixes it:
def repair_mobile_number(phone): # Check if the number has a space at the 6th position (index 5, 0-based) if len(phone) == 10 and phone[5] == ' ': return phone[:5] + '8' + phone[6:] # Return unchanged if no space found return phone df["Mobile No"] = df["Mobile No"].apply(repair_mobile_number)
Example Test
For your sample number '88888 8888', both methods will convert it to '8888888888' as expected.
内容的提问来源于stack exchange,提问作者Optimizer

