Python/Pandas - 将类型从 Pandas 句点转换为字符串 [英] Python/Pandas - Convert type from pandas period to string
本文介绍了Python/Pandas - 将类型从 Pandas 句点转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框:
Seasonal
Date
2014-12 -1.089744
2015-01 -0.283654
2015-02 0.158974
2015-03 0.461538
我在 DataFrame 中使用了 pd.to_period,所以它的索引变成了 Pandas 周期类型(type 'pandas._period.Period').
I used a pd.to_period in the DataFrame, so its index has turned into a Pandas period type (type 'pandas._period.Period').
现在,我想将该索引转换为字符串.我正在尝试应用以下内容:
Now, I want to turn that index to strings. I'm trying to apply the following:
df.index=df.index.astype(str)
然而这不起作用...
ValueError: Cannot cast PeriodIndex to dtype |S0
我的代码从那时起就被冻结了.
My code has been frozen since then.
求救
推荐答案
您可以使用 to_series
然后转换为string
:
print df
# Seasonal
#Date
#2014-12 -1.089744
#2015-01 -0.283654
#2015-02 0.158974
#2015-03 0.461538
print df.index
#PeriodIndex(['2014-12', '2015-01', '2015-02', '2015-03'],
# dtype='int64', name=u'Date', freq='M')
df.index=df.index.to_series().astype(str)
print df
# Seasonal
#Date
#2014-12 -1.089744
#2015-01 -0.283654
#2015-02 0.158974
#2015-03 0.461538
print df.index
#Index([u'2014-12', u'2015-01', u'2015-02', u'2015-03'], dtype='object', name=u'Date')
这篇关于Python/Pandas - 将类型从 Pandas 句点转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文