Python / Pandas - 将类型从 pandas 转换为字符串 [英] Python/Pandas - Convert type from pandas period to string

查看:2712
本文介绍了Python / Pandas - 将类型从 pandas 转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataFrame:

I have a DataFrame:

         Seasonal
Date             
2014-12 -1.089744
2015-01 -0.283654
2015-02  0.158974
2015-03  0.461538

我在DataFrame中使用了一个pd.to_period,所以它的索引变成一个熊猫时期类型(类型'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

我的代码已被冻结

SOS

推荐答案

您可以使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆