Я пытаюсь прочитать данные строкового типа из файла Excel с помощью Pandas. Я могу прочитать заголовок всего файла. Однако, когда я пытаюсь найти первый или второй столбец файла, я получаю сообщение об ошибке «Traceback (последний вызов был последним)». Мой файл .xlsx содержит все данные текстового типа. Я не знаю, если что-то не так с форматом моего файла .xlsx. Мой код, как показано ниже.
import pandas as pd
df = pd.read_excel("document name.xlsx",index_col=0)
df.head() # It works here to show me the head of the whole file.
df['column 1'].head() # It does NOT work for locating the first column.The error message is listed below.
KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in
get_loc(self, key, method, tolerance)
2656 try:
-> 2657 return self._engine.get_loc(key)
2658 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in
pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in
pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'column1'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-17-a04362371301> in <module>
----> 1 df['column1'].head()
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2925 if self.columns.nlevels > 1:
2926 return self._getitem_multilevel(key)
-> 2927 indexer = self.columns.get_loc(key)
2928 if is_integer(indexer):
2929 indexer = [indexer]
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2657 return self._engine.get_loc(key)
2658 except KeyError:
-> 2659 return self._engine.get_loc(self._maybe_cast_indexer(key))
2660 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2661 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'column1'