Я создал фрейм данных в пандах и попытался отобразить 2 столбца с их метками. Мой код:
#5.py
import numpy as np
import pandas as pd
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data)
print(df.loc[:,['name', 'score']])
#print(df.loc['name', 'score'])
Этот код работает нормально, но когда я заменяю оператор печати print(df.loc[:,['name', 'score']])
на print(df.loc['name', 'score'])
, программа выдает следующие ошибки:
Traceback (most recent call last):
File "C:/Users/Vikranth Inti/PycharmProjects/Python-Basics/Pandas/Data Frame/5.py", line 29, in <module>
print(df.loc['name', 'score'])
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexing.py", line 1418, in __getitem__
return self._getitem_tuple(key)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexing.py", line 805, in _getitem_tuple
return self._getitem_lowerdim(tup)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexing.py", line 929, in _getitem_lowerdim
section = self._getitem_axis(key, axis=i)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexing.py", line 1850, in _getitem_axis
return self._get_label(key, axis=axis)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexing.py", line 160, in _get_label
return self.obj._xs(label, axis=axis)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\generic.py", line 3737, in xs
loc = self.index.get_loc(key)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexes\range.py", line 379, in get_loc
return super().get_loc(key, method=method, tolerance=tolerance)
File "C:\Users\Vikranth Inti\PycharmProjects\Rough-Work\venv\lib\site-packages\pandas\core\indexes\base.py", line 2899, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 128, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index_class_helper.pxi", line 91, in pandas._libs.index.Int64Engine._check_type
KeyError: 'name'
Process finished with exit code 1
(Использование PyCharm в Windows 10) .loc метод не принимает метки столбцов! Почему это так?