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
0  0.000868  33782.17      4     1.000000
1  0.000872  33224.89      3     0.460829
      Price    Price2  Count  perc_change
2  0.000875  84110.85      7     0.344037
3  0.000878  67686.15      4     0.342857
     Price     Price2  Count  perc_change
4  0.00088  121400.22      4      0.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) in zip(t, t):
    print(row1, row2)

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