0

Имеется excel таблица, в которой часть данных я беру из другой таблицы, а часть прописываю по умолчанию. Выглядит это примерно так:

    res_file = pd.read_excel('name.xlsx', header=0)
    data = pd.read_excel(path)
    res_file['Код'] = range(1, 1 + len(data['Вопрос']) )
    res_file['Заголовок вопроса'] = data['Вопрос']
    res_file['Тип вопроса'] = ['multiple_choice' for i in templ['Тип вопроса']]
    res_file['Текст вопроса'] = data['Вопрос']

При попытке прописать значения циклом, как в "Тип вопроса" - вылетает ошибка:

Traceback (most recent call last):
  File "C:\Users\io\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Тип вопроса'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/io/github/itables/tables.py", line 110, in <module>
    main()
  File "C:/Users/io/github/itables/tables.py", line 108, in main
    merge(s_path, file_name)
  File "C:/Users/io/github/itables/tables.py", line 87, in merge
    templ['Тип вопроса'] = ['multiple_choice' for i in templ['Тип вопроса']]
  File "C:\Users\io\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Users\io\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Тип вопроса'

Не могу понять в чем причина, ранее подобные циклы работали исправно

2
  • 1
    Ну видимо в templ нет колонки 'Тип вопроса'
    – CrazyElf
    9 сен 2020 в 17:01
  • Это я проверил в первую очередь, нет, проблема именно в цикле. Для всех столбцов, где задействован цикл - такая же ошибка
    – Lumxi
    9 сен 2020 в 20:30

1 ответ 1

0

Первым решением оказалось не использовать данные циклы, то есть записать в данном виде:

    templ['Код'] = range(1, 1 + len(data['Вопрос']) )
    templ['Заголовок вопроса'] = data['Вопрос']
    templ['Тип вопроса'] = 'multiple_choice'
    templ['Текст вопроса'] = data['Вопрос']

Почему-то этот очевидный вариант работает не всегда, иногда приходится делать вышеупомянутый цикл. Вероятно, связано с внутренним отличием стандартного dataframe от excel dataframe формата

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.