在大熊猫中将列除以第99百分位数

时间:2017-01-18 05:21:54

标签: python pandas

我在pandas数据框中有一个表。 DF

LeafId  pidx    pidy    count    value
1       10      20       2         5
1       10      35       10        10
1       10      26       30        15
1       10      40       11        20
1       15      20       25        25
1       30      70       12        30
1       40      20       27        35

我希望通过将值除以该列的第99个百分位来规范化countvalue列。 在除法之后,它的值超过1,使其为1。

我正在尝试的是

count_quantile_99 = df['count'].quantile(.99)    #finding 99th percentile of count & storing in variable
    value_quantile_99 = df['count'].quantile(.99)    #finding 99th percentile of value & storing in variable

df['count'] = df.count.div(count_quantile_99 )
df['value'] = df.value.div(value_quantile_99)

我不知道这是否是正确的做法。  还寻找任何其他更好的方法来找到第99百分位。

此外,只要我在count列和value列中的值大于1 怎么做到1

2 个答案:

答案 0 :(得分:3)

DataFrame.clip_upper的解决方案:

df1 = df[['count', 'value']]
df[['count','value']] = df1.div(df1.quantile(.99)).clip_upper(1)
print (df)
   LeafId  pidx  pidy     count     value
0       1    10    20  0.067069  0.144092
1       1    10    35  0.335345  0.288184
2       1    10    26  1.000000  0.432277
3       1    10    40  0.368880  0.576369
4       1    15    20  0.838364  0.720461
5       1    30    70  0.402414  0.864553
6       1    40    20  0.905433  1.000000

答案 1 :(得分:2)

d1 = df[['count', 'value']]
d1 = d1.div(d1.quantile(.99))
df.update(d1.where(d1 < 1, 1))

print(df)

   LeafId  pidx  pidy     count     value
0       1    10    20  0.067069  0.144092
1       1    10    35  0.335345  0.288184
2       1    10    26  1.000000  0.432277
3       1    10    40  0.368880  0.576369
4       1    15    20  0.838364  0.720461
5       1    30    70  0.402414  0.864553
6       1    40    20  0.905433  1.000000
相关问题