【问题标题】:How to create a table using a crosstab and then group by another column value如何使用交叉表创建表,然后按另一列值分组
【发布时间】:2022-11-14 18:55:41
【问题描述】:

我有以下数据集。

col1    col2    col3
a       1       yes
a       1       no
b       1       no
a       3       yes
c       1       yes
b       2       yes

我使用交叉表在 col1 和 col2 之间创建了一个表并计算观察结果。

pd.crosstab(df.col1, df.col2)

output:

col2    1   2   3

col1 
a       2   0   1
b       1   1   0
c       1   0   0

如果我想要 groupby col3 的同一张表,我该怎么做?

Desired output:

col3: Yes                           col3: No                
col2    1   2   3                   col2    1   2   3

col1                                col1
a       1   0   1                   a       1   0   0
b       0   1   0                   b       1   0   0
c       1   0   0                   c       0   0   0 

此外,有什么方法可以使表格更美观?

【问题讨论】:

    标签: pandas group-by pivot-table


    【解决方案1】:

    您可以将列列表传递给pd.crosstab

    x = pd.crosstab(df.col1, [df.col3, df.col2])
    
    idx = pd.MultiIndex.from_product(
        [
            x.columns.get_level_values(0).unique(),
            x.columns.get_level_values(1).unique(),
        ]
    )
    
    x = x.reindex(idx, axis=1, fill_value=0)
    print(x)
    

    印刷:

    col3 no       yes      
    col2  1  2  3   1  2  3
    col1                   
    a     1  0  0   1  0  1
    b     1  0  0   0  1  0
    c     0  0  0   1  0  0
    

    【讨论】:

      【解决方案2】:

      如果将 col2 转换为 Categorical 然后将 DataFrame.pivot_table 添加到两个级别的所有类别:

      df['col2'] = pd.Categorical(df['col2'])
      
      df = df.pivot_table(index='col1',columns=['col3','col2'], aggfunc='size')
      print (df)
      col3 no       yes      
      col2  1  2  3   1  2  3
      col1                   
      a     1  0  0   1  0  1
      b     1  0  0   0  1  0
      c     0  0  0   1  0  0
      

      【讨论】:

        猜你喜欢
        • 2013-05-26
        • 2013-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-07
        • 1970-01-01
        • 1970-01-01
        • 2020-05-26
        相关资源
        最近更新 更多