简体   繁体   中英

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    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?

Yes, you can use DataFrame.groupby with integer division for return 2 rows DataFrame s 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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM