Skip to content Skip to sidebar Skip to footer

Pandas Dataframe Iterating Through Two Rows At A Time

I'm using the following Dataframe: Price Price2 Count perc_change 0 0.000868 33782.17 4 1.000000 1 0.000872 33224.89 3 0.460829 2 0.000875

Solution 1:

Yes, you can use DataFrame.groupby with integer division for return 2 rows DataFrames if possible:

#default RangeIndex
for i, g in df.groupby(df.index // 2):print (g)

General solution with numpy.arange:

for i, g in df.groupby(np.arange(len(df)) // 2):print (g)
      Price    Price2  Count  perc_change
00.00086833782.1741.00000010.00087233224.8930.460829
      Price    Price2  Count  perc_change
20.00087584110.8570.34403730.00087867686.1540.342857
     Price     Price2  Count  perc_change
40.00088121400.2240.22779

Solution 2:

iterrows is generator object, so you just need to call next twice on it or use zip

t = df.iterrows()
for (i, row1), (j, row2) inzip(t, t):
    print(row1, row2)

Post a Comment for "Pandas Dataframe Iterating Through Two Rows At A Time"