Python-iloc-giving-indexError:在simple-for循环中,单个位置索引器超出边界

2024-04-26 11:47:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的数据帧如下所示:

df = 
          0
1      0.993995
2      1.111068
3      1.760940
.
.
.
49    40.253574
50    40.664486
51    41.083962

我遍历每一行并打印每个元素。我的代码如下:

for idx,row in df.iterrows():
    print(df[0].iloc[idx])

当前输出:

1.111068
1.76094
2.691832
.
.
40.664486
41.083962
Traceback (most recent call last):

  File "<ipython-input-46-80539a9081e5>", line 2, in <module>
    print(darkdf[0].iloc[idx])

  File "C:\Users\MM\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 1500, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)

  File "C:\Users\MM\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 2230, in _getitem_axis
    self._validate_integer(key, axis)

  File "C:\Users\MM\Anaconda3\lib\site-packages\pandas\core\indexing.py", line 2139, in _validate_integer
    raise IndexError("single positional indexer is out-of-bounds")

IndexError: single positional indexer is out-of-bounds

为什么这个简单的函数会出错。有人能帮我理解错误在说什么吗?你知道吗


Tags: incorepandasdflibpackageslinesite
2条回答

选择的第一个正确方法是使用^{}

print (df)
          0
1  0.993995
2  1.111068
3  1.760940

for idx,row in df.iterrows():
    print(df.loc[idx, 0])
0.9939950000000001
1.111068
1.7609400000000002

解决方案中的问题:

如果使用^{}函数,则按位置选择,而不是按标签选择。你知道吗

所以您希望通过选择以下选项来选择第4行:

df[0].iloc[3]

但是没有4.th(python从0开始计数,所以对于select 4.th行需要3)行所以引发了错误。你知道吗

如果使用:

df[0].loc[3]

它的工作方式和您预期的一样,因为选择索引3(不是不存在的位置4)和列0,但更好的方法是使用:

df.loc[idx, 0]

因为evaluation order matters。你知道吗

您可能希望使用loc而不是ilociloc使用基于零的行号,而不是索引。您的代码正在传递索引,这些索引超出了以零为基础的行号的范围,因此超出了界限。你知道吗

相关问题 更多 >