首页 > 解决方案 > 计算熊猫中列的四分位数类别

问题描述

我有一个如下所示的数据框

东风:

product_x  year     total_price      total_sale
A          2016     50               200           
B          2016     200              100           
A          2017     250              250           
B          2017     1000             300           
A          2018     100              50           
B          2018     900              600
K          2016     20               300
D          2016     100              450

在上面的数据框中,我想添加名为 total_sale_Quartile 的新列。

计算 total_sale_Quartile 的说明。

排序 total_sale 如下所示

50, 100, 200, 250, 300, 300, 450, 600

Q1 = 50 to 100
Q2 = 101 to 250
Q3 = 251 to 300
Q4 = 301 to 600

预期输出:

product_x  year     total_price      total_sale   total_sale_Quartile
A          2016     50               200          Q2
B          2016     200              100          Q1    
A          2017     250              250          Q2  
B          2017     1000             300          Q3   
A          2018     100              50           Q1    
B          2018     900              600          Q4
K          2016     20               300          Q3
D          2016     100              450          Q4

标签: pythonpandasdataframe

解决方案


使用,pd.cut带有可选参数include_lowest=True将值从total_saleinto分类Quartiles

df['total_sale_Quartile'] = (
    pd.cut(
        df['total_sale'], bins=[50, 100, 250, 300, 600],
        labels=['Q1', 'Q2', 'Q3', 'Q4'], include_lowest=True)
)

或者,pd.qcut如果您想仅根据分位数范围对列进行分类,请使用:

df['total_sale_Quartile'] = (
    pd.qcut(df['total_sale'], 4, labels=['Q1', 'Q2', 'Q3', 'Q4'])
)

结果:

# print(df)
  product_x  year  total_price  total_sale total_sale_Quartile
0         A  2016           50         200                  Q2
1         B  2016          200         100                  Q1
2         A  2017          250         250                  Q2
3         B  2017         1000         300                  Q3
4         A  2018          100          50                  Q1
5         B  2018          900         600                  Q4
6         K  2016           20         300                  Q3
7         D  2016          100         450                  Q4

推荐阅读