Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove whitespace from df column headers (strip isn't working)

Tags:

python

pandas

I've seen this question asked a few times, but the suggested answers don't seem to be working for me. I've brought in a csv with read_csv and am trying to clean up the names, which are initially:

In [89]: data.columns
Out[89]: 
Index(['Node Number', 'X [ m ]', 'Y [ m ]', 'Z [ m ]',
       'Turbulence Kinetic Energy [ m^2 s^-2 ]', 'turbulenceIntensity',
       'Velocity u [ m s^-1 ]', 'Velocity v [ m s^-1 ]',
       'Velocity w [ m s^-1 ]', 'windspeedratio'],
      dtype='object')

The simplest suggestion I've found should be:

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

But if I try that, absolutely nothing changes. Same with

data.columns = data.columns.str.strip()

Any idea why?

like image 472
Benjamin Brannon Avatar asked Sep 06 '25 03:09

Benjamin Brannon


1 Answers

Seems like you need replace all ' ' to ''

df.columns.str.replace(' ','')
Out[103]: 
Index(['NodeNumber', 'X[m]', 'Y[m]', 'Z[m]',
       'TurbulenceKineticEnergy[m^2s^-2]', 'turbulenceIntensity',
       'Velocityu[ms^-1]', 'Velocityv[ms^-1]', 'Velocityw[ms^-1]',
       'windspeedratio'],
      dtype='object')
like image 116
BENY Avatar answered Sep 07 '25 21:09

BENY