【问题标题】:Calculate the percentage for each target variable in python计算python中每个目标变量的百分比
【发布时间】:2020-03-15 20:33:35
【问题描述】:

我有一个这样的数据框,

category    target
A               1
B               1
A               0
A               0
A               0
B               0
C               1
C               1

我想计算每个类别中每个目标值的百分比。 例如,

的百分比

'A'==1 是count(1)/(count(1)+count(0))

'A'==0 是count(0)/(count(1)+count(0))

我怎样才能得到这样的表,

category        1          0
A              25%        75%
B              50%        50%
C             100%         0%

也许我应该使用一些分组功能?

【问题讨论】:

    标签: python pandas numpy dataframe group-by


    【解决方案1】:

    crosstab与参数normalize='index'一起使用:

    df = pd.crosstab(df['category'], df['target'], normalize='index').mul(100)
    print (df)
    target       0      1
    category             
    A         75.0   25.0
    B         50.0   50.0
    C          0.0  100.0
    

    或者使用SeriesGroupBy.value_countsSeries.unstack 进行整形:

    df = df.groupby('category').target.value_counts(normalize=True).unstack(fill_value=0).mul(100)
    print (df)
    target       0      1
    category             
    A         75.0   25.0
    B         50.0   50.0
    C          0.0  100.0
    

    【讨论】:

    • 感谢您的帮助!我还有一个问题。如果target 也是字符串类型,或者在名为object 的pandas 数据框中,这种方法也可以吗?
    • @JiayuZhang - 是的,因为它计算值。
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    相关资源
    最近更新 更多