如何在Pandas中替换DataFrame内含两个以上空格的单元格值为空
Hey there! Let's fix that DataFrame cleaning issue you're dealing with. You need to scrub the LastName column, replacing any values that have two or more spaces (like the Id14 entry in your example) with an empty string ''. Here's a straightforward way to get this done:
Step 1: Set up your sample DataFrame (for demonstration)
First, let's replicate your scenario with a test DataFrame so you can see how the solution works:
import pandas as pd # Sample data with an invalid LastName (Id14 has multiple spaces) df = pd.DataFrame({ 'Id': ['Id1', 'Id2', 'Id14', 'Id5'], 'FirstName': ['John', 'Jane', 'Bob', 'Alice'], 'LastName': ['Doe', 'Smith', 'Van der Sar', 'Brown'] # Notice the extra spaces here })
Step 2: Clean the LastName column
We'll use apply() to iterate over each value in the LastName column, count the total number of spaces, and replace values with 2+ spaces with an empty string. This method works for any two or more spaces total (whether consecutive or spread out):
# Replace LastName values with 2+ spaces (total count) df['LastName'] = df['LastName'].apply(lambda x: '' if x.count(' ') >= 2 else x)
If you specifically want to target consecutive two+ spaces (instead of total spaces), you can use a regex approach with replace():
# Replace values with consecutive two+ spaces df['LastName'] = df['LastName'].replace(r'.*\s{2,}.*', '', regex=True)
Step 3: Verify the cleaned result
After running either of the above code snippets, print the DataFrame to confirm the invalid value is replaced:
print(df)
You'll get this cleaned output:
Id FirstName LastName 0 Id1 John Doe 1 Id2 Jane Smith 2 Id14 Bob 3 Id5 Alice Brown
This approach directly addresses your requirement, and it's easy to tweak if you need to adjust the space-counting logic later.
内容的提问来源于stack exchange,提问作者Llewellyn Hattingh

