python - "IndexError: positional indexers are out-of-bounds"当他们显然不是

标签 python pandas dataframe conditional-statements

这是我正在使用的一些代码的 MWE。我通过切片和一些条件慢慢地削减了一个初始数据帧,直到我只有我需要的行。每个五行 block 实际上代表一个不同的对象,因此,当我减少内容时,如果每个五行 block 中的任何一行满足条件,我想保留它——这就是循环 keep.index 完成的。无论如何,当我完成后,我可以看到我想要的最终索引存在,但我收到一条错误消息,指出“IndexError:位置索引器超出范围。”这里发生了什么?

import pandas as pd
import numpy as np

temp = np.random.rand(100,5)

df = pd.DataFrame(temp, columns=['First', 'Second', 'Third', 'Fourth', 'Fifth'])

df_cut = df.iloc[10:]

keep = df_cut.loc[(df_cut['First'] < 0.5) & (df_cut['Second'] <= 0.6)]

new_indices_to_use = []
for item in keep.index:
    remainder = (item % 5)
    add = np.arange(0-remainder,5-remainder,1)
    inds_to_use = item + add
    new_indices_to_use.append(inds_to_use)

new_indices_to_use = [ind for sublist in new_indices_to_use for ind in sublist]
final_indices_to_use = []
for item in new_indices_to_use:
    if item not in final_indices_to_use:
        final_indices_to_use.append(item)

final = df_cut.iloc[final_indices_to_use]

最佳答案

来自 .iloc 上的 Pandas 文档(强调我的):

Pandas provides a suite of methods in order to get purely integer based indexing. The semantics follow closely python and numpy slicing. These are 0-based indexing.

您正在尝试按标签使用它,这意味着您需要 .loc

从你的例子:

>>>print df_cut.iloc[89]
...
Name: 99, dtype: float64

>>>print df_cut.loc[89]
...
Name: 89, dtype: float64

关于python - "IndexError: positional indexers are out-of-bounds"当他们显然不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44123056/

相关文章:

python - 如何使用aiohttp_jinja2获取url的一部分?

python - TypeError: Fetch argument has invalid type float32, must be a string or Tensor

python - Django:代理元类忽略 verbose_name_plural

python - 按 Pandas 中一个索引级别的排名进行过滤?

python - Pandas groupby 将系列转换为具有最大值计数的数据帧

python-3.x - 如何在查看前几行值的每一行中执行代码的同时,高效地逐行遍历 pandas 数据框?

python - 如何根据列标签获取数据帧的集合差异?

python - django:如何在模板 html 页面内进行计算?

python - Pandas 中 "&"和 "and"之间的区别

python - 对 Pandas Dataframe 的行求和