“IndexError:位置索引器越界”,当它们明显不是时

2024-04-25

这是我正在使用的一些代码的 MWE。我通过切片和一些条件慢慢地缩减初始数据帧,直到只有我需要的行。每个五行块实际上代表一个不同的对象,因此,当我缩小范围时,如果每个五行块中的任何一行满足条件,我想保留它——这就是 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]

来自 Pandas 文档.iloc http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-position(强调我的):

Pandas 提供了一套方法来获得纯粹基于整数的索引。语义紧密遵循 python 和 numpy 切片。这些都是从 0 开始的索引.

您尝试按标签使用它,这意味着您需要.loc http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label

从你的例子来看:

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

>>>print df_cut.loc[89]
...
Name: 89, dtype: float64
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“IndexError:位置索引器越界”,当它们明显不是时 的相关文章

随机推荐