Skip to content Skip to sidebar Skip to footer

How To Remove Space "before" Column Name When Importing Csv Data In Pandas

I use the default Pandas csv reading to import some data as followed: df = pd.read_csv('data_file.csv') The data frame I got is as below: Force [N] Stress [MPa] 0

Solution 1:

To avoid post-processing the column data set skipinitialspace=True to pd.read_csv:

df = pd.read_csv('data_file.csv', skipinitialspace=True)

df:

   Force [N]  Stress [MPa]00.0000002.230649e-1310.0141171.071518e-0120.1352553.365490e+00

df.columns:

Index(['Force [N]', 'Stress [MPa]'], dtype='object')

data_file.csv

          Force [N],      Stress [MPa]0.000000,       2.230649e-130.014117,       1.071518e-010.135255,      3.365490e+00

Solution 2:

A simpler alternative to the replace approach is rename:

df = df.rename(columns=str.strip)

or using inplace:

df.rename(columns=str.strip, inplace=True)

Solution 3:

pandas.Series.str.replace to replace occurrences of ^[ ]+|[ ]+$ (one or more spaces at the start or end of the column names) with "" (nothing)

df.columns = df.columns.str.replace("^[ ]+|[ ]+$", "", regex=True)

Solution 4:

You can use Index.str.strip() (which is the Index version of Series.str.strip()), as follows:

df.columns = df.columns.str.strip()

Input:

print(df.columns)

Index(['       Force [N]', '    Stress [MPa] '], dtype='object')

Output:

print(df.columns)

Index(['Force [N]', 'Stress [MPa]'], dtype='object')

Post a Comment for "How To Remove Space "before" Column Name When Importing Csv Data In Pandas"