Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove space "before" column name when importing csv data in Pandas

Tags:

python

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            0.000000       2.230649e-13
1            0.014117       1.071518e-01
2            0.135255       3.365490e+00

The data frame column I got here has spaces before the actual name (illustrated below) so that I could not use the actual column name string to access the column afterwards.

>>> df.columns
Index(['       Force [N]', '    Stress [MPa] '])

I would like to remove the space before the string, but keep the space within the column name string. Tried the following one but it will remove all spaces so the column name got changed as well.

df.columns=df.columns.str.replace(' ','');

Is there anyway to strip the white spaces to the left of column name when importing csv? I would like the column name to be like:

'Force [N]','Stress [MPa]'
like image 406
Kai03 Avatar asked Nov 04 '25 16:11

Kai03


1 Answers

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]
0   0.000000  2.230649e-13
1   0.014117  1.071518e-01
2   0.135255  3.365490e+00

df.columns:

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

data_file.csv

          Force [N],      Stress [MPa] 
          0.000000,       2.230649e-13
          0.014117,       1.071518e-01
          0.135255,      3.365490e+00
like image 100
Henry Ecker Avatar answered Nov 07 '25 10:11

Henry Ecker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!