calculate quarters from months

前端 未结 1 1312
我在风中等你
我在风中等你 2021-01-21 16:27

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                


        
1条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-21 17:03

    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
    

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

    0 讨论(0)
提交回复
热议问题