Search code examples
pythonnumpyscipypercentilefunctools

functools: computing inter quartile range


I use functools to compute percentiles this way:

import functools
percentiles = tuple(functools.partial(np.percentile, q=q) for q in (75, 85, 95))

percentiles
(functools.partial(<function percentile at 0x7f91fe1e9730>, q=75),
 functools.partial(<function percentile at 0x7f91fe1e9730>, q=85),
 functools.partial(<function percentile at 0x7f91fe1e9730>, q=95))

so that anywhere in my code I can compute percentiles like so:

stat_functions =  percentiles

Then I want to add inter quartile to my percentile function, but adding [75-25] compute the mean instead.

percentiles = tuple(functools.partial(np.percentile, q=q) for q in (75, 85, 95, 75-25))

percentiles
(functools.partial(<function percentile at 0x7f91fe1e9730>, q=75),
 functools.partial(<function percentile at 0x7f91fe1e9730>, q=85),
 functools.partial(<function percentile at 0x7f91fe1e9730>, q=95),
 functools.partial(<function percentile at 0x7f91fe1e9730>, q=50))

My intention is to get the value of inter quartile range not the mean. How do I fix this?


Solution

  • I added an iqr function to scipy.stats a while back.

    You can modify the comprehension as follows:

    percentiles = tuple(ss.iqr if q is None else functools.partial(np.percentile, q=q) for q in (75, 85, 95, None))