Pandas iterate over DataFrame row pairs

前端 未结 4 2011
执笔经年
执笔经年 2020-12-10 21:35

How can I iterate over pairs of rows of a Pandas DataFrame?

For example:

content = [(1,2,[1,3]),(3,4,[2,4]),(5,6,[6,9]),(7,8,[9,10])]
df = pd.DataFra         


        
4条回答
  •  死守一世寂寞
    2020-12-10 22:06

    If you want to keep the loop for, using zip and iterrows could be a way

    for (indx1,row1),(indx2,row2) in zip(df[:-1].iterrows(),df[1:].iterrows()):
        print "row1:\n", row1
        print "row2:\n", row2
        print "\n"
    

    To access the next row at the same time, start the second iterrow one row after with df[1:].iterrows(). and you get the output the way you want.

    row1:
    a    1
    b    2
    Name: 0, dtype: int64
    row2:
    a    3
    b    4
    Name: 1, dtype: int64
    
    
    row1:
    a    3
    b    4
    Name: 1, dtype: int64
    row2:
    a    5
    b    6
    Name: 2, dtype: int64
    
    
    row1:
    a    5
    b    6
    Name: 2, dtype: int64
    row2:
    a    7
    b    8
    Name: 3, dtype: int64
    

    But as said @RafaelC, doing for loop might not be the best method for your general problem.

提交回复
热议问题