Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turning the dataframe upside down and performing groupby

x = ts.loc[::-1, "public.holiday"].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?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading