Return the n-th percentile of the given data

    Assume that the data are already sorted
557461
def percentile(data, n):
    

    size = len(data)
    idx = (n / 100.0) * size - 0.5

    if idx < 0 or idx > size:
        raise StatisticsError("Too few data points ({}) for {}th percentile".format(size, n))

    return data[int(idx)]
491219
public int getValueAtPercentile(double percentile) {
        int permyriad = (int) (percentile * 100);
        switch (permyriad) {
            case 0: return p0;
            case 500: return p5;
            case 1000: return p10;
            case 1500: return p15;
            case 2000: return p20;
            case 2500: return p25;
            case 3000: return p30;
            case 3500: return p35;
            case 4000: return p40;
            case 4500: return p45;
            case 5000: return p50;
            case 5500: return p55;
            case 6000: return p60;
            case 6500: return p65;
            case 7000: return p70;
            case 7500: return p75;
            case 8000: return p80;
            case 8500: return p85;
            case 9000: return p90;
            case 9500: return p95;
            case 9900: return p99;
            case 9950: return p99_5;
            case 9990: return p99_9;
            case 9995: return p99_95;
            case 9999: return p99_99;
            case 10000: return p100;
            default: throw new IllegalArgumentException("Percentile (" + percentile + ") is not currently cached");
        }
    }
518551
def percentiles(self, percentiles):
    """"""
    try:
      scores = [0.0]*len(percentiles)

      if self.count > 0:
        values = self.samples()
        values.sort()

        for i in range(len(percentiles)):
          p = percentiles[i]
          pos = p * (len(values) + 1)
          if pos < 1:
            scores[i] = values[0]
          elif pos > len(values):
            scores[i] = values[-1]
          else:
            upper, lower = values[int(pos - 1)], values[int(pos)]
            scores[i] = lower + (pos - floor(pos)) * (upper - lower)

      return scores
    except IndexError:
      return [float('NaN')] * len(percentiles)
567673
def get_top(self, stat, n):
        """'"""
        return sorted(self.stats, key=lambda x: getattr(x, stat), reverse=True)[:n]
654626
def fast_median(a):
    
    a = checkma(a)
    #return scoreatpercentile(a.compressed(), 50)
    if a.count() > 0:
        out = np.percentile(a.compressed(), 50)
    else:
        out = np.ma.masked
    return out
378643
def ptake(n: int, xs: Iterable[T]) -> Iterable[T]:
    
    return tqdm(take(n, xs), total=n)
298052
def percent_rank(expr, sort=None, ascending=True):
    
    return _rank_op(expr, PercentRank, types.float64, sort=sort, ascending=ascending)
550452
def get_median(data_np):
    """"""
    i = np.isfinite(data_np)
    if not np.any(i):
        return np.nan
    return np.median(data_np[i])
464173
def maskedNanPercentile(maskedArray, percentiles, *args, **kwargs):
    

    #https://docs.scipy.org/doc/numpy/reference/maskedarray.generic.html#accessing-the-data
    awm = ArrayWithMask.createFromMaskedArray(maskedArray)

    maskIdx = awm.maskIndex()
    validData = awm.data[~maskIdx]

    if len(validData) >= 1:
        result = np.nanpercentile(validData, percentiles, *args, **kwargs)
    else:
        # If np.nanpercentile on an empty list only returns a single Nan. We correct this here.
        result = len(percentiles) * [np.nan]

    assert len(result) == len(percentiles), \
        "shape mismatch: {} != {}".format(len(result), len(percentiles))

    return result
1205302
public static <T extends Comparable<? super T>> Collector<T, ?, Optional<T>> percentile(double percentile) {
        return percentile(percentile, t -> t, naturalOrder());
    }
534229
public static <T> Collector<T, ?, Optional<T>> percentile(double percentile, Comparator<? super T> comparator) {
        return percentile(percentile, t -> t, comparator);
    }
772370
def winsorize(row, min_percentile, max_percentile):
    
    a = row.copy()
    nan_count = isnan(row).sum()
    nonnan_count = a.size - nan_count

    # NOTE: argsort() sorts nans to the end of the array.
    idx = a.argsort()

    # Set values at indices below the min percentile to the value of the entry
    # at the cutoff.
    if min_percentile > 0:
        lower_cutoff = int(min_percentile * nonnan_count)
        a[idx[:lower_cutoff]] = a[idx[lower_cutoff]]

    # Set values at indices above the max percentile to the value of the entry
    # at the cutoff.
    if max_percentile < 1:
        upper_cutoff = int(ceil(nonnan_count * max_percentile))
        # if max_percentile is close to 1, then upper_cutoff might not
        # remove any values.
        if upper_cutoff < nonnan_count:
            start_of_nans = (-nan_count) if nan_count else None
            a[idx[upper_cutoff:start_of_nans]] = a[idx[upper_cutoff - 1]]

    return a
905772
public static Map<Percentage, Long> percentiles(final long[] sortedArray) {
        N.checkArgNotNullOrEmpty(sortedArray, "The spcified 'sortedArray' can not be null or empty");

        final int len = sortedArray.length;
        final Map<Percentage, Long> m = new LinkedHashMap<>(N.initHashCapacity(Percentage.values().length));

        for (Percentage p : Percentage.values()) {
            m.put(p, sortedArray[(int) (len * p.doubleValue())]);
        }

        return ImmutableMap.of(m);
    }
942511
def scoreatpercentile(inlist, percent):
    
    if percent > 1:
        print("\nDividing percent>1 by 100 in lscoreatpercentile().\n")
        percent = percent / 100.0
    targetcf = percent * len(inlist)
    h, lrl, binsize, extras = histogram(inlist)
    cumhist = cumsum(copy.deepcopy(h))
    for i in range(len(cumhist)):
        if cumhist[i] >= targetcf:
            break
    score = binsize * ((targetcf - cumhist[i - 1]) / float(h[i])) + (lrl + binsize * i)
    return score
210471
def nPercentile(requestContext, seriesList, n):
    """"""
    assert n, 'The requested percent is required to be greater than 0'

    results = []
    for s in seriesList:
        # Create a sorted copy of the TimeSeries excluding None values in the
        # values list.
        s_copy = TimeSeries(s.name, s.start, s.end, s.step,
                            sorted(not_none(s)))
        if not s_copy:
            continue    # Skip this series because it is empty.

        perc_val = _getPercentile(s_copy, n)
        if perc_val is not None:
            name = 'nPercentile(%s, %g)' % (s_copy.name, n)
            point_count = int((s.end - s.start)/s.step)
            perc_series = TimeSeries(name, s_copy.start, s_copy.end,
                                     s_copy.step, [perc_val] * point_count)
            perc_series.pathExpression = name
            results.append(perc_series)
    return results
954425
public static <T> Collector<T, ?, Optional<T>> median(Comparator<? super T> comparator) {
        return percentile(0.5, comparator);
    }
1258139
def removeBetweenPercentile(requestContext, seriesList, n):
    
    if n < 50:
        n = 100 - n

    transposed = list(zip_longest(*seriesList))

    lowPercentiles = [_getPercentile(col, 100-n) for col in transposed]
    highPercentiles = [_getPercentile(col, n) for col in transposed]

    return [l for l in seriesList
            if sum([not lowPercentiles[index] < val < highPercentiles[index]
                    for index, val in enumerate(l)]) > 0]