我知道 pandas.DataFrame.iterrows
允许逐行遍历 DataFrame。是否可以在迭代中跳回?
例如,我有一个包含十个项目的列表。迭代光标位于#8。出于某种原因,我想跳回到例如#5 然后从那里继续。
(如何)我可以做到这一点?
我已经尝试搜索类似的问题,但遗憾的是无济于事。
最佳答案
我会使用 iloc
,它是基于整数的索引来进行索引选择,这是因为您的索引可能不是基于 0 的 int64,但它仍然有效,例如:
In [103]:
df = pd.DataFrame({'a':np.arange(10)}, index = list('abcdefghij'))
for i in range(len(df)):
if i != 0 and i % 5 == 0:
print(df.iloc[i-3])
else:
print(df.iloc[i])
a 0
Name: a, dtype: int32
a 1
Name: b, dtype: int32
a 2
Name: c, dtype: int32
a 3
Name: d, dtype: int32
a 4
Name: e, dtype: int32
a 2
Name: c, dtype: int32
a 6
Name: g, dtype: int32
a 7
Name: h, dtype: int32
a 8
Name: i, dtype: int32
a 9
Name: j, dtype: int32
关于python - 在 pandas 数据帧上逐行迭代,并有可能跳回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30192692/