Iterating a list of Pandas dataframes / reshaping dataframe with .unstack

Viewed 274

I have a dataframe with a DatetimeIndex:

                          X
timestamp                    
2013-01-01 00:00:00  0.788500
2013-01-01 00:30:00  0.761525
2013-01-01 01:00:00  0.751850
2013-01-01 01:30:00  0.746445
2013-01-01 02:00:00  0.688677

and I am using unstack to reshape it with half-hourly intervals as the columns, and dates as the rows - as suggested in this answer.

df.index = [df.index.date, df.index.hour + df.index.minute / 60]
df = df['X'].unstack()
df.head()
              0.0       0.5       1.0       1.5       2.0       2.5   \
2013-01-01  0.788500  0.761525  0.751850  0.746445  0.688677  0.652226   
2013-01-02  0.799029  0.705590  0.661059  0.627001  0.606560  0.592116   
2013-01-03  0.645102  0.597785  0.563410  0.516707  0.495896  0.492416   
2013-01-04  0.699592  0.649553  0.598019  0.576290  0.561023  0.537802   
2013-01-05  0.782781  0.706697  0.645172  0.627405  0.605972  0.583536

All good. BUT I now want to carry out the same procedure for a number of dataframes. Initially, I'm using 2:

for df in [df1,df2]:
        df.index = [df.index.date, df.index.hour + df.index.minute / 60]
        df = df['X'].unstack()

The reindexing works, but the reshaping does not:

df1.head()

                      X
2013-01-01 0.0  0.788500
           0.5  0.761525
           1.0  0.751850
           1.5  0.746445
           2.0  0.688677

I think maybe I need some equivalent of inplace so the unstacked dataframes are passed back to df1 and df2

Any suggestions?

1 Answers
Related