Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas Dataframe iterating through two rows at a time

Tags:

python

pandas

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    84110.85     7     0.344037
3  0.000878    67686.15     4     0.342857
4  0.000880    121400.22    4     0.227790

The following code:

for row in df.iterrows():
    print(row)

Returns one row at a time of the df Dataframe I was wondering if it is possible to iterate through two rows at a time?

like image 350
Nazim Kerimbekov Avatar asked Dec 22 '22 22:12

Nazim Kerimbekov


2 Answers

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
like image 162
jezrael Avatar answered Dec 25 '22 11:12

jezrael


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)
like image 33
Andy L. Avatar answered Dec 25 '22 12:12

Andy L.