How to make a pandas crosstab with percentages?

前端 未结 6 653
时光说笑
时光说笑 2021-01-30 01:44

Given a dataframe with different categorical variables, how do I return a cross-tabulation with percentages instead of frequencies?

df = pd.DataFrame({\'A\' : [\         


        
6条回答
  •  执笔经年
    2021-01-30 02:13

    We can show it as percentages by multiplying by 100:

    pd.crosstab(df.A,df.B, normalize='index')\
        .round(4)*100
    
    B          A      B      C
    A                         
    one    33.33  33.33  33.33
    three  33.33  33.33  33.33
    two    33.33  33.33  33.33
    

    Where I've rounded for convenience.

提交回复
热议问题