Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column names in Python Pandas from datetime objects to strings?

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.

like image 246
hernanavella Avatar asked Feb 23 '15 00:02

hernanavella


Video Answer


1 Answers

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
like image 185
JAB Avatar answered Oct 16 '22 18:10

JAB