使用itertools()在Python 3中一次遍历3行

时间:2019-02-22 15:55:24

标签: python pandas loops dataframe itertools

这段代码有助于一次迭代2行。 如何在熊猫的数据框中一次遍历3行?

例如

1,2,3

2,3,4

3,4,5 等

from itertools import tee
from itertools import zip_longest as izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

for (idx1, row1), (idx2, row2) in pairwise(stock_fut.iterrows()):
    print(idx1,row1,"\n\n",idx2,row2,"\n\n")

1 个答案:

答案 0 :(得分:0)

此代码有效

from itertools import tee
from itertools import zip_longest as izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b, c = tee(iterable,3)
    next(b);next(c);next(c)
    return izip(a, b, c)

for (idx1, row1), (idx2, row2), (idx3, row3) in pairwise(stock_fut.iterrows()):
    print(idx1,row1,"\n\n",idx2,row2,"\n\n",idx3, row3,"\n\n")