Garrett Mark Scott
Garrett Mark Scott

Reputation: 285

Changing Period to Datetime

My goal is to convert period to datetime.

If Life Was Easy:

master_df = master_df['Month'].to_datetime()

Back Story:

I built a new dataFrame that originally summed the monthly totals and made a 'Month' column by converting a timestamp to period. Now I want to convert that time period back to a timestamp so that I can create plots using matplotlib.

enter image description here

I have tried following:

A simple goal would be to plot the following:

plot.bar(m_totals['Month'], m_totals['Showroom Visits']);

This is the error I get if I try to use a period dtype in my charts

ValueError: view limit minimum 0.0 is less than 1 and is an invalid Matplotlib date value. 

This often happens if you pass a non-datetime value to an axis that has datetime units.

Additional Material:

Code I used to create the Month column (where period issue was created):

master_df['Month'] = master_df['Entry Date'].dt.to_period('M')

Codes I used to group to monthly totals:

m_sums = master_df.groupby(['DealerName','Month']).sum().drop(columns={'Avg. Response Time','Closing Percent'})

m_means = master_df.groupby(['DealerName','Month']).mean()
m_means = m_means[['Avg. Response Time','Closing Percent']]

m_totals = m_sums.join(m_means)
m_totals.reset_index(inplace=True)
m_totals

Resulting DataFrame:

enter image description here

Upvotes: 8

Views: 15066

Answers (3)

Raisin
Raisin

Reputation: 434

Another potential solution is to use to_timestamp. For example: m_totals['Month'] = m_totals['Month'].dt.to_timestamp()

Upvotes: 5

Wais Yousofi
Wais Yousofi

Reputation: 19

First change it to str then to date

index=pd.period_range(start='1949-01',periods=144 ,freq='M')
type(index)
#changing period to date
index=index.astype(str)
index=pd.to_datetime(index)
df.set_index(index,inplace=True)
type(df.index)
df.info()

Upvotes: 0

Garrett Mark Scott
Garrett Mark Scott

Reputation: 285

I was able to cast the period type to string then to datetime. Just could not go straight from period to datetime.

m_totals['Month'] = m_totals['Month'].astype(str)
m_totals['Month'] = pd.to_datetime(m_totals['Month'])
m_totals.dtypes

enter image description here

I wish I did not get downvoted for not providing the entire dataFrame.

Upvotes: 14

Related Questions