1

I have several csv files which I want to process using Pandas. The complication is that every file has different header of the 1st column (its data should be read as string) and all other columns' values should be read as numbers.

I want to trim the trailing whitespaces in the values of the first column, but all solutions which I found:

  1. convert the whole dataframe in string format (this is not desirable)
  2. need the column name in order to trim only its values (as I said the title of this column is different in every file)

Is there any way in Pandas how to take the 1st column by position and to trim only the trailing spaces of its values?

1 Answers1

1

Use .iloc[:, 0] to select rows and columns by index position.
In this case .loc[:, 0] means: select all rows and select the first column.

To remove only the trailing spaces, use .str.rstrip()
If you want to remove both leading and trailing spaces, use .str.strip()

df.iloc[:, 0] = df.iloc[:, 0].astype(str).str.rstrip()

See also:
How to get the first column of a pandas DataFrame as a Series?

Sander van den Oord
  • 10,986
  • 5
  • 51
  • 96