KeyError: 'метка [india \ n] отсутствует в [index]' - PullRequest
0 голосов
/ 27 апреля 2020

Я создаю чат-бота, где я извлекаю название страны из текстового виджета и печатаю статистику страны. Я создал DataFrame с именем df_country с названием страны в качестве индекса. если я передаю название страны в виде жестко запрограммированного значения в качестве индекса DataFrame, он печатает статистику, но если я пытаюсь передать его как переменную с именем страны, извлеченным из текстового виджета, я получаю сообщение об ошибке.

--------------- Код --------------------

master=Tk() 
frm_up=Frame(master)
frm_up.pack(expand=1, fill=BOTH)
frm_dwn=Frame(master)
frm_dwn.pack(side=BOTTOM)
chatlog=Text(frm_up, state=DISABLED,yscrollcommand= scrollbar.set)
chatlog.pack(fill=BOTH,expand=1)
enter_message=Text(frm_dwn, height=5)
enter_message.pack(side = LEFT, expand=1, fill=X)
cntry=enter_message.get('1.0',END)
enter_message.delete('1.0',END)
chatlog.config(state=NORMAL)
chatlog.insert(END,'YOU : '+'Country name entered - '+cntry+'\n\n')
print(df_country.loc[cntry.lower()].to_string()) 
#passing country name say'India' in place of the variable cntry above,it works fine
#The issue may be that the variable cntry is of type **class 'str'** but we need **str** here
chatlog.config(state=DISABLED)

- -------- Ошибка ------------

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Ejaz\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1506, in _has_valid_type
    error()
  File "C:\Users\Ejaz\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [india\n] is not in the [index]'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Ejaz\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "<ipython-input-13-8ded476435b7>", line 237, in countrywise
    print(df_country.loc[cntry.lower()].to_string()) #cntry is <class 'str'>, hence failing here
  File "C:\Users\Ejaz\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1373, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "C:\Users\Ejaz\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1626, in _getitem_axis
    self._has_valid_type(key, axis)
  File "C:\Users\Ejaz\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1514, in _has_valid_type
    error()
  File "C:\Users\Ejaz\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1501, in error
    axis=self.obj._get_axis_name(axis)))
KeyError: 'the label [india\n] is not in the [index]'

1 Ответ

0 голосов
/ 27 апреля 2020

Комментарий в вашем коде говорит, что вы ищете такой ключ, как, например, «Индия». Однако переменная в print(df_country.loc[cntry.lower()].to_string())
, кажется, разрешается в india\n, то есть все в нижнем регистре, а также имеет трейлинг символ перевода строки.
Возможно, если вы убедитесь, что значение переменной соответствует ожидаемому имени столбца df, оно будет работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...