"IndexError:位置索引器越界".当他们证明不是 [英] "IndexError: positional indexers are out-of-bounds" when they're demonstrably not

查看:70
本文介绍了"IndexError:位置索引器越界".当他们证明不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的某些代码的MWE.我通过切片和一些条件慢慢缩减了初始数据帧,直到只有我需要的行.五行的每个块实际上代表一个不同的对象,因此,当我仔细研究时,如果五行的每个块中的任何一行满足条件,我都希望保留它-这是keep.index循环完成的工作.不管怎样,完成后我可以看到我想要的最终索引存在,但是我收到一条错误消息,提示"IndexError:位置索引器超出范围."这是怎么回事?

Here's an MWE of some code I'm using. I slowly whittle down an initial dataframe via slicing and some conditions until I have only the rows that I need. Each block of five rows actually represents a different object so that, as I whittle things down, if any one row in each block of five meets the criteria, I want to keep it -- this is what the loop over keep.index accomplishes. No matter what, when I'm done I can see that the final indices I want exist, but I get an error message saying "IndexError: positional indexers are out-of-bounds." What is happening here?

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 (强调我):

From Pandas documentation on .iloc (emphasis mine):

Pandas提供了一组方法来获取纯粹基于整数的索引.语义紧随python和numpy切片.这些是基于 0的索引.

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

You're trying to use it by label, which means you need .loc

根据您的示例:

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

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

这篇关于"IndexError:位置索引器越界".当他们证明不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆