计算熊猫百分比

时间:2019-04-24 08:34:16

标签: python pandas

我有一个名为join2的数据集

   pd.DataFrame({'id' : [197, 220, 278, 300, 303, 318, 326, 339, 354, 382, 407, 432, 433, 440, 441, 447, 454, 501, 504, 508, 550, 564,601, 602, 606,628,643, 668,688,718], 'count' : [10, 5, 5, 5,15, 5, 5, 25, 10, 5, 5, 5, 20, 15, 5, 5, 10, 10, 10, 5, 5,5,5, 5,10,10,5, 10, 15, 5]
, 'sum' : [6, 3, 5, 3, 11, 1, 4, 13, 4, 3, 1, 5, 16, 9, 1, 5, 8, 10, 10, 4, 5, 5, 5, 4, 6, 10, 1, 6, 15, 5],
'percentage' : [60.0,60.0,100.0,60.0,73.33333333333333,20.0,80.0,52.0,40.0,60.0,20.0,100.0,80.0,60.0,20.0,100.0,80.0,100.0,100.0,80.0,100.0,100.0, 100.0,80.0, 60.0, 100.0, 20.0, 60.0, 100.0, 100.0]})

,我想添加一个名为percentile的新列。

我都尝试过


    join2['pctile'] = join2['percentage'].rank(pct=True)
and 
    sz = join2['percentage'].size-1
    join2['pctile'] = join2['percentage'].rank(method='max').apply(lambda x: 100.0*(x-1)/sz)

但是我得到的百分位数不正确。百分比应为25%(百分比为60%)。我该怎么解决?

2 个答案:

答案 0 :(得分:0)

您要寻找的是DataFrame.quantile()

df1 = pd.DataFrame({'id' : [197, 220, 278,300,303], 'count' : [10,5,5,5,15], 'sum' : [6,3,5,3,11], 'percentage' : [60,60,100,60,73]})

达到70%的分位数

df1.quantile(0.7)

答案 1 :(得分:0)

使用此method='average'代替'method='min'

df['pctile'] = df['percentage'].rank(method='average').apply(lambda x: 100.0*(x-1)/sz)

输出:

>>> df
    id  count  sum  percentage  pctile
0  197     10    6          60    25.0
1  220      5    3          60    25.0
2  278      5    5         100   100.0
3  300      5    3          60    25.0
4  303     15   11          73    75.0

点击此处查看link.rank()的熊猫文档