【问题标题】:How can I create a table view of percentiles by date using Python如何使用 Python 按日期创建百分位数的表格视图
【发布时间】:2020-07-03 22:54:44
【问题描述】:

使用Python/Jupyter Notebook,我想创建一个百分位数的表格视图grouped by date

数据集如下所示:

count date
12    2020-02-01
15    2020-02-01
20    2020-02-02
...

我正在寻找的结果如下所示:

      2020-02-01   2020-02-02
25%     12.5           15        
50%     15             16
75%     17.5           17
95%     19             18.5

我见过quantile 函数,但不知道如何在表格视图中排列它。

【问题讨论】:

    标签: python pandas pandas-groupby quantile


    【解决方案1】:

    使用DataFrameGroupBy.quantileDataFrame.unstack - 最后一次数据清理 - 通过DataFrame.rename_axis 删除列名称并通过f-strings 将百分位数动态转换为百分比:

    df = (df.groupby('date')['count']
            .quantile([.25,.5,.75,.95])
            .unstack(0)
            .rename_axis(None, axis=1)
            .rename(lambda x: f'{int(x * 100)}%'))
    
    print (df)
         2020-02-01  2020-02-02
    25%       12.75        20.0
    50%       13.50        20.0
    75%       14.25        20.0
    95%       14.85        20.0
    

    【讨论】:

      【解决方案2】:

      你也可以使用.describe()

      import pandas as pd 
      
      # Creating the dataframe  
      df = pd.DataFrame({"count":[12, 15, 20],
                         "date":['2020-02-01', '2020-02-01', '2020-02-02']})
      
      df2 = df.groupby('date')['count'].describe(percentiles=[.25, .5, .75, .95])
      
      # Filtering out the needed columns
      df2 = df2[['25%', '50%', '75%', '95%']].T
      
      # output
      date  2020-02-01  2020-02-02
      25%        12.75        20.0
      50%        13.50        20.0
      75%        14.25        20.0
      95%        14.85        20.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-30
        • 1970-01-01
        • 2018-01-26
        • 2021-03-30
        • 2014-11-10
        • 2017-05-25
        • 2020-10-13
        • 1970-01-01
        相关资源
        最近更新 更多