我有如下数据框:
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
为什么这个简单的函数出错。有人可以帮助我了解错误的意思吗?
选择的第一个正确方法是使用DataFrame.loc
:
DataFrame.loc
您的解决方案中的问题:
如果使用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行:
Series.iloc
但没有Series.iloc
(Python从0开始计数,因此对于选择第4行需要3),所以引发了错误。
如果使用:
df[0].iloc[3]
它的工作方式与您预期的一样,因为选择索引4.th
(不存在不存在的位置4)和列df[0].loc[3]
,但使用更好:]]
3
因为
0
。
您可能想使用df.loc[idx, 0]
而不是evaluation order matters。 loc
使用从零开始的行号,而不是索引。您的代码正在传递索引,该索引超出了从零开始的行号的范围,因此超出范围。