Home > Software design >  Turning the dataframe upside down and performing groupby
Turning the dataframe upside down and performing groupby

Time:01-04

x = ts.loc[::-1, "column_1"].eq(0) #First Line of code for reference
x.groupby(pd.Grouper(freq="M")).cumsum().head(35) #Second Line of code for reference

Goal: I have a timeseries dataframe which i need to turn it upside down and perform the groupby

problem: the first line of code above is succesfully turning my dataframe upside down, But in second line of code the groupby is automatically turning my dataframe into right order and then performing its functionality.

Can someone tell me how to overcome this(How to apply groupby while my dataframe is stilll reverse?)

Sample timeseries dataset:
  Date           

01.01.2000  
02.01.2000  
03.01.2000   
..
..
..
26.01.2000   
27.01.2000  
28.01.2000 
29.01.2000   
30.01.2000   
31.01.2000  
01.02.2000
02.02.2000 

CodePudding user response:

For me working converting DatetimeIndex to month PeriodIndex with parameter sort=False:

ts = pd.DataFrame({'public.holiday':[0,1,0,1,1,0]}, 
                  index=pd.date_range('2000-01-01', periods=6))
print (ts)
            public.holiday
2000-01-01               0
2000-01-02               1
2000-01-03               0
2000-01-04               1
2000-01-05               1
2000-01-06               0

x = ts.loc[::-1, "public.holiday"].eq(0)
out = x.groupby(x.index.to_period('M'), sort=False).cumsum().head(35)
print (out)
2000-01-06    1
2000-01-05    1
2000-01-04    1
2000-01-03    2
2000-01-02    2
2000-01-01    3
Freq: -1D, Name: public.holiday, dtype: int64
  • Related