Python / Pandas - convert type from pandas to string

I have a DataFrame:

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

I used pd.to_period in the DataFrame, so its index turned into the Pandas period type (type 'pandas._ period.Period').

Now I want to turn this index into rows. I am trying to apply the following:

df.index=df.index.astype(str)

However, this does not work ...

ValueError: Cannot cast PeriodIndex to dtype |S0

My code has been frozen since.

SOS

+4
source share
3 answers

You can use to_seriesand 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')
+7
source

The following line should convert the format PeriodIndexto a string:

df.index = df.index.strftime('%Y-%m')
+3
source

, basestring:

df.index = df.index.astype(basestring)

:

df.index = df.index.map(str)

Referring to the comments of this answer , this may be relevant to your version of pandas / python.

+3
source

Source: https://habr.com/ru/post/1624352/


All Articles