Return the bin of a certain value after splitting into Pandas bins after CUT or value_counts()

Viewed 48

Say I split my frame using df.value_counts(bins=10) this is how it looks

Values_mean
(53.649, 90.21]                  5127
(35.369, 53.649]                 4285
(90.21, 108.49]                  3559
(108.49, 126.77]                 2579
(866.77, 935.05]                 1526
(199.891, 218.171]               1304
(218.171, 251.451]                506
(-1.46699, 17.089]                478
(251.451, 284.732]                 30
(284.732, 343.012]                  7
Name: Values_mean, dtype: int64

now I want to find out where the value : newVal=38.54 would fit and in which percentile of data is it .

example : The CUMSUM of these values = 19401 newVal=38.54 will belong to the Bin :

(35.369, 53.649]                 4285

so it means 4285/19401 where it belongs to 0.2208 of the data.

Thank you in advance

1 Answers

You want to sort the index then use the right attribute to get at the right hand side of the intervals. Then use searchsorted to find where the search value fits in. Use that information to figure out the count value.

def ptile(x, s):
    total = s.sum()
    s = s.sort_index()
    i = s.index.right.searchsorted(x)
    return s.iloc[i] / total

ptile(38.54, s)

0.2208649038709345
Related