strip dataframe column pandas in python

To strip unwanted characters from a pandas dataframe column, you can use the str.strip() method. This method removes the leading and trailing whitespaces or any other specified characters from each element in the given series.

Here is an example of how to use str.strip() to remove whitespaces from a specific column of a pandas dataframe:

main.py
import pandas as pd

# Create a sample dataframe
df = pd.DataFrame({'col_1': ['     apple', 'banana      ', '    cherry     ']})

# Remove whitespace from the 'col_1' column
df['col_1'] = df['col_1'].str.strip()

# View the updated dataframe
print(df)
252 chars
11 lines

This code will output the following:

main.py
    col_1
0   apple
1  banana
2  cherry
40 chars
5 lines

As you can see, the leading and trailing whitespaces from each element in the 'col_1' column have been removed.

gistlibby LogSnag