Home > Enterprise >  How to count percentile of distribution in python
How to count percentile of distribution in python

Time:09-22

Is there any python/numpy function that calculates n-th percentile of given probability distribution?

# Like This
distr = [.2, .6, .2]
do_some_magic(distr, 50)  # 1
distr = [.1, .1, .6, .2]
do_some_magic(distr, 50)  # 2

CodePudding user response:

Yes, you can use scipy's percentileofscore.

from scipy.stats import percentileofscore

distr = [.2, .6, .2]

print(percentileofscore(distr,50)/100)
1.0

CodePudding user response:

Try following options

NumPy Approach:

import numpy as np


distr = np.array([.2, .6, .2])
percentile = np.percentile(distr, 50)

print(percentile)

Pythonic Approach:

import math


def percentile(data, perc: int):
    size = len(data)
    return sorted(data)[int(math.ceil((size * perc) / 100)) - 1]

distr = [.2, .6, .2]

print(percentile(distr, 50))

Output: 0.2

  • Related