python, find confidence interval around median
Asked Answered
L

1

7

How do I find confidence interval around median for my data in python?

Say I have array

a = np.array([24, 38, 61, 22, 16, 57, 31, 29, 35])

I would like to find 80% confidence interval around median. How do I do it in python?

Lincolnlincolnshire answered 12/12, 2016 at 13:39 Comment(1)
B
2

My implementation of this procedure to calculate the confidence interval around the median.

For your example, set cutoff=0.8. This requires python > 3 and pandas > 1.
It assumes that you pass the array as a pd.Series.

import statistics, math
import pandas as pd 

def median_confidence_interval(dx,cutoff=.95):
    ''' cutoff is the significance level as a decimal between 0 and 1'''
    dx = dx.sort_values(ascending=True, ignore_index=True)
    factor = statistics.NormalDist().inv_cdf((1+cutoff)/2)
    factor *= math.sqrt(len(df)) # avoid doing computation twice

    lix = round(0.5*(len(dx)-factor))
    uix = round(0.5*(1+len(dx)+factor))

    return (dx[lix],dx[uix])

a = np.array([24, 38, 61, 22, 16, 57, 31, 29, 35])
print(median_confidence_interval(df,cutoff=0.8))
# (29,57)
Basidiospore answered 20/5, 2020 at 18:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.