代码之家  ›  专栏  ›  技术社区  ›  EvitaSchaap

计算按另一列分组的标志百分比

  •  0
  • EvitaSchaap  · 技术社区  · 9 月前

    我有以下数据帧:

    帐户ID 订阅类型 取消标志
    123 基础 1.
    222 基础 0
    234 混合的 1.
    345 混合的 1.

    现在,我想计算取消的百分比,但按订阅类型分组。 我想把它做成一种格式,这样我就可以很容易地根据订阅类型分组的百分比创建一个条形图。

    2 回复  |  直到 9 月前
        1
  •  2
  •   mozway    9 月前

    使用a groupby.mean :

    out = df.groupby('Subscription type')['Cancellation flag'].mean().mul(100)
    

    输出:

    Subscription type
    Basic      50.0
    Hybrid    100.0
    Name: Cancellation flag, dtype: float64
    

    那么 plot.bar :

    out.plot.bar()
    

    enter image description here

    或直接与 seaborn.barplot :

    import seaborn as sns
    sns.barplot(df, x='Subscription type', y='Cancellation flag',
                estimator='mean', errorbar=None)
    

    输出:

    enter image description here

        2
  •  0
  •   Explants    9 月前

    我没有时间编写代码,但你能试着获取不同类型的索引,将其附加到列表中,然后添加并除以列表中的项目数吗?