-1

enter image description here hello guys. Hi guys. As you can see in the picture, when I tried to use the target column, I encountered a key error. I tried different ways but it did not work. When I type: y= train['Level'] or y= train[['Level']] or print (Train['Level']) or enc = OrdinalEncoder() enc.fit(Train['Level'])

and any other things about Level column this Error occured. how I can fix it? please help me "| enter image description here

Panah
  • 3
  • 3
  • Please provide enough code so others can better understand or reproduce the problem. – Community Jun 15 '22 at 12:47
  • so you mean that `Train['Level']` exists when you print it? Also please provide more details for example arent you trying to fit it with categories and transform on `Train['Level']`? At least show us what `Train` Looks like – demetere._ Jun 15 '22 at 12:47
  • it sounds like your `Train` does not contain `Level` column/key – Ach113 Jun 15 '22 at 12:48
  • @DemetreDzmanashvili Thank for your attention. I add train tabel in other picture – Panah Jun 15 '22 at 12:55
  • @Panah can you try `print(Train['Level']` and if an error still occurs try `print(Train.columns)` and show us the results. Thanks – demetere._ Jun 15 '22 at 12:56
  • @Ach113 no it's contain. I added other picture – Panah Jun 15 '22 at 12:56
  • @DemetreDzmanashvili I try that but still I got Error. this is result of `print(Train.columns)` :Index(['STG', 'SCG', 'STR', 'LPR', 'PEG', ' Level'], dtype='object') – Panah Jun 15 '22 at 12:59
  • @Panah as you can see `' Level'` contains space. now try `enc.fit(Train[' Level'])` and it will work but I suggest you fixing that name problem in the excel file – demetere._ Jun 15 '22 at 13:00

1 Answers1

0

When there is KeyError in dataframe you should always check for the columns by Train.columns because sometimes it may contain spaces or other characters that can not be seen by the eye so it would be good if you always checked for that.

I also want to add suggestions to your code, because you are trying to encode the target variable why don't use LabelEncoder instead of OrdinalEncoder?

the input for LabelEncoder is (n_samples,) that seems the case for you and the input for OrdinalEncoder is (n_samples, n_features). So I think you should use the first one.

Good Luck

demetere._
  • 268
  • 2
  • 10