【问题标题】:Pandas goupby and percentage on same dataframePandas groupby和同一数据框上的百分比
【发布时间】:2020-06-26 10:04:37
【问题描述】:

我最近刚开始学习 pandas 和 numpy 以及我需要对数据进行分组的用例 根据日期并计算每月状态上升的时间百分比(即 count(up)/total_count())。

    date                                             status
   2017-08                                            up
   2017-08                                            down
   2017-08                                             up
   2017-08                                             up   
   2017-09                                             down
   2017-09                                             up   
   2017-09                                             down
   2017-09                                             up

date.      percentage
2017-08     75
2017-09     50

由于我具有软件工程背景,因此我正在逐步采用先计数然后除以得到最终输出的方法。但是,当我尝试打印 count df 时,我看到 count 列没有任何列标题。我怎样才能得到它的标题?有没有一种方法可以在一个命令中完成?

df_up = df[df['status'] == "up"]
count_up = df_up.groupby(['date']).date.count()
total_count = df.groupby(['date']).date.count() 
print (count_up)

date
2017-08     705
2017-09    5598
2017-10    3419
2017-11    1476
2017-12     758

【问题讨论】:

    标签: python pandas numpy pandas-groupby


    【解决方案1】:

    我们有pd.crosstab

    P_df=pd.crosstab(df.date,df.status,normalize='index')*100
    status   down    up
    date               
    2017-08  25.0  75.0
    2017-09  50.0  50.0
    

    【讨论】:

      【解决方案2】:
       res=(df.groupby('date')['status'].value_counts(normalize=True).unstack('status')*100).astype(int).reset_index()
      
      status     date  down  up
      0       2017-08    25  75
      1       2017-09    50  50
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-13
        • 1970-01-01
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 2014-06-16
        相关资源
        最近更新 更多