Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • Reading the docs for Period.to_timestamp.

  • Converting to a string and then back to datetime. Still keeps the period issue and won't convert.

  • Following a couple similar questions in Stackoverflow but could not seem to get it to work.

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

like image 325
Garrett Mark Scott Avatar asked Jun 07 '26 15:06

Garrett Mark Scott


1 Answers

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.

like image 160
Garrett Mark Scott Avatar answered Jun 10 '26 05:06

Garrett Mark Scott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!