Yan Tian
Yan Tian

Reputation: 397

pandas groupby & aggregate into original dataframe

Original dataframe is:

                       open  high  low  close
2018-01-01 09:30:00    22.2  24.4  21.1  23.3
2018-01-01 09:35:00
.
.
.
2018-03-09 15:00:00

and I want to calculate Open/high/low/close on daily/weekly/monthly basis and aggregate the results and relevant index (week, month) into the original dataframe with multi-index as below:

open_day  open_week  open_month              open  high  low   close
2018-Jan  1st-week   2018-01-01   09:30:00   22.2  24.4  21.1  23.3
                                  09:35:00
.
.
.

Upvotes: 1

Views: 258

Answers (1)

BENY
BENY

Reputation: 323226

Sounds like you need

df.assign(open_month=df.index.strftime('%Y%B'),
  open_week=df.index.strftime('%W'),
  open_date=df.index.date,
  open_time=df.index.time).\
   set_index(['open_month','open_week','open_date','open_time'])
Out[235]: 
                                            open  high   low  close
open_month  open_week open_date  open_time                         
2018January 01        2018-01-01 09:30:00   22.2  24.4  21.1   23.3
                                 09:35:00   22.2  24.4  21.1   23.3
2018March   09        2018-03-01 09:35:00   22.2  24.4  21.1   23.3

Upvotes: 1

Related Questions