Python/Pandas - 将类型从 Pandas 句点转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34800343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python/Pandas - Convert type from pandas period to string
提问by abutremutante
I have a DataFrame:
我有一个数据框:
Seasonal
Date
2014-12 -1.089744
2015-01 -0.283654
2015-02 0.158974
2015-03 0.461538
I used a pd.to_period in the DataFrame, so its index has turned into a Pandas period type (type 'pandas._period.Period').
我在 DataFrame 中使用了 pd.to_period,所以它的索引变成了 Pandas 周期类型(类型 '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)
However that doesn't work...
然而这行不通...
ValueError: Cannot cast PeriodIndex to dtype |S0
My code has been frozen since then.
从那时起我的代码就被冻结了。
S.O.S.
求救
回答by jezrael
You can use to_series
and then convert to string
:
您可以使用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')
回答by Sergey Bushmanov
The line below should convert your PeriodIndex
to string format:
下面的行应该将您PeriodIndex
的字符串格式转换为:
df.index = df.index.strftime('%Y-%m')
回答by Will Pan
You can convert the items to strings by specifying basestring
:
您可以通过指定将项目转换为字符串basestring
:
df.index = df.index.astype(basestring)
or if that doesn't work:
或者如果这不起作用:
df.index = df.index.map(str)
Refering to the comments from this answer, it might have to do with your pandas/python version.
参考此答案中的评论,它可能与您的Pandas/python 版本有关。
回答by zyu
If your index is a PeriodIndex
, you can convert it to a str
list
as the following example shows:
如果您的索引是 a PeriodIndex
,您可以将其转换为 a str
list
,如下例所示:
import pandas as pd
pi = pd.period_range("2000-01", "2000-12", freq = "M")
print(list(pi.astype(str)))