将Python Pandas中的列名从datatime对象更改为字符串? [英] Change column names in Python Pandas from datatime objects to strings?
本文介绍了将Python Pandas中的列名从datatime对象更改为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按照此配方。我'转动'一个数据框,如下所示:
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
并将其转换为:
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']
得到一个KeyError,因为'pivot'后面的列名称是datetime.time数据。
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)]
怎么可能我修改我的枢轴数据框,所以我可以在列之间进行简单的计算。我想这意味着将列名的格式从datetime.time更改为str。
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'))
或使用重命名
:
df.rename(columns =lambda t: t.strftime('%H:%M'), inplace=True)
然后将它们索引:
df['14:00']
返回:
2015-02-20 2399.9
2015-02-21 NaN
2015-02-22 NaN
Name: 14:00, dtype: float64
这篇关于将Python Pandas中的列名从datatime对象更改为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文