Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Pandas - Convert type from pandas period 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 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.

like image 792
aabujamra Avatar asked Jan 14 '16 21:01

aabujamra


People also ask

How do I change Dtype of a column in pandas to string?

If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df. astype(str) methods.

How do I change the data type of a pandas series?

Change data type of a series in PandasUse a numpy. dtype or Python type to cast entire pandas object to the same type. Alternatively, use {col: dtype, …}, where col is a column label and dtype is a numpy. dtype or Python type to cast one or more of the DataFrame's columns to column-specific types.

Is Dtype object a string?

Moreover, having dtype as Object will make it less clear to work with just text and exclude the non-text values. With the new String dtype, the values are explicitly treated as strings.


3 Answers

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')
like image 51
jezrael Avatar answered Oct 20 '22 10:10

jezrael


The line below should convert your PeriodIndex to string format:

df.index = df.index.strftime('%Y-%m')
like image 41
Sergey Bushmanov Avatar answered Oct 20 '22 10:10

Sergey Bushmanov


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.

like image 5
Will Pan Avatar answered Oct 20 '22 09:10

Will Pan