20

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').

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.

aabujamra
  • 4,494
  • 13
  • 51
  • 101

4 Answers4

24

You can use to_series and then convert to 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')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
9

The line below should convert your PeriodIndex to string format:

df.index = df.index.strftime('%Y-%m')
Sergey Bushmanov
  • 23,310
  • 7
  • 53
  • 72
5

You can convert the items to strings by specifying 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.

Community
  • 1
  • 1
Will Pan
  • 282
  • 1
  • 10
1

If your index is a PeriodIndex, you can convert it to a str list as the following example shows:

import pandas as pd
pi = pd.period_range("2000-01", "2000-12", freq = "M")
print(list(pi.astype(str)))
zyu
  • 31
  • 3