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:
- Use
pd.to_datetime()
andto_period()
functions to create a group variable of quarters for each year; - 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
df.groupby(pd.to_datetime(df.columns).to_period("Q"), axis=1).sum().reset_index()
Post a Comment for "Calculate Quarters From Months"