Like numpy.percentile, but:

    * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.]
    * scalar q not supported (q must be iterable)
    * optional weights on x
962630
def quantile(x, q, weights=None):
    
    if weights is None:
        return np.percentile(x, [100. * qi for qi in q])
    else:
        idx = np.argsort(x)
        xsorted = x[idx]
        cdf = np.add.accumulate(weights[idx])
        cdf /= cdf[-1]
        return np.interp(q, cdf, xsorted).tolist()
491258
def normalize_qvalue(q)
      (q == 1 || q == 0) && q.is_a?(Float) ? q.to_i : q
    end
282093
def _check_percentile(self, q):
        

        msg = ("percentiles should all be in the interval [0, 1]. "
               "Try {0} instead.")
        q = np.asarray(q)
        if q.ndim == 0:
            if not 0 <= q <= 1:
                raise ValueError(msg.format(q / 100.0))
        else:
            if not all(0 <= qs <= 1 for qs in q):
                raise ValueError(msg.format(q / 100.0))
        return q
203585
def get_value_at_percentile(self, percentile):
        '''
        '''
        count_at_percentile = self.get_target_count_at_percentile(percentile)
        total = 0
        for index in range(self.counts_len):
            total += self.get_count_at_index(index)
            if total >= count_at_percentile:
                value_at_index = self.get_value_from_index(index)
                if percentile:
                    return self.get_highest_equivalent_value(value_at_index)
                return self.get_lowest_equivalent_value(value_at_index)
        return 0
1022304
def rolling_percentileofscore(series, window, min_periods=None):
    """"""
    import scipy.stats as stats

    def _percentile(arr):
        score = arr[-1]
        vals = arr[:-1]
        return stats.percentileofscore(vals, score)

    notnull = series.dropna()
    min_periods = min_periods or window
    if notnull.empty:
        return pd.Series(np.nan, index=series.index)
    else:
        return pd.rolling_apply(notnull, window, _percentile, min_periods=min_periods).reindex(series.index)
52220
def q(self, val):
        
        self._q = np.asarray(val)
        self.Q = cumsum(val)
729502
def param_describe(params, quant=95, axis=0):
    """"""
    par = np.mean(params, axis=axis)
    lo, up = perc(quant)
    p_up = np.percentile(params, up, axis=axis)
    p_lo = np.percentile(params, lo, axis=axis)
    return par, p_lo, p_up
506711
def Percentile(pmf, percentage):
    
    p = percentage / 100.0
    total = 0
    for val, prob in pmf.Items():
        total += prob
        if total >= p:
            return val
276803
def generate_numeric_range(items, lower_bound, upper_bound):
    

    quantile_grid = create_quantiles(items, lower_bound, upper_bound)
    labels, bounds = (zip(*quantile_grid))
    ranges = ((label, NumericRange(*bound))
              for label, bound in zip(labels, bounds))
    return ranges
120876
def _geoville_index_by_percentile(self, data, percentile):
        
        # no_obs = bn.allnan(arr_tmp["data"], axis=0)
        data_tmp = np.array(data, copy=True)
        valid_obs = np.sum(np.isfinite(data_tmp), axis=0)
        # replace NaN with maximum
        max_val = np.nanmax(data_tmp) + 1
        data_tmp[np.isnan(data_tmp)] = max_val
        # sort - former NaNs will move to the end
        ind_tmp = np.argsort(data_tmp, kind="mergesort", axis=0)
        # desired position as well as floor and ceiling of it
        k_arr = (valid_obs - 1) * (percentile / 100.0)
        k_arr = np.where(k_arr < 0, 0, k_arr)
        f_arr = np.floor(k_arr + 0.5)
        f_arr = f_arr.astype(np.int)
        # get floor value of reference band and index band
        ind = f_arr.astype("int16")
        y_val, x_val = ind_tmp.shape[1], ind_tmp.shape[2]
        y_val, x_val = np.ogrid[0:y_val, 0:x_val]
        idx = np.where(valid_obs == 0, self.max_index, ind_tmp[ind, y_val, x_val])
        return idx
1164797
public double quantile(double p) {
        if (nd > 0) {
            update();
        }
        int jl = 0, jh = nq - 1, j;
        while (jh - jl > 1) {
            j = (jh + jl) >> 1;
            if (p > pval[j]) {
                jl = j;
            } else {
                jh = j;
            }
        }
        j = jl;
        double q = qile[j] + (qile[j + 1] - qile[j]) * (p - pval[j]) / (pval[j + 1] - pval[j]);
        return Math.max(qile[0], Math.min(qile[nq - 1], q));
    }
159335
def non_unique_bin_edges_error(func):
    
    message = """

    An error occurred while computing bins/quantiles on the input provided.
    This usually happens when the input contains too many identical
    values and they span more than one quantile. The quantiles are choosen
    to have the same number of records each, but the same value cannot span
    multiple quantiles. Possible workarounds are:
    1 - Decrease the number of quantiles
    2 - Specify a custom quantiles range, e.g. [0, .50, .75, 1.] to get unequal
        number of records per quantile
    3 - Use 'bins' option instead of 'quantiles', 'bins' chooses the
        buckets to be evenly spaced according to the values themselves, while
        'quantiles' forces the buckets to have the same number of records.
    4 - for factors with discrete values use the 'bins' option with custom
        ranges and create a range for each discrete value
    Please see utils.get_clean_factor_and_forward_returns documentation for
    full documentation of 'bins' and 'quantiles' options.

"""

    def dec(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except ValueError as e:
            if 'Bin edges must be unique' in str(e):
                rethrow(e, message)
            raise
    return dec
315234
def _getPercentile(points, n, interpolate=False):
    
    sortedPoints = sorted(not_none(points))
    if len(sortedPoints) == 0:
        return None
    fractionalRank = (n/100.0) * (len(sortedPoints) + 1)
    rank = int(fractionalRank)
    rankFraction = fractionalRank - rank

    if not interpolate:
        rank += int(math.ceil(rankFraction))

    if rank == 0:
        percentile = sortedPoints[0]
    elif rank - 1 == len(sortedPoints):
        percentile = sortedPoints[-1]
    else:
        percentile = sortedPoints[rank - 1]  # Adjust for 0-index

    if interpolate:
        if rank != len(sortedPoints):  # if a next value exists
            nextValue = sortedPoints[rank]
            percentile = percentile + rankFraction * (nextValue - percentile)

    return percentile
1192375
def _PopulateQuantilesHistogram(self, hist, nums):
    
    if not nums:
      return
    num_quantile_buckets = 10
    quantiles_to_get = [
        x * 100 / num_quantile_buckets for x in range(num_quantile_buckets + 1)
    ]
    quantiles = np.percentile(nums, quantiles_to_get)
    hist.type = self.histogram_proto.QUANTILES
    quantiles_sample_count = float(len(nums)) / num_quantile_buckets
    for low, high in zip(quantiles, quantiles[1:]):
      hist.buckets.add(
          low_value=low, high_value=high, sample_count=quantiles_sample_count)
630535
private double allowableError(int rank) {
        // NOTE: according to CKMS, this should be count, not size, but this
        // leads
        // to error larger than the error bounds. Leaving it like this is
        // essentially a HACK, and blows up memory, but does "work".
        // int size = count;
        int size = sample.size();
        double minError = size + 1;

        for (Quantile q : quantiles) {
            double error;
            if (rank <= q.quantile * size) {
                error = q.u * (size - rank);
            } else {
                error = q.v * rank;
            }
            if (error < minError) {
                minError = error;
            }
        }

        return minError;
    }
895776
def trimsquants(self, col: str, sup: float):
        
        try:
            self.df = self._trimquants(col, None, sup)
        except Exception as e:
            self.err(e, self.trimsquants, "Can not trim superior quantiles")
342524
def _numpy_index_by_percentile(self, data, percentile):
        
        data_perc_low = np.nanpercentile(data, percentile, axis=0, interpolation=self.interpolation)

        indices = np.empty(data_perc_low.shape, dtype=np.uint8)
        indices[:] = np.nan

        abs_diff = np.where(np.isnan(data_perc_low), np.inf, abs(data - data_perc_low))

        indices = np.where(np.isnan(data_perc_low), self.max_index, np.nanargmin(abs_diff, axis=0))

        return indices