2

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?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264

2 Answers2

0

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))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

You can't get the IQR with a single call to percentile: it's the difference between two percentiles. The closest you can do is to compute the 25th and 75th percentile in one call:

functools.partial(np.percentile, q=(25, 75))

You can modify your comprehension to construct a function wrapped in np.diff when q is a tuple:

percentiles = tuple(lambda x: np.diff(np.percentile(x, q=q)) if isinstance(q, tuple) else functools.partial(np.percentile, q=q) for q in (75, 85, 95, (25, 75)))
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264