在pandas数据帧上逐行迭代,可以跳回

时间:2015-05-12 13:42:27

标签: python pandas iterator

我知道pandas.DataFrame.iterrows允许逐行迭代DataFrame。是否有可能在迭代中跳回来?

例如,我有十个项目的列表。迭代光标位于#8。出于某种原因,我想跳回到例如#5然后继续。

(怎么样)我可以这样做吗?

我已经尝试搜索类似的问题,但遗憾的是无济于事。

1 个答案:

答案 0 :(得分:1)

我使用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
相关问题