Python中的DataFrame切片失败

亚历克斯

我想在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])应显示第二列的第二行。

错误信息:

在pandas._libs.hashtable.PyObjectHashTable.get_item KeyError中的文件“ pandas_libs \ hashtable_class_helper.pxi”,第1500行KeyError:(1、1)

在处理上述异常期间,发生了另一个异常:

追溯(最近一次通话最近):文件“ C:/Users/Lenovo/.PyCharmCE2018.1/config/scratches/Dictionary.py”,行8,在print(h_select [1,1])中文件“ C:\ Users \ Lenovo \ PycharmProjects \ mindnotez \ venv \ lib \ site-packages \ pandas \ core \ frame.py“,第2688行,在getitem中返回self._getitem_column(key)文件“ C:\ Users \ Lenovo \ PycharmProjects \ mindnotez \ venv \ lib \ site-packages \ pandas \ core \ frame.py”,行2695,在_getitem_column中返回self._get_item_cache(key)文件“ C:\ Users \ Lenovo \ PycharmProjects \ mindnotez \ venv \ lib \ site-packages \ pandas \ core \ generic.py”,行2489,在_get_item_cache值= self._data.get(item)文件中,“ C:\ Users \ Lenovo \ PycharmProjects \ mindnotez \ venv \ lib \ site-packages \ pandas \ core \ internals.py“,第4115行,位于get loc = self.items.get_loc(item)文件” C:\ Users \ Lenovo \ PycharmProjects \ mindnotez \ venv \ lib \ site-packages \ pandas \ core \ indexes \ base.py“,行3080,在get_loc中返回self._engine.get_loc(self._maybe_cast_indexer(key))文件“ pandas_libs \ index.pyx”,行140,在pandas._libs.index.IndexEngine.get_loc文件“ pandas_libs \ index.pyx”中,第162行,pandas._libs.index.IndexEngine.get_loc中的文件“ pandas_libs \ hashtable_class_helper.pxi”,第1492行,pandas._libs.hashtable.PyObjectHashTable.get_item文件“ pandas_libs \ hashtable_class_helper.pxi”,pandas的1500行。 .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
  • 药香
  • Anaconda(已安装)
阿约戈

当您想切片数据框时

按行号

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

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

您还可以按如下所示将其范围缩小到特定列(以避免链索引

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']

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章