【问题标题】:Python pandas: positional indexers are out of bounds with .ilocPython pandas:位置索引器超出了 .iloc 的范围
【发布时间】:2020-03-26 04:58:04
【问题描述】:

df.tail() 返回:

35114   False   False   0.0 False   False   0.0 False   False   0.0 0.0 0.0 False   
35115   False   False   0.0 False   False   0.0 False   False   0.0 0.0 0.0 False   
35116   False   False   0.0 False   False   0.0 False   False   0.0 0.0 0.0 False   
35117   False   False   0.0 False   False   0.0 False   False   0.0 0.0 0.0 False   
35118   False   False   0.0 False   False   0.0 False   False   0.0 0.0 0.0 False

df.iloc[35118] 返回:

IndexError: single positional indexer is out-of-bounds

df.iloc[[35118]] 返回:

IndexError: positional indexers are out-of-bounds

df.iloc[[10]] 返回:

10   False   False   0.0   False   ....

别管我可以做的 .astype(int) 了,为什么这个索引不能通过一个明显存在的索引呢?

df.index[-10:] 返回:

Int64Index([35109, 35110, 35111, 35112, 35113, 35114, 35115, 35116, 35117,
            35118], dtype='int64')

【问题讨论】:

  • 我假设 df 的索引不是从 0 开始的,因此会出现错误。如果你通过 df.loc[[35118]] 你应该得到一个结果,因为它是按标签的。你可以使用 df.index.get_loc(35118) 来确认实际的索引,看看它是否给你 35118
  • df.index[:5] Int64Index([0, 1, 2, 3, 4], dtype='int64') 但是:df.index.get_loc(35118) 返回 34363 ?!?!
  • 正如我所说,这意味着一些操作减少了数据帧的长度,可能删除了一些行,这就是你所拥有的。如果你运行 df.iloc[[34363]] 你应该得到 35118 的行。对数据帧进行的一些操作或转换可能会导致这种情况。

标签: python pandas indexing


【解决方案1】:

如果您尝试使用 iloc[n] 访问行,则数字 (n) 应该是 小于行数。在这种情况下,您尝试访问 从 0 开始,经过其位置(不是索引值)的行。

所以从运行开始:df.index.size 显示的数字将显示如何 你有很多行。

显然,您的 DataFrame 中的行号小于或等于 您传递的数字(缺少一些索引值)。

另一方面,您也可以使用 loc[n] 访问一行,这次是通过 一个索引

例如df.loc[35118] 将返回索引等于给定值的行, 在你的情况下最后一行。

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2019-09-24
    • 2016-10-23
    • 1970-01-01
    • 2022-07-06
    • 2020-05-29
    • 2020-11-26
    • 2020-09-03
    • 2019-04-13
    相关资源
    最近更新 更多