。loc方法不使用DataFrame的列标签

问题描述 投票:0回答:1

我在熊猫中创建了一个数据框,并尝试显示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

((在Windows 10上使用PyCharm).loc方法不带列标签!为什么会这样?

python pandas dataframe label
1个回答
0
投票

。loc方法的格式为df.loc [row_slice,column_slice]

要不使用loc就可以返回列标签,只需使用df [column_slice]

print(df[['name','score']])
© www.soinside.com 2019 - 2024. All rights reserved.