2

I have this Pandas dataframe:

             Value
Date
2015-06-01     6.9
2015-07-01     7.5
2015-08-01     7.6
2015-09-01     7.6
2015-10-01     7.9
2015-11-01     7.5

I'm accessing its last index item with this code:

somedate=dict.index[-1]

It is already in a datetime format. When I print somedate I get the following:

2015-11-01 00:00:00
2015-11-01 00:00:00

(not sure why it comes in two lines, but it is working fine anyway)

I'm using this same date to build another dataframe from Pandas:

            Prediction  MAPE  Score
2015-11-01        7.93  1.83      1

Well, all I need is that instead of 2015-11-01 in this last frame, it shows up only as 2015-11.

Can I work this out in the variable somedate or that's something I need to adjust when building the dataframe?

OBS.: I tried to use datetime.strptime, however it seems only to work on string dates, not on timestamps.

1 Answer 1

1

IIUC you need DatetimeIndex.to_period:

print df

#            Prediction  MAPE  Score
#                                   
#2015-11-01        7.93  1.83      1

print df.index

#DatetimeIndex(['2015-11-01'], dtype='datetime64[ns]', name=u'', freq=None)

df.index = df.index.to_period('M')
print df

#         Prediction  MAPE  Score
#                                
#2015-11        7.93  1.83      1

Or you can use DataFrame.to_period:

df = df.to_period('M')
print df

#         Prediction  MAPE  Score
#                                
#2015-11        7.93  1.83      1

EDIT:

I think dtype of index is not datetime but object, so you can convert it:

import pandas as pd
import io

temp=u"""Prediction;MAPE;Score
2015-11-01;7.93;1.83;1"""
df = pd.read_csv(io.StringIO(temp), sep=";", index_col=None)
df.index.name = ''    
print df

#            Prediction  MAPE  Score
#                                   
#2015-11-01        7.93  1.83      1

print df.index
#Index([u'2015-11-01'], dtype='object', name=u'')

#convert index to datetime
df.index = pd.to_datetime(df.index)

df = df.to_period('M')
print df

#         Prediction  MAPE  Score
#                                
#2015-11        7.93  1.83      1
Sign up to request clarification or add additional context in comments.

1 Comment

I'm getting this: AttributeError: 'Index' object has no attribute 'to_period'. Any idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.