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]'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With