How to make a pandas crosstab with percentages?

前端 未结 6 708
时光说笑
时光说笑 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 01:55

    If you're looking for a percentage of the total, you can divide by the len of the df instead of the row sum:

    pd.crosstab(df.A, df.B).apply(lambda r: r/len(df), axis=1)
    

提交回复
热议问题