gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
for a dataframe clean the column value like remove . - space
- User
for a dataframe clean the column value like remove . - space
- Assistant
To clean a column in a Pandas DataFrame by removing
.,-, and spaces from the string values, you can use thestr.replace()method with a regular expression. Here's an example:pythonimport pandas as pd # Sample DataFrame df = pd.DataFrame({ 'column_name': ['12.34-56', '78 90-12', '34. 56-78'] }) # Remove '.', '-' and spaces from the column values df['column_name'] = df['column_name'].str.replace(r'[.\-\s]', '', regex=True) print(df)Explanation:
r'[.\-\s]'is a regex pattern that matches any.,-, or whitespace character.str.replace(pattern, '', regex=True)replaces all occurrences of the pattern with an empty string (effectively removing them).
Output:
codecolumn_name 0 123456 1 789012 2 345678Let me know if you want to clean other characters or handle non-string values!
- User
use apply function
- Assistant
Certainly! You can also use the
applyfunction with a lambda to clean the column values by removing.,-, and spaces. Here's how you can do it:pythonimport pandas as pd # Sample DataFrame df = pd.DataFrame({ 'column_name': ['12.34-56', '78 90-12', '34. 56-78'] }) # Using apply with a lambda function and str.replace df['column_name'] = df['column_name'].apply(lambda x: x.replace('.', '').replace('-', '').replace(' ', '')) print(df)Explanation:
.apply(lambda x: ...)applies the lambda function to every element in the column.- Inside the lambda, we chain
.replace()calls to remove.,-, and spaces.
Output:
codecolumn_name 0 123456 1 789012 2 345678If you want a more concise approach with regex inside
apply, you can also do: