Home > Back-end >  Get last three records for every loop in a dataframe
Get last three records for every loop in a dataframe

Time:06-22

I have a dataframe like the following:

    User           Warehouse    R_Number    Date    Missing
0   Delhi_Goa    Goa Warehouse  5046    2022-05-24  TRRFF.1T22AD0041
1   Delhi_Goa    Goa Warehouse  5046    2022-05-24  PPRFP.1T22AD0017
2   Delhi_Goa    Goa Warehouse  5048    2022-05-24  TRRFF.1T22AD0031
3   Delhi_Goa    Goa Warehouse  5048    2022-05-24  TRRFF.1T22AD0037
4   Delhi_Goa    Goa Warehouse  5048    2022-05-24  PPRFP.1T22AD0039
5   Delhi_Goa    Goa Warehouse  5048    2022-05-24  TRRFF.1T22AD0026

I want to loop over the DataFrame and perform actions for every row where the result will be dependent on last three records

for eg.

Loop 1 to fetch index 0 
loop 2 to fetch index 0,1
loop 3 to fetch index 0,1,2
loop 4 to fetch index 1,2,3
loop 5 to fetch index 2,3,4
loop 6 to fetch index 3,4,5

How can I do loop the dataframe for last three records ?

CodePudding user response:

Use DataFrame.rolling:

for g in df.rolling(3):
    print (g)

   User                Warehouse  R_Number        Date           Missing
0     0  Delhi_Goa Goa Warehouse      5046  2022-05-24  TRRFF.1T22AD0041
   User                Warehouse  R_Number        Date           Missing
0     0  Delhi_Goa Goa Warehouse      5046  2022-05-24  TRRFF.1T22AD0041
1     1  Delhi_Goa Goa Warehouse      5046  2022-05-24  PPRFP.1T22AD0017
   User                Warehouse  R_Number        Date           Missing
0     0  Delhi_Goa Goa Warehouse      5046  2022-05-24  TRRFF.1T22AD0041
1     1  Delhi_Goa Goa Warehouse      5046  2022-05-24  PPRFP.1T22AD0017
2     2  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0031
   User                Warehouse  R_Number        Date           Missing
1     1  Delhi_Goa Goa Warehouse      5046  2022-05-24  PPRFP.1T22AD0017
2     2  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0031
3     3  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0037
   User                Warehouse  R_Number        Date           Missing
2     2  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0031
3     3  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0037
4     4  Delhi_Goa Goa Warehouse      5048  2022-05-24  PPRFP.1T22AD0039
   User                Warehouse  R_Number        Date           Missing
3     3  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0037
4     4  Delhi_Goa Goa Warehouse      5048  2022-05-24  PPRFP.1T22AD0039
5     5  Delhi_Goa Goa Warehouse      5048  2022-05-24  TRRFF.1T22AD0026
  • Related