Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim Header values in pandas.read_csv

I'm reading a csv file using pandas.read_csv(). My csv file has headers with spaces at start or end like ' header1', 'header2 ' I want to trim that extra space at start/end. Is their a way to specify this using some arguments? If not how to achieve that in my resultant dataframe?

like image 200
DevLoverUmar Avatar asked Sep 14 '25 08:09

DevLoverUmar


1 Answers

You could try with this, after reading the csv:

df.columns =[col.strip() for col in df.columns]

Same as:

df.rename(columns=lambda x: x.strip(), inplace=True)

Or this too:

df.columns=df.columns.str.strip()
like image 125
MrNobody33 Avatar answered Sep 17 '25 00:09

MrNobody33