python - 在 pandas 数据帧上逐行迭代,并有可能跳回

标签 python pandas iterator

我知道 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/

相关文章:

python - 如何对大文件应用单热编码?

python - Python/BeautifulSoup 有没有办法在相似行的列表中选择特定行?

python - 如何通过 MySQLdb Python 将值插入表中

python - Pandas 造型 : Conditionally change background color of column by absolute value

python - 如何在 Pandas 数据框的每一行的开头添加动态数量的空格?

c++ - *it++ 如何对输出迭代器有效?

python - GAE 中的 SQLAlchemy 'character_set_name' 错误

python - Q : Python CSV, 能否根据日期时间列中的不同日期自动将 CSV 中的数据行发送到数据框

rust - IntoIterator 作为函数参数不接受适配器结构

c++ - 通过索引访问 vector 迭代器?