首页 > 解决方案 > 如何将 1 个系列的唯一值作为列并计算每季度系列中唯一值的每次出现?

问题描述

我有一个看起来像这样的df:

           date                              col1
0      2020-01-09T19:25                      a
1      2020-01-09T13:27                      a
2      2020-01-04T13:44                      b
3      2019-12-31T15:37                      b
4      2019-12-23T21:47                      c

我想将 col1 的唯一值分配为列标题,并按季度对日期进行分组,并按季度计算 col1 的唯一值。

我可以按季度分组并像这样计算:

df['date'] = pd.to_datetime(df['date']) 

df = df.groupby(df['date'].dt.to_period('Q'))['col1'].agg(['count'])

df 现在看起来像这样:

               count
dateresponded       
2019Q4            2
2020Q1            3

我无法分辨出唯一值的计数是多少。

我希望 df 看起来像这样:

                   a                b               c              
dateresponded       
2019Q4                              1               1
2020Q1             2                1

标签: python-3.xpandaspandas-groupby

解决方案


IIUC,你想要pd.crosstab

new_df = pd.crosstab(df['date'].dt.to_period('Q'),df['col1'],
                     rownames=['dateresponded'],
                     colnames=[None])
print(new_df)

我们也可以使用groupby+ DataFrame.unstack。我们可以使用 重命名轴DataFrame.rename_axis

new_df = (df.groupby([df['date'].dt.to_period('Q'),'col1'])
            .size()
            .unstack(fill_value = 0)
            .rename_axis(columns = None,index = 'dateresponded'))
print(new_df)

new_df = (df.groupby(df['date'].dt.to_period('Q'))
            .col1
            .value_counts()
            .unstack(fill_value = 0)
            .rename_axis(columns = None,index = 'dateresponded'))
 print(new_df)

输出

               a  b  c
dateresponded         
2019Q4         0  1  1
2020Q1         2  1  0

推荐阅读