Following this recipe. I 'pivoted' a dataframe that looks like this:
                      Close
2015-02-20 14:00:00  1200.1
2015-02-20 14:10:00  1199.8
2015-02-21 14:00:00  1199.3
2015-02-21 14:10:00  1199.0
2015-02-22 14:00:00  1198.4
2015-02-22 14:10:00  1199.7
And turned it into this:
             14:00  14:10
 2015-02-20 1200.1 1199.8
 2015-02-21 1199.3 1199.0
 2015-02-22 1198.4 1199.7
However, now that I want do to simple calculations between the columns like:
df['Chg'] = df['14:10:00'] - df['14:00:00']
I get a KeyError, because after 'pivoting' the column names are datetime.time data.
In [1]: df_pivot.columns.tolist()
Out [2]:   
[datetime.time(14, 0),
 datetime.time(14, 10)]
How can I modify my pivoted dataframe, so I can do simple calculations between columns. I guess It means changing the format of the column names from datetime.time to str.
You can convert the column names to strings like this:
df.columns =df.columns.map(lambda t: t.strftime('%H:%M'))
or using rename:
df.rename(columns =lambda t: t.strftime('%H:%M'), inplace=True)
and then index them:
df['14:00']
returns:
2015-02-20    2399.9
2015-02-21       NaN
2015-02-22       NaN
Name: 14:00, dtype: float64
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With