jay
jay

Reputation: 1463

Deleting extra space in column names in pandas

I have a sample dataframe called df with following column names;

col_names=[' 24- hour Indicator Yes/No', 'Time of Transaction', ' Date of Transaction']

As you can see some values are misaligned, for example extra space at the beginning or end of the string, say ' 24- hour Indicator Yes/No'. Is it possible to do some data cleaning in order to get rid of that unwanted space in column names. My present approach is right now manual;

df['Date of Transaction']  = df[' Date of Transaction']
df.drop(columns=[' Date of Transaction'],\
          axis=1,inplace=True)

But it will be nice to have a function in order to avoid reassigning values and dropping columns. Kindly advise.

Upvotes: 0

Views: 66

Answers (2)

Ricardo
Ricardo

Reputation: 128

You can use lstrip() in column names, it will remove leading spaces:

df.columns.str.lstrip()

Upvotes: 1

drec4s
drec4s

Reputation: 8077

You can use the rename function:

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

Upvotes: 2

Related Questions