0

According to these question Pandas iterate over DataFrame row pairs

I want to iterate over three rows like question above, but I find it difficult.

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

These are the code in the solution for iterating two rows, and I want to modify these code so it could iterate three rows.

I am trying df.index//3 or df[::3] but it's not what I want. Help me

Mario
  • 1,631
  • 2
  • 21
  • 51

1 Answers1

0
for (indx1,row1),(indx2,row2),(indx3,row3) in zip(
    df[:-2].iterrows(),df[1:-1].iterrows(),df[2:].iterrows()):

    print "row1:\n", row1
    print "row2:\n", row2
    print "row3:\n", row3
    print "\n"

Is this what you're looking for? Btw, it's about time to say goodbye to Python2...

LukasNeugebauer
  • 1,331
  • 7
  • 10
  • and what if I only want to display per three rows in the last two rows? thank you for advice, I actually use Python3 – Windy Aulia R. Jun 13 '19 at 04:03
  • I don't understand, what you're trying to say here. Can you try again? Maybe I can help then. – LukasNeugebauer Jun 13 '19 at 08:19
  • I mean, I want to iterate over three rows in only two columns, then in the function of iteration, I do linear regression in that three rows. So, iterate over three rows, do linear regression, iterate over three rows, do linear regression, so on. – Windy Aulia R. Jun 13 '19 at 09:42
  • You just have to iterate over the two columns then. So df[:-2] becomes df.iloc[:-2,:2] if you want only the first two columns, and so on. But that means that you just have 6 values per iteration and that's probably not enough for whatever you're trying to do with a regression. Don't get me wrong, but I get the feeling that you'd be better of by working through a pandas intro tutorial and then figure it out. Because this stuff here is really basic. – LukasNeugebauer Jun 19 '19 at 11:01