0

I have the following code:

import pandas as pd
df = pd.read_csv("myfile.csv", sep=';', header=0, encoding='latin_1')

The content of my CSV separted by semicolon

num_report; date_hour_ocorrence; Nº_involved; conductor; cod_severity; 
2019-007782512-001;18/02/2019 19:24;3;Y;1
2019-007782515-001;20/02/2019 08:44;4;N;3

But when I try do this:

df.loc[df['conductor'] == 'S']

I got the error

KeyError: 'conductor'

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Leonardo Lima
  • 586
  • 1
  • 6
  • 20
  • 2
    It looks like your column is `' conductor'` note the leading whitespace. – Henry Ecker Jun 19 '21 at 23:31
  • @HenryEcker thats it!!! do you know how can I filter my header eliminating white spaces? is that an encoding type? – Leonardo Lima Jun 19 '21 at 23:35
  • Take a look at your input file. The split delimiter is ';' and there is whitespace on the header row that is not present in other rows. You could fix that row or – Henry Ecker Jun 19 '21 at 23:36
  • `df.columns = df.columns.str.strip()` should work to programmatically strip after reading in the DataFrame or add `, skipinitialspace=True` to `read_csv` to skip leading whitespace after the separator. Take a look at the duplicate below: – Henry Ecker Jun 19 '21 at 23:36

0 Answers0