Reputation: 83
Here I have a large dataframe (Nx1, it has thousands of stocks, here I just make it to be 4)
ds code close
20160101 001 1.5
002 1.12
003 1.21
005 12.4
20160102 001 2.3
002 3.4
003 5.4
005 7.2
``` ``` ```
20201231 001 14.5
002 2.2
003 3.3
005 24.5
My purpose is to arbitrarily select a time period within the dataset, and calculate the average close of each stock in 30 days. For example, the codes should be able to calculate the average close in 30 days of each stock from 20170101 to 20191231.
So I would like to split the large dataframe by "ds" and reform those splited dataframes to the following form, that it might be easier to reach my goal. But I don't know if there is any easy way to get there?
code 20160101 20160102 .... 20201231
001 1.5 2.3 .... 14.5
002 1.12 3.4 .... 2.2
003 1.21 5.4 .... 3.3
005 12.4 7.2 .... 24.5
Upvotes: 0
Views: 29
Reputation: 862591
Use Series.unstack
with select close
for Series
(ds
and code
are levels of MultiIndex
):
df1 = df['close'].unstack(level=0)
Upvotes: 1