Skip to main content
 首页 » 编程设计

python之Python 中的 DataFrame 切片失败

2025年05月04日10cloudgamer

我想用 Python 对数据进行切片。对我的数据帧进行切片这一非常基本的任务会向我抛出意外错误。

我的代码是:

import pandas as pd 
 
test_file = pd.read_csv("C:/Users/Lenovo/Desktop/testfile.csv") 
test_select = test_file[["Category", "Shop"]] 
print(test_select[1,1]) 

代码 print(test_select[1,1]) 应该显示第二列的第二行。

错误信息:

File "pandas_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: (1, 1)

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:/Users/Lenovo/.PyCharmCE2018.1/config/scratches/Dictionary.py", line 8, in print(h_select[1,1]) File "C:\Users\Lenovo\PycharmProjects\mindnotez\venv\lib\site-packages\pandas\core\frame.py", line 2688, in getitem return self._getitem_column(key) File "C:\Users\Lenovo\PycharmProjects\mindnotez\venv\lib\site-packages\pandas\core\frame.py", line 2695, in _getitem_column return self._get_item_cache(key) File "C:\Users\Lenovo\PycharmProjects\mindnotez\venv\lib\site-packages\pandas\core\generic.py", line 2489, in _get_item_cache values = self._data.get(item) File "C:\Users\Lenovo\PycharmProjects\mindnotez\venv\lib\site-packages\pandas\core\internals.py", line 4115, in get loc = self.items.get_loc(item) File "C:\Users\Lenovo\PycharmProjects\mindnotez\venv\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc return self._engine.get_loc(self._maybe_cast_indexer(key)) File "pandas_libs\index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc File "pandas_libs\hashtable_class_helper.pxi", line 1492, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas_libs\hashtable_class_helper.pxi", line 1500, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: (1, 1)

当我打印 print(test_select.head()) 时,我得到以下输出:

     Category           Shop 
0       Jidlo         Albert 
1       Jidlo          BILLA 
2       Jidlo         Albert 
3       Jidlo         Albert 
4  Restaurant  Kockafé Freyd 

像 print(test_select[1:4]) 一样对数据框进行切片,打印第 1:3 行。 使用命令 print(test_select[1,1]),我想要第二列,第二行。但是,我收到上面的错误消息。

为什么我会收到 KeyError 异常?我错过了什么?

我使用:

  • python 3.7
  • PyCharm
  • Anaconda(已安装)

请您参考如下方法:

当你想要切片数据帧时

按行号

df.iloc[[1, 5]] # to get rows 1 and 5 
 
df.iloc[1:6] # to get rows 1 to 5 inclusive 

您还可以将其缩小到特定列,如下所示(以避免 chain indexing )

df.iloc[[1, 5], df.columns.get_loc('Shop')] 

或多列

df.iloc[[1, 5], df.columns.get_indexer(['Shop', 'Category'])] 

基于标签的索引

# Numeric 
df.loc[[1, 5]] # 1 and 5 are considered labels here 
df.loc[[1, 5], 'Shop'] 
df.loc[[1, 5], ['Shop', 'Category']] 
 
# Textual or otherwise 
df.set_index('Shop', inplace=True) 
df.loc[['BILLA', 'Albert'], 'Category']