How to remove leading/trailing white spaces in pandas?

Published on Aug. 22, 2023, 12:18 p.m.

To remove leading/trailing white spaces from column names in pandas, you can use the str.strip() method on the column names. Here’s an example:

import pandas as pd

# create a sample dataframe
df = pd.DataFrame({' Column A ': [1, 2, 3], ' Column B ': ['a', 'b', 'c']})

# strip leading/trailing spaces from column names
df.columns = df.columns.str.strip()

print(df)

This will output the DataFrame with the column names stripped of any leading or trailing spaces:

   Column A Column B
0         1        a
1         2        b
2         3        c

Note that str.strip() returns a new object with the spaces removed, it does not modify the original object in place. Additionally, the str.strip() method only works on string columns, so if you have columns with non-string data types, you may need to convert them to strings first or use a different method to remove the spaces.

Tags: