iloc-IndexError(“位置索引器超出范围”),即使它在范围之内

时间:2019-05-06 19:52:13

标签: python pandas

我正在尝试从特定索引中获取行(这些索引在列表中)。即使这些索引(列表中的一个)在范围内,我仍会收到IndexError

df的索引计数为10872(最高值为2600) 该列表计数为628(最大值为2500)

list = df.loc [df [col] == value] .index.tolist

df.iloc [[列表]]

我想打印出数据,然后最终从每个特定索引中获取下4行

1 个答案:

答案 0 :(得分:1)

这里您不应该将.iloc用于索引,.iloc用于排名,loc用于索引

因此,您应该

l= df.loc[df[col] == value].index.tolist()

df.loc[l]

例如

df
Out[59]: 
  key
1   1
3   1
4   1
7   2
9   3

如果您想使用.iloc获得第一行,则可以

df.iloc[[0]]
Out[61]: 
  key
1   1

但带有loc

df.loc[[1]]
Out[62]: 
  key
1   1

错误,当您需要最后一行时,索引为9,但df没有位置9。

df.iloc[9]
IndexError: single positional indexer is out-of-bounds
df.loc[9]
Out[64]: 
key    3
Name: 9, dtype: object
相关问题