Search code examples
pythonstringpandasheaderwhitespace

Remove all whitespace in the header of a dataframe in pandas


I have the following dataframe:

         eff,       par 0,       par 1,       par 2,       par 3,       par 4,       par 5,       par 6,       par 7,       par 8,       par 9,       par10,       par11,       par12,       par13,       par14 
-0.133,0.989,0.554,5.524,                 NaN,0.000,0.702,0.500,-4.556,266.644,-1.635,5.764,1.351,0.561,0.013,775.924
-0.133,0.989,0.554,5.524,                 NaN,0.000,0.702,0.500,-4.556,266.644,-1.635,5.764,1.351,0.561,0.013,775.924
-0.133,0.989,0.554,5.524,                 NaN,0.000,0.702,0.500,-4.556,266.644,-1.635,5.764,1.351,0.561,0.013,775.924

As you can noticed, there are a lot of whitespace in the header of the dataframe which are very unpractical in managing columns. As a consequence, I would like to remove them in order to have the following dataframe:

eff,par 0,par 1,par 2,par 3,par 4,par 5,par 6,par 7,par 8,par 9,par10,par11,par12,par13,par14 
-0.133,0.989,0.554,5.524,                 NaN,0.000,0.702,0.500,-4.556,266.644,-1.635,5.764,1.351,0.561,0.013,775.924
-0.133,0.989,0.554,5.524,                 NaN,0.000,0.702,0.500,-4.556,266.644,-1.635,5.764,1.351,0.561,0.013,775.924
-0.133,0.989,0.554,5.524,                 NaN,0.000,0.702,0.500,-4.556,266.644,-1.635,5.764,1.351,0.561,0.013,775.924

Do you know some easy and smart command or I have to do a cycle on the header and to apply a sort of "strip".

Thanks for any kind of help Best


Solution

  • You can use rename:

    df.rename(columns=lambda x: x.strip())