【问题标题】:iloc - IndexError("positional indexers are out-of-bounds") even though it's within the boundsiloc - IndexError("位置索引器超出范围") 即使它在范围内
【发布时间】:2019-09-24 11:06:51
【问题描述】:

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

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

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

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

【问题讨论】:

  • 你为什么不直接做df[df[col]==value],这样可以用更少的步骤为你提供相同的数据
  • 如果我这样做,我会得到一个空数据集

标签: python pandas


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-02
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2017-03-31
    • 2019-03-21
    • 2016-06-28
    相关资源
    最近更新 更多