Advertisement
elena1234

Time Series and grouping by year and month in Python

May 5th, 2023 (edited)
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | Source Code | 0 0
  1. #1. Group by year and month:
  2. df_year_month_quantity = df_category_date_quantity.assign(yr = df_category_date_quantity['TransactionDate'].dt.year, mnth = df_category_date_quantity['TransactionDate'].dt.month).groupby(['yr', 'mnth']).agg({'Quantity': 'sum'}).reset_index()
  3. df_year_month_quantity
  4.  
  5. #2.Unstack and set index
  6. unstack_month_quantity_by_year = df_year_month_quantity.set_index(['mnth', 'yr']).unstack(fill_value = 0).reset_index()
  7. unstack_month_quantity_by_year = unstack_month_quantity_by_year.set_index('mnth')
  8. unstack_month_quantity_by_year
  9.  
  10. #3.Plot
  11. sns.set(font_scale=1.3)
  12. unstack_month_quantity_by_year.plot(figsize=(12,15), subplots = True, cmap='viridis', sharex = False, sharey=True,
  13.                                     linestyle = '--',linewidth=2.5)
  14. plt.xticks([1,2,3,4,5,6,7,8,9,10,11,12], ha='center')
  15. plt.yticks([100000,200000,300000,400000,500000,600000,700000,800000])
  16. plt.show()
  17.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement