Skip to content Skip to sidebar Skip to footer

Calculate Quarters From Months

I have a data frame with a number of columns by month c1 c2 yyyy-01 yyyy-02 yyyy-03 yyyy-04 yyyy-05 yyyy-06 ... a A 1 1 3 2 2 3 b B 2

Solution 1:

  1. Use pd.to_datetime() and to_period() functions to create a group variable of quarters for each year;
  2. You can pass an axis parameter to the groupby() function to group your data frame by columns, in this case the column index.

so, you can try:

df.set_index(['c1', 'c2'], inplace=True)
df

enter image description here

df.groupby(pd.to_datetime(df.columns).to_period("Q"), axis=1).sum().reset_index()

enter image description here


Post a Comment for "Calculate Quarters From Months"