query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
deducting the median from each column
|
python
|
def median(data, freq_col=1):
"""Compute the median of the <freq_col>'th column of the values is <data>.
>>> chart_data.median([(10,20), (20,4), (30,5)], 0)
20
>>> chart_data.median([(10,20), (20,4), (30,5)], 1)
5.
"""
nr_data = _nr_data(data, freq_col)
median_idx = nr_data / 2
i = 0
for d in data:
i += d[freq_col]
if i >= median_idx:
return d
raise Exception("??? median ???")
|
https://github.com/ska-sa/purr/blob/4c848768d0485d0f88b30850d0d5372221b21b66/Purr/Plugins/local_pychart/chart_data.py#L319-L335
|
deducting the median from each column
|
python
|
def median(x):
"""
Return a numpy array of column median.
It does not affect if the array is one dimension
Parameters
----------
x : ndarray
A numpy array instance
Returns
-------
ndarray
A 1 x n numpy array instance of column median
Examples
--------
>>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
>>> np.array_equal(median(a), [2, 5, 8])
True
>>> a = np.array([1, 2, 3])
>>> np.array_equal(median(a), [1, 2, 3])
True
"""
if x.ndim > 1 and len(x[0]) > 1:
return np.median(x, axis=1)
return x
|
https://github.com/lambdalisue/maidenhair/blob/d5095c1087d1f4d71cc57410492151d2803a9f0d/src/maidenhair/statistics/__init__.py#L66-L93
|
deducting the median from each column
|
python
|
def median(self, **kwargs):
"""Returns median of each column or row.
Returns:
A new QueryCompiler object containing the median of each column or row.
"""
if self._is_transposed:
kwargs["axis"] = kwargs.get("axis", 0) ^ 1
return self.transpose().median(**kwargs)
# Pandas default is 0 (though not mentioned in docs)
axis = kwargs.get("axis", 0)
func = self._build_mapreduce_func(pandas.DataFrame.median, **kwargs)
return self._full_axis_reduce(axis, func)
|
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/backends/pandas/query_compiler.py#L1251-L1263
|
deducting the median from each column
|
python
|
def median(ls):
"""
Takes a list and returns the median.
"""
ls = sorted(ls)
return ls[int(floor(len(ls)/2.0))]
|
https://github.com/emilydolson/avida-spatial-tools/blob/7beb0166ccefad5fa722215b030ac2a53d62b59e/avidaspatial/utils.py#L333-L338
|
deducting the median from each column
|
python
|
def median(ma):
""" do it row by row, to save memory...."""
_median = 0*ma[0].filled(fill_value=0)
for i in range(ma.shape[-1]):
t=xmedian(ma[:,:,i])
_median[:,i]=t
t=None
return _median
|
https://github.com/OSSOS/MOP/blob/94f91d32ad5ec081d5a1ebd67604a838003465af/src/jjk/preproc/median.py#L3-L10
|
deducting the median from each column
|
python
|
def median(self, values, axis=0, average=True):
"""compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true, the average of the two central values is taken for groups with an even key-count
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
mid_2 = self.index.start + self.index.stop
hi = (mid_2 ) // 2
lo = (mid_2 - 1) // 2
#need this indirection for lex-index compatibility
sorted_group_rank_per_key = self.index.sorted_group_rank_per_key
def median1d(slc):
#place values at correct keys; preconditions the upcoming lexsort
slc = slc[self.index.sorter]
#refine value sorting within each keygroup
sorter = np.lexsort((slc, sorted_group_rank_per_key))
slc = slc[sorter]
return (slc[lo]+slc[hi]) / 2 if average else slc[hi]
values = np.asarray(values)
if values.ndim>1: #is trying to skip apply_along_axis somewhat premature optimization?
values = np.apply_along_axis(median1d, axis, values)
else:
values = median1d(values)
return self.unique, values
|
https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L343-L382
|
deducting the median from each column
|
python
|
def median(lst):
""" Calcuates the median value in a @lst """
#: http://stackoverflow.com/a/24101534
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0
|
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/debug/stats.py#L47-L56
|
deducting the median from each column
|
python
|
def median(data):
"""Calculate the median of a list."""
data.sort()
num_values = len(data)
half = num_values // 2
if num_values % 2:
return data[half]
return 0.5 * (data[half-1] + data[half])
|
https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L60-L67
|
deducting the median from each column
|
python
|
def median(data):
"""Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
i = n // 2
return (data[i - 1] + data[i]) / 2
|
https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L194-L210
|
deducting the median from each column
|
python
|
def median(self, **kwargs):
"""
Compute median of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex
"""
try:
return self._cython_agg_general('median', **kwargs)
except GroupByError:
raise
except Exception: # pragma: no cover
def f(x):
if isinstance(x, np.ndarray):
x = Series(x)
return x.median(axis=self.axis, **kwargs)
with _group_selection_context(self):
return self._python_agg_general(f)
|
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/core/groupby/groupby.py#L1159-L1176
|
deducting the median from each column
|
python
|
def median(array):
"""
Return the median value of a list of numbers.
"""
n = len(array)
if n < 1:
return 0
elif n == 1:
return array[0]
sorted_vals = sorted(array)
midpoint = int(n / 2)
if n % 2 == 1:
return sorted_vals[midpoint]
else:
return (sorted_vals[midpoint - 1] + sorted_vals[midpoint]) / 2.0
|
https://github.com/ChrisCummins/labm8/blob/dd10d67a757aefb180cb508f86696f99440c94f5/labmath.py#L125-L141
|
deducting the median from each column
|
python
|
def median(self, name, **kwargs):
"""
Median of the distribution.
"""
data = self.get(name,**kwargs)
return np.percentile(data,[50])
|
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L294-L299
|
deducting the median from each column
|
python
|
def median_approx(self, expression, percentage=50., binby=[], limits=None, shape=default_shape, percentile_shape=256, percentile_limits="minmax", selection=False, delay=False):
"""Calculate the median , possibly on a grid defined by binby.
NOTE: this value is approximated by calculating the cumulative distribution on a grid defined by
percentile_shape and percentile_limits
:param expression: {expression}
:param binby: {binby}
:param limits: {limits}
:param shape: {shape}
:param percentile_limits: {percentile_limits}
:param percentile_shape: {percentile_shape}
:param selection: {selection}
:param delay: {delay}
:return: {return_stat_scalar}
"""
return self.percentile_approx(expression, 50, binby=binby, limits=limits, shape=shape, percentile_shape=percentile_shape, percentile_limits=percentile_limits, selection=selection, delay=delay)
|
https://github.com/vaexio/vaex/blob/a45b672f8287afca2ada8e36b74b604b9b28dd85/packages/vaex-core/vaex/dataframe.py#L1168-L1185
|
deducting the median from each column
|
python
|
def median(values):
"""Return median value for the list of values.
@param values: list of values for processing.
@return: median value.
"""
values.sort()
n = int(len(values) / 2)
return values[n]
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/intelhex/bench.py#L45-L52
|
deducting the median from each column
|
python
|
def median(data):
"""
Calculates the median of a list of integers or floating point numbers.
Args:
data: A list of integers or floating point numbers
Returns:
Sorts the list numerically and returns the middle number if the list has an odd number
of items. If the list contains an even number of items the mean of the two middle numbers
is returned.
"""
ordered = sorted(data)
length = len(ordered)
if length % 2 == 0:
return (
ordered[math.floor(length / 2) - 1] + ordered[math.floor(length / 2)]
) / 2.0
elif length % 2 != 0:
return ordered[math.floor(length / 2)]
|
https://github.com/bbusenius/Diablo-Python/blob/646ac5a6f1c79cf9b928a4e2a7979988698b6c82/simple_math/simple_math.py#L261-L281
|
deducting the median from each column
|
python
|
def median(self):
"""Compute median of groups, excluding missing values.
For multiple groupings, the result index will be a MultiIndex.
"""
self._prep_pandas_groupby()
return DataFrame.fromDataFrameRDD(
self._regroup_mergedRDD().values().map(
lambda x: x.median()), self.sql_ctx)
|
https://github.com/sparklingpandas/sparklingpandas/blob/7d549df4348c979042b683c355aa778fc6d3a768/sparklingpandas/groupby.py#L146-L154
|
deducting the median from each column
|
python
|
def median(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.median:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=num,
oper='median',
minimum=minimum,
maximum=maximum,
ref=ref
)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L180-L200
|
deducting the median from each column
|
python
|
def median(arr):
"""median of the values, must have more than 0 entries.
:param arr: list of numbers
:type arr: number[] a number array
:return: median
:rtype: float
"""
if len(arr) == 0:
sys.stderr.write("ERROR: no content in array to take average\n")
sys.exit()
if len(arr) == 1: return arr[0]
quot = len(arr)/2
rem = len(arr)%2
if rem != 0:
return sorted(arr)[quot]
return float(sum(sorted(arr)[quot-1:quot+1]))/float(2)
|
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/statistics/__init__.py#L24-L41
|
deducting the median from each column
|
python
|
def median(data):
"""
Return the median of numeric data, unsing the "mean of middle two" method.
If ``data`` is empty, ``0`` is returned.
Examples
--------
>>> median([1, 3, 5])
3.0
When the number of data points is even, the median is interpolated:
>>> median([1, 3, 5, 7])
4.0
"""
if len(data) == 0:
return None
data = sorted(data)
return float((data[len(data) // 2] + data[(len(data) - 1) // 2]) / 2.)
|
https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/helper/maths.py#L88-L108
|
deducting the median from each column
|
python
|
def median(values):
"""Return the middle value, when the values are sorted.
If there are an odd number of elements, try to average the middle two.
If they can't be averaged (e.g. they are strings), choose one at random.
>>> median([10, 100, 11])
11
>>> median([1, 2, 3, 4])
2.5
"""
n = len(values)
values = sorted(values)
if n % 2 == 1:
return values[n/2]
else:
middle2 = values[(n/2)-1:(n/2)+1]
try:
return mean(middle2)
except TypeError:
return random.choice(middle2)
|
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/utils.py#L459-L477
|
deducting the median from each column
|
python
|
def median(self):
"""Computes the median of a log-normal distribution built with the stats data."""
mu = self.mean()
ret_val = math.exp(mu)
if math.isnan(ret_val):
ret_val = float("inf")
return ret_val
|
https://github.com/soravux/scoop/blob/d391dfa62f47e49d48328ee9cf08aa114256fd33/scoop/_control.py#L82-L88
|
deducting the median from each column
|
python
|
def median(items):
"""Note: modifies the input list!"""
items.sort()
k = len(items)//2
if len(items) % 2 == 0:
return (items[k] + items[k - 1]) / 2
else:
return items[k]
|
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/step_detect.py#L885-L892
|
deducting the median from each column
|
python
|
def median_high(data):
"""Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
return data[n // 2]
|
https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L229-L240
|
deducting the median from each column
|
python
|
def median_fill(adf):
""" Looks at each row, and chooses the median. Honours
the Trump override/failsafe logic. """
ordpt = adf.values[0]
if not pd.isnull(ordpt):
return ordpt
fdmn = adf.iloc[1:-1].median()
if not pd.isnull(fdmn):
return fdmn
flspt = adf.values[-1]
if not pd.isnull(flspt):
return flspt
return nan
|
https://github.com/Equitable/trump/blob/a2802692bc642fa32096374159eea7ceca2947b4/trump/aggregation/symbol_aggs.py#L93-L108
|
deducting the median from each column
|
python
|
def median(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs):
"""Computes median across the DataFrame.
Args:
axis (int): The axis to take the median on.
skipna (bool): True to skip NA values, false otherwise.
Returns:
The median of the DataFrame. (Pandas series)
"""
axis = self._get_axis_number(axis) if axis is not None else 0
if numeric_only is not None and not numeric_only:
self._validate_dtypes(numeric_only=True)
return self._reduce_dimension(
self._query_compiler.median(
axis=axis,
skipna=skipna,
level=level,
numeric_only=numeric_only,
**kwargs
)
)
|
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/base.py#L1546-L1567
|
deducting the median from each column
|
python
|
def median_grouped(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the grouped mean of the ``num`` most recent values. Requires a
list.
USAGE:
.. code-block:: yaml
foo:
calc.median_grouped:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=num,
oper='median_grouped',
minimum=minimum,
maximum=maximum,
ref=ref
)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L249-L270
|
deducting the median from each column
|
python
|
def median(nums):
"""Return median.
With numbers sorted by value, the median is the middle value (if there is
an odd number of values) or the arithmetic mean of the two middle values
(if there is an even number of values).
Cf. https://en.wikipedia.org/wiki/Median
Parameters
----------
nums : list
A series of numbers
Returns
-------
int or float
The median of nums
Examples
--------
>>> median([1, 2, 3])
2
>>> median([1, 2, 3, 4])
2.5
>>> median([1, 2, 2, 4])
2
"""
nums = sorted(nums)
mag = len(nums)
if mag % 2:
mag = int((mag - 1) / 2)
return nums[mag]
mag = int(mag / 2)
med = (nums[mag - 1] + nums[mag]) / 2
return med if not med.is_integer() else int(med)
|
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/stats/_mean.py#L644-L680
|
deducting the median from each column
|
python
|
def mean(self):
"""return the median value"""
# XXX rename this method
if len(self.values) > 0:
return sorted(self.values)[len(self.values) / 2]
else:
return None
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L160-L166
|
deducting the median from each column
|
python
|
def median1d(self, param, return_errors=False):
""" Return median 1d marginalized parameters
Parameters
----------
name: str
The name of the parameter requested
return_errors: Optional, {bool, False}
If true, return a second and third parameter that represents the
lower and upper 90% error on the parameter.
Returns
-------
param: nump.ndarray or tuple
The requested parameter
"""
v = [self.mergers[m].median1d(param, return_errors=return_errors) for m in self.mergers]
if return_errors:
value, merror, perror = zip(*v)
return numpy.array(value), numpy.array(merror), numpy.array(perror)
else:
return numpy.array(v)
|
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/catalog/__init__.py#L137-L158
|
deducting the median from each column
|
python
|
def median_interp(interp_object):
"""
Find the median of the function represented as an interpolation object.
"""
new_grid = np.sort(np.concatenate([interp_object.x[:-1] + 0.1*ii*np.diff(interp_object.x)
for ii in range(10)]).flatten())
tmp_prop = np.exp(-(interp_object(new_grid)-interp_object.y.min()))
tmp_cumsum = np.cumsum(0.5*(tmp_prop[1:]+tmp_prop[:-1])*np.diff(new_grid))
median_index = min(len(tmp_cumsum)-3, max(2,np.searchsorted(tmp_cumsum, tmp_cumsum[-1]*0.5)+1))
return new_grid[median_index]
|
https://github.com/neherlab/treetime/blob/f6cdb58d19243a18ffdaa2b2ec71872fa00e65c0/treetime/utils.py#L129-L139
|
deducting the median from each column
|
python
|
def median(series):
"""
Returns the median value of a series.
Args:
series (pandas.Series): column to summarize.
"""
if np.issubdtype(series.dtype, np.number):
return series.median()
else:
return np.nan
|
https://github.com/kieferk/dfply/blob/6a858f066602735a90f8b6b85106bc39ceadc282/dfply/summary_functions.py#L153-L164
|
deducting the median from each column
|
python
|
def median(self, *args, **kwargs):
'''
geo.median(axis=None, out=None, overwrite_input=False)
axis : int, optional
Axis along which the medians are computed. The default (axis=None)
is to compute the median along a flattened version of the array.
out : ndarray, optional
Alternative output array in which to place the result. It must have
the same shape and buffer length as the expected output, but the
type (of the output) will be cast if necessary.
overwrite_input : bool, optional
If True, then allow use of memory of input array (a) for
calculations. The input array will be modified by the call to
median. This will save memory when you do not need to preserve the
contents of the input array. Treat the input as undefined, but it
will probably be fully or partially sorted. Default is False. Note
that, if `overwrite_input` is True and the input is not already an
ndarray, an error will be raised.
'''
return np.ma.median(self.raster, *args, **kwargs)
|
https://github.com/ozak/georasters/blob/0612bd91bb2a2cb2f1d59ba89c1ff131dae27d70/georasters/georasters.py#L593-L613
|
deducting the median from each column
|
python
|
def median_low(data):
"""Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
if n % 2 == 1:
return data[n // 2]
else:
return data[n // 2 - 1]
|
https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/statistics.py#L213-L226
|
deducting the median from each column
|
python
|
def median(numbers):
"""
Return the median of the list of numbers.
see: http://mail.python.org/pipermail/python-list/2004-December/294990.html
"""
# Sort the list and take the middle element.
n = len(numbers)
copy = sorted(numbers)
if n & 1: # There is an odd number of elements
return copy[n // 2]
else:
return (copy[n // 2 - 1] + copy[n // 2]) / 2.0
|
https://github.com/exhuma/python-cluster/blob/4c0ac14d9beafcd51f0d849151514083c296402f/cluster/util.py#L66-L78
|
deducting the median from each column
|
python
|
def weighted_median(d, w):
"""A utility function to find a median of d based on w
Parameters
----------
d : array
(n, 1), variable for which median will be found
w : array
(n, 1), variable on which d's median will be decided
Notes
-----
d and w are arranged in the same order
Returns
-------
float
median of d
Examples
--------
Creating an array including five integers.
We will get the median of these integers.
>>> d = np.array([5,4,3,1,2])
Creating another array including weight values for the above integers.
The median of d will be decided with a consideration to these weight
values.
>>> w = np.array([10, 22, 9, 2, 5])
Applying weighted_median function
>>> weighted_median(d, w)
4
"""
dtype = [('w', '%s' % w.dtype), ('v', '%s' % d.dtype)]
d_w = np.array(list(zip(w, d)), dtype=dtype)
d_w.sort(order='v')
reordered_w = d_w['w'].cumsum()
cumsum_threshold = reordered_w[-1] * 1.0 / 2
median_inx = (reordered_w >= cumsum_threshold).nonzero()[0][0]
if reordered_w[median_inx] == cumsum_threshold and len(d) - 1 > median_inx:
return np.sort(d)[median_inx:median_inx + 2].mean()
return np.sort(d)[median_inx]
|
https://github.com/pysal/esda/blob/2fafc6ec505e153152a86601d3e0fba080610c20/esda/smoothing.py#L66-L113
|
deducting the median from each column
|
python
|
def get_median(temp_list):
"""Return median
"""
num = len(temp_list)
temp_list.sort()
print(temp_list)
if num % 2 == 0:
median = (temp_list[int(num/2)] + temp_list[int(num/2) - 1]) / 2
else:
median = temp_list[int(num/2)]
return median
|
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/src/sdk/pynni/nni/metis_tuner/metis_tuner.py#L501-L511
|
deducting the median from each column
|
python
|
def median_high(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the high mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.median_high:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=num,
oper='median_high',
minimum=minimum,
maximum=maximum,
ref=ref
)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L226-L246
|
deducting the median from each column
|
python
|
def calculate_median(given_list):
"""
Returns the median of values in the given list.
"""
median = None
if not given_list:
return median
given_list = sorted(given_list)
list_length = len(given_list)
if list_length % 2:
median = given_list[int(list_length / 2)]
else:
median = (given_list[int(list_length / 2)] + given_list[int(list_length / 2) - 1]) / 2.0
return median
|
https://github.com/RIPE-NCC/ripe.atlas.sagan/blob/f0e57221cf0ba3504baddd3ea460fc955bc41cc6/ripe/atlas/sagan/base.py#L264-L281
|
deducting the median from each column
|
python
|
def get_median(values, kdd):
"""
Given an unsorted list of numeric values, return median value (as a float).
Note that in the case of even-length lists of values, we apply the value to
the left of the center to be the median (such that the median can only be
a value from the list of values).
Eg: get_median([1,2,3,4]) == 2, not 2.5.
"""
if not values:
raise Exception("Cannot calculate median of list with no values!")
sorted_values = deepcopy(values)
sorted_values.sort() # Not calling `sorted` b/c `sorted_values` may not be list.
if kdd:
return sorted_values[len(values)//2]
else:
if len(values) % 2 == 0:
return sorted_values[len(values)//2-1]
else:
return sorted_values[len(values)//2]
|
https://github.com/algofairness/BlackBoxAuditing/blob/b06c4faed5591cd7088475b2a203127bc5820483/BlackBoxAuditing/repairers/calculators.py#L3-L24
|
deducting the median from each column
|
python
|
def median1d(self, name, return_errors=False):
""" Return median 1d marginalized parameters
Parameters
----------
name: str
The name of the parameter requested
return_errors: Optional, {bool, False}
If true, return a second and third parameter that represents the
lower and upper 90% error on the parameter.
Returns
-------
param: float or tuple
The requested parameter
"""
if return_errors:
mid = self.data[name]['best']
low, high = self.data[name]['err']
return (mid, low, high)
else:
return self.data[name]['best']
|
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/catalog/__init__.py#L50-L71
|
deducting the median from each column
|
python
|
def subtract_column_median(df, prefix='Intensity '):
"""
Apply column-wise normalisation to expression columns.
Default is median transform to expression columns beginning with Intensity
:param df:
:param prefix: The column prefix for expression columns
:return:
"""
df = df.copy()
df.replace([np.inf, -np.inf], np.nan, inplace=True)
mask = [l.startswith(prefix) for l in df.columns.values]
df.iloc[:, mask] = df.iloc[:, mask] - df.iloc[:, mask].median(axis=0)
return df
|
https://github.com/mfitzp/padua/blob/8b14bf4d2f895da6aea5d7885d409315bd303ec6/padua/normalization.py#L4-L22
|
deducting the median from each column
|
python
|
def median(self, func=lambda x: x):
"""
Return the median value of data elements
:param func: lambda expression to project and sort data
:return: median value
"""
if self.count() == 0:
raise NoElementsError(u"Iterable contains no elements")
result = self.order_by(func).select(func).to_list()
length = len(result)
i = int(length / 2)
return result[i] if length % 2 == 1 else (float(result[i - 1]) + float(result[i])) / float(2)
|
https://github.com/viralogic/py-enumerable/blob/63363649bccef223379e1e87056747240c83aa9d/py_linq/py_linq.py#L104-L115
|
deducting the median from each column
|
python
|
def median_low(name, num, minimum=0, maximum=0, ref=None):
'''
Calculates the low mean of the ``num`` most recent values. Requires a list.
USAGE:
.. code-block:: yaml
foo:
calc.median_low:
- name: myregentry
- num: 5
'''
return calc(
name=name,
num=num,
oper='median_low',
minimum=minimum,
maximum=maximum,
ref=ref
)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/thorium/calc.py#L203-L223
|
deducting the median from each column
|
python
|
def median_filter(X, M=8):
"""Median filter along the first axis of the feature matrix X."""
for i in range(X.shape[1]):
X[:, i] = filters.median_filter(X[:, i], size=M)
return X
|
https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/algorithms/foote/segmenter.py#L15-L19
|
deducting the median from each column
|
python
|
def median_scaler(s):
"""
Remove median, divide by IQR.
"""
if sum(~np.isnan(s)) > 2:
ss = s[~np.isnan(s)]
median = np.median(ss)
IQR = np.diff(np.percentile(ss, [25, 75]))
return (s - median) / IQR
else:
return np.full(s.shape, np.nan)
|
https://github.com/oscarbranson/latools/blob/cd25a650cfee318152f234d992708511f7047fbe/latools/filtering/signal_optimiser.py#L75-L85
|
deducting the median from each column
|
python
|
def median_frequency(sig,FS):
"""Compute median frequency along the specified axes.
Parameters
----------
sig: ndarray
input from which median frequency is computed.
FS: int
sampling frequency
Returns
-------
f_max: int
0.50 of max_frequency using cumsum.
"""
f, fs = plotfft(sig, FS, doplot=False)
t = cumsum(fs)
ind_mag = find (t>t[-1]*0.50)[0]
f_median=f[ind_mag]
return f_median
|
https://github.com/biosignalsnotebooks/biosignalsnotebooks/blob/aaa01d4125180b3a34f1e26e0d3ff08c23f666d3/biosignalsnotebooks/build/lib/biosignalsnotebooks/external_packages/novainstrumentation/freq_analysis.py#L75-L95
|
deducting the median from each column
|
python
|
def getMedian(numericValues):
"""
Gets the median of a list of values
Returns a float/int
"""
theValues = sorted(numericValues)
if len(theValues) % 2 == 1:
return theValues[(len(theValues) + 1) / 2 - 1]
else:
lower = theValues[len(theValues) / 2 - 1]
upper = theValues[len(theValues) / 2]
return (float(lower + upper)) / 2
|
https://github.com/edx/ease/blob/a7890ed403da94d03726b0639cd8ebda45af6bbb/ease/util_functions.py#L485-L498
|
deducting the median from each column
|
python
|
def median2D(const, bin1, label1, bin2, label2, data_label,
returnData=False):
"""Return a 2D average of data_label over a season and label1, label2.
Parameters
----------
const: Constellation or Instrument
bin#: [min, max, number of bins]
label#: string
identifies data product for bin#
data_label: list-like
contains strings identifying data product(s) to be averaged
Returns
-------
median : dictionary
2D median accessed by data_label as a function of label1 and label2
over the season delineated by bounds of passed instrument objects.
Also includes 'count' and 'avg_abs_dev' as well as the values of
the bin edges in 'bin_x' and 'bin_y'.
"""
# const is either an Instrument or a Constellation, and we want to
# iterate over it.
# If it's a Constellation, then we can do that as is, but if it's
# an Instrument, we just have to put that Instrument into something
# that will yeild that Instrument, like a list.
if isinstance(const, pysat.Instrument):
const = [const]
elif not isinstance(const, pysat.Constellation):
raise ValueError("Parameter must be an Instrument or a Constellation.")
# create bins
#// seems to create the boundaries used for sorting into bins
binx = np.linspace(bin1[0], bin1[1], bin1[2]+1)
biny = np.linspace(bin2[0], bin2[1], bin2[2]+1)
#// how many bins are used
numx = len(binx)-1
numy = len(biny)-1
#// how many different data products
numz = len(data_label)
# create array to store all values before taking median
#// the indices of the bins/data products? used for looping.
yarr = np.arange(numy)
xarr = np.arange(numx)
zarr = np.arange(numz)
#// 3d array: stores the data that is sorted into each bin? - in a deque
ans = [ [ [collections.deque() for i in xarr] for j in yarr] for k in zarr]
for inst in const:
# do loop to iterate over instrument season
#// probably iterates by date but that all depends on the
#// configuration of that particular instrument.
#// either way, it iterates over the instrument, loading successive
#// data between start and end bounds
for inst in inst:
# collect data in bins for averaging
if len(inst.data) != 0:
#// sort the data into bins (x) based on label 1
#// (stores bin indexes in xind)
xind = np.digitize(inst.data[label1], binx)-1
#// for each possible x index
for xi in xarr:
#// get the indicies of those pieces of data in that bin
xindex, = np.where(xind==xi)
if len(xindex) > 0:
#// look up the data along y (label2) at that set of indicies (a given x)
yData = inst.data.iloc[xindex]
#// digitize that, to sort data into bins along y (label2) (get bin indexes)
yind = np.digitize(yData[label2], biny)-1
#// for each possible y index
for yj in yarr:
#// select data with this y index (and we already filtered for this x index)
yindex, = np.where(yind==yj)
if len(yindex) > 0:
#// for each data product label zk
for zk in zarr:
#// take the data (already filtered by x); filter it by y and
#// select the data product, put it in a list, and extend the deque
ans[zk][yj][xi].extend( yData.ix[yindex,data_label[zk]].tolist() )
return _calc_2d_median(ans, data_label, binx, biny, xarr, yarr, zarr, numx, numy, numz, returnData)
|
https://github.com/rstoneback/pysat/blob/4ae1afd80e15e4449397d39dce8c3e969c32c422/pysat/ssnl/avg.py#L14-L98
|
deducting the median from each column
|
python
|
def median_date(dt_list):
"""Calcuate median datetime from datetime list
"""
#dt_list_sort = sorted(dt_list)
idx = len(dt_list)/2
if len(dt_list) % 2 == 0:
md = mean_date([dt_list[idx-1], dt_list[idx]])
else:
md = dt_list[idx]
return md
|
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/timelib.py#L373-L382
|
deducting the median from each column
|
python
|
def _weighted_median(values, weights, quantile):
""" Calculate a weighted median for values above a particular quantile cut
Used in pseudo continuum normalization
Parameters
----------
values: np ndarray of floats
the values to take the median of
weights: np ndarray of floats
the weights associated with the values
quantile: float
the cut applied to the input data
Returns
------
the weighted median
"""
sindx = np.argsort(values)
cvalues = 1. * np.cumsum(weights[sindx])
if cvalues[-1] == 0: # means all the values are 0
return values[0]
cvalues = cvalues / cvalues[-1] # div by largest value
foo = sindx[cvalues > quantile]
if len(foo) == 0:
return values[0]
indx = foo[0]
return values[indx]
|
https://github.com/annayqho/TheCannon/blob/8010a0a5dc9a3f9bb91efa79d7756f79b3c7ba9a/TheCannon/normalization.py#L61-L88
|
deducting the median from each column
|
python
|
def median(arrays, masks=None, dtype=None, out=None,
zeros=None, scales=None,
weights=None):
"""Combine arrays using the median, with masks.
Arrays and masks are a list of array objects. All input arrays
have the same shape. If present, the masks have the same shape
also.
The function returns an array with one more dimension than the
inputs and with size (3, shape). out[0] contains the mean,
out[1] the variance and out[2] the number of points used.
:param arrays: a list of arrays
:param masks: a list of mask arrays, True values are masked
:param dtype: data type of the output
:param out: optional output, with one more axis than the input arrays
:return: median, variance of the median and number of points stored
"""
return generic_combine(intl_combine.median_method(), arrays, masks=masks,
dtype=dtype, out=out,
zeros=zeros, scales=scales, weights=weights)
|
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/combine.py#L62-L85
|
deducting the median from each column
|
python
|
def min(self):
"""
:returns the minimum of the column
"""
res = self._qexec("min(%s)" % self._name)
if len(res) > 0:
self._min = res[0][0]
return self._min
|
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/types.py#L64-L71
|
deducting the median from each column
|
python
|
def median_grouped(data, interval=1):
""""Return the 50th percentile (median) of grouped continuous data.
>>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
3.7
>>> median_grouped([52, 52, 53, 54])
52.5
This calculates the median as the 50th percentile, and should be
used when your data is continuous and grouped. In the above example,
the values 1, 2, 3, etc. actually represent the midpoint of classes
0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
class 3.5-4.5, and interpolation is used to estimate it.
Optional argument ``interval`` represents the class interval, and
defaults to 1. Changing the class interval naturally will change the
interpolated 50th percentile value:
>>> median_grouped([1, 3, 3, 5, 7], interval=1)
3.25
>>> median_grouped([1, 3, 3, 5, 7], interval=2)
3.5
This function does not check whether the data points are at least
``interval`` apart.
"""
data = sorted(data)
n = len(data)
if n == 0:
raise StatisticsError("no median for empty data")
elif n == 1:
return data[0]
# Find the value at the midpoint. Remember this corresponds to the
# centre of the class interval.
x = data[n//2]
for obj in (x, interval):
if isinstance(obj, (str, bytes)):
raise TypeError('expected number but got %r' % obj)
try:
L = x - interval/2 # The lower limit of the median interval.
except TypeError:
# Mixed type. For now we just coerce to float.
L = float(x) - float(interval)/2
cf = data.index(x) # Number of values below the median interval.
# FIXME The following line could be more efficient for big lists.
f = data.count(x) # Number of data points in the median interval.
return L + interval*(n/2 - cf)/f
|
https://github.com/datalib/StatsCounter/blob/5386c967808bbe451025af1d550f060cd7f86669/statscounter/_stats.py#L154-L200
|
deducting the median from each column
|
python
|
def fn_median(self, a, axis=None):
"""
Compute the median of an array, ignoring NaNs.
:param a: The array.
:return: The median value of the array.
"""
return numpy.nanmedian(self._to_ndarray(a), axis=axis)
|
https://github.com/consbio/ncdjango/blob/f807bfd1e4083ab29fbc3c4d4418be108383a710/ncdjango/geoprocessing/evaluation.py#L380-L388
|
deducting the median from each column
|
python
|
def median_mean(timeseries, segmentlength, noverlap=None,
window=None, plan=None):
"""Calculate a PSD of this `TimeSeries` using a median-mean average method
The median-mean average method divides overlapping segments into "even"
and "odd" segments, and computes the bin-by-bin median of the "even"
segments and the "odd" segments, and then takes the bin-by-bin average
of these two median averages.
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single average.
noverlap : `int`
number of samples to overlap between segments, defaults to 50%.
window : `tuple`, `str`, optional
window parameters to apply to timeseries prior to FFT
plan : `REAL8FFTPlan`, optional
LAL FFT plan to use when generating average spectrum
Returns
-------
spectrum : `~gwpy.frequencyseries.FrequencySeries`
average power `FrequencySeries`
See also
--------
lal.REAL8AverageSpectrumMedianMean
"""
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap,
method='median-mean', window=window, plan=plan)
|
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/spectral/_lal.py#L343-L379
|
deducting the median from each column
|
python
|
def median(values, simple=True, mean_weight=0.0):
"""
RETURN MEDIAN VALUE
IF simple=False THEN IN THE EVENT MULTIPLE INSTANCES OF THE
MEDIAN VALUE, THE MEDIAN IS INTERPOLATED BASED ON ITS POSITION
IN THE MEDIAN RANGE
mean_weight IS TO PICK A MEDIAN VALUE IN THE ODD CASE THAT IS
CLOSER TO THE MEAN (PICK A MEDIAN BETWEEN TWO MODES IN BIMODAL CASE)
"""
if OR(v == None for v in values):
Log.error("median is not ready to handle None")
try:
if not values:
return Null
l = len(values)
_sorted = sorted(values)
middle = int(l / 2)
_median = float(_sorted[middle])
if len(_sorted) == 1:
return _median
if simple:
if l % 2 == 0:
return (_sorted[middle - 1] + _median) / 2
return _median
# FIND RANGE OF THE median
start_index = middle - 1
while start_index > 0 and _sorted[start_index] == _median:
start_index -= 1
start_index += 1
stop_index = middle + 1
while stop_index < l and _sorted[stop_index] == _median:
stop_index += 1
num_middle = stop_index - start_index
if l % 2 == 0:
if num_middle == 1:
return (_sorted[middle - 1] + _median) / 2
else:
return (_median - 0.5) + (middle - start_index) / num_middle
else:
if num_middle == 1:
return (1 - mean_weight) * _median + mean_weight * (_sorted[middle - 1] + _sorted[middle + 1]) / 2
else:
return (_median - 0.5) + (middle + 0.5 - start_index) / num_middle
except Exception as e:
Log.error("problem with median of {{values}}", values= values, cause=e)
|
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/stats.py#L295-L350
|
deducting the median from each column
|
python
|
def runningMedian(seq, M):
"""
Purpose: Find the median for the points in a sliding window (odd number in size)
as it is moved from left to right by one point at a time.
Inputs:
seq -- list containing items for which a running median (in a sliding window)
is to be calculated
M -- number of items in window (window size) -- must be an integer > 1
Otputs:
medians -- list of medians with size N - M + 1
Note:
1. The median of a finite list of numbers is the "center" value when this list
is sorted in ascending order.
2. If M is an even number the two elements in the window that
are close to the center are averaged to give the median (this
is not by definition)
"""
seq = iter(seq)
s = []
m = M // 2 #// does a truncated division like integer division in Python 2
# Set up list s (to be sorted) and load deque with first window of seq
s = [item for item in islice(seq,M)]
d = deque(s)
# Simple lambda function to handle even/odd window sizes
median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5
# Sort it in increasing order and extract the median ("center" of the sorted window)
s.sort()
medians = [median()]
# Now slide the window by one point to the right for each new position (each pass through
# the loop). Stop when the item in the right end of the deque contains the last item in seq
for item in seq:
old = d.popleft() # pop oldest from left
d.append(item) # push newest in from right
del s[bisect_left(s, old)] # locate insertion point and then remove old
insort(s, item) # insert newest such that new sort is not required
medians.append(median())
return medians
|
https://github.com/hollenstein/maspy/blob/f15fcfd24df306d8420540460d902aa3073ec133/maspy/mit_stats.py#L48-L88
|
deducting the median from each column
|
python
|
def median(self, default=None):
"""
Calculate the median value over the time series.
:param default: Value to return as a default should the calculation not be possible.
:return: Float representing the median value or `None`.
"""
return numpy.asscalar(numpy.median(self.values)) if self.values else default
|
https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/modules/time_series.py#L321-L328
|
deducting the median from each column
|
python
|
def median(timeseries, segmentlength, **kwargs):
"""Calculate a PSD using Welch's method with a median average
"""
if scipy_version <= '1.1.9999':
raise ValueError(
"median average PSD estimation requires scipy >= 1.2.0",
)
kwargs.setdefault('average', 'median')
return welch(timeseries, segmentlength, **kwargs)
|
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/spectral/_scipy.py#L74-L82
|
deducting the median from each column
|
python
|
def get_median(data_np):
"""Like :func:`get_mean` but for median."""
i = np.isfinite(data_np)
if not np.any(i):
return np.nan
return np.median(data_np[i])
|
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/util/iqcalc.py#L46-L51
|
deducting the median from each column
|
python
|
def median_fltr(dem, fsize=7, origmask=False):
"""Scipy.ndimage median filter
Does not properly handle NaN
"""
print("Applying median filter with size %s" % fsize)
from scipy.ndimage.filters import median_filter
dem_filt_med = median_filter(dem.filled(np.nan), fsize)
#Now mask all nans
out = np.ma.fix_invalid(dem_filt_med, copy=False, fill_value=dem.fill_value)
if origmask:
out = np.ma.array(out, mask=dem.mask, fill_value=dem.fill_value)
out.set_fill_value(dem.fill_value)
return out
|
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/filtlib.py#L271-L284
|
deducting the median from each column
|
python
|
def median_hilow(series, confidence_interval=0.95):
"""
Median and a selected pair of outer quantiles having equal tail areas
"""
tail = (1 - confidence_interval) / 2
return pd.DataFrame({'y': [np.median(series)],
'ymin': np.percentile(series, 100 * tail),
'ymax': np.percentile(series, 100 * (1 - tail))})
|
https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat_summary.py#L65-L72
|
deducting the median from each column
|
python
|
def weighted_median(y, w):
"""
Compute weighted median of `y` with weights `w`.
"""
items = sorted(zip(y, w))
midpoint = sum(w) / 2
yvals = []
wsum = 0
for yy, ww in items:
wsum += ww
if wsum > midpoint:
yvals.append(yy)
break
elif wsum == midpoint:
yvals.append(yy)
else:
yvals = y
return sum(yvals) / len(yvals)
|
https://github.com/airspeed-velocity/asv/blob/d23bb8b74e8adacbfa3cf5724bda55fb39d56ba6/asv/step_detect.py#L933-L953
|
deducting the median from each column
|
python
|
def mad(a):
'''Calculate the median absolute deviation of a sample
a - a numpy array-like collection of values
returns the median of the deviation of a from its median.
'''
a = np.asfarray(a).flatten()
return np.median(np.abs(a - np.median(a)))
|
https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/threshold.py#L520-L528
|
deducting the median from each column
|
python
|
def median(self):
""" -> #float :func:numpy.median of the timing intervals """
return round(float(np.median(self.array)), self.precision)\
if len(self.array) else None
|
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/debug/__init__.py#L2174-L2177
|
deducting the median from each column
|
python
|
def median_interval(self, name, alpha=_alpha, **kwargs):
"""
Median including bayesian credible interval.
"""
data = self.get(name,**kwargs)
return median_interval(data,alpha)
|
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L301-L306
|
deducting the median from each column
|
python
|
def median(timeseries, segmentlength, noverlap=None, window=None, plan=None):
"""Calculate a PSD of this `TimeSeries` using a median average method
The median average is similar to Welch's method, using a median average
rather than mean.
Parameters
----------
timeseries : `~gwpy.timeseries.TimeSeries`
input `TimeSeries` data.
segmentlength : `int`
number of samples in single average.
noverlap : `int`
number of samples to overlap between segments, defaults to 50%.
window : `tuple`, `str`, optional
window parameters to apply to timeseries prior to FFT
plan : `REAL8FFTPlan`, optional
LAL FFT plan to use when generating average spectrum
Returns
-------
spectrum : `~gwpy.frequencyseries.FrequencySeries`
average power `FrequencySeries`
See also
--------
lal.REAL8AverageSpectrumMedian
"""
return _lal_spectrum(timeseries, segmentlength, noverlap=noverlap,
method='median', window=window, plan=plan)
|
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/signal/spectral/_lal.py#L307-L340
|
deducting the median from each column
|
python
|
def med_cost_fn_val(self):
'''Returns median cost function return value for all members'''
if len(self.__members) != 0:
if self.__num_processes > 1:
members = [m.get() for m in self.__members]
else:
members = self.__members
return median([m.cost_fn_val for m in members])
else:
return None
|
https://github.com/tjkessler/PyGenetics/blob/b78ee6393605d6e85d2279fb05f3983f5833df40/pygenetics/ga_core.py#L158-L168
|
deducting the median from each column
|
python
|
def mad(data, axis=None):
"""
Computes the median absolute deviation of *data* along a given *axis*.
See `link <https://en.wikipedia.org/wiki/Median_absolute_deviation>`_ for
details.
**Parameters**
data : array-like
**Returns**
mad : number or array-like
"""
return median(absolute(data - median(data, axis)), axis)
|
https://github.com/astroswego/plotypus/blob/b1162194ca1d4f6c00e79afe3e6fb40f0eaffcb9/src/plotypus/utils.py#L172-L186
|
deducting the median from each column
|
python
|
def cummedian(expr, sort=None, ascending=True, unique=False,
preceding=None, following=None):
"""
Calculate cumulative median of a sequence expression.
:param expr: expression for calculation
:param sort: name of the sort column
:param ascending: whether to sort in ascending order
:param unique: whether to eliminate duplicate entries
:param preceding: the start point of a window
:param following: the end point of a window
:return: calculated column
"""
data_type = _stats_type(expr)
return _cumulative_op(expr, CumMedian, sort=sort, ascending=ascending,
unique=unique, preceding=preceding,
following=following, data_type=data_type)
|
https://github.com/aliyun/aliyun-odps-python-sdk/blob/4b0de18f5864386df6068f26f026e62f932c41e4/odps/df/expr/window.py#L356-L372
|
deducting the median from each column
|
python
|
def mean_abs(self):
"""return the median of absolute values"""
# XXX rename this method
if len(self.values) > 0:
return sorted(map(abs, self.values))[len(self.values) / 2]
else:
return None
|
https://github.com/TrafficSenseMSD/SumoTools/blob/8607b4f885f1d1798e43240be643efe6dccccdaa/sumolib/miscutils.py#L168-L174
|
deducting the median from each column
|
python
|
def weighted_median(values, weights):
'''
Returns element such that sum of weights below and above are (roughly) equal
:param values: Values whose median is sought
:type values: List of reals
:param weights: Weights of each value
:type weights: List of positive reals
:return: value of weighted median
:rtype: Real
'''
if len(values) == 1:
return values[0]
if len(values) == 0:
raise ValueError('Cannot take median of empty list')
values = [float(value) for value in values]
indices_sorted = np.argsort(values)
values = [values[ind] for ind in indices_sorted]
weights = [weights[ind] for ind in indices_sorted]
total_weight = sum(weights)
below_weight = 0
i = -1
while below_weight < total_weight / 2:
i += 1
below_weight += weights[i]
return values[i]
|
https://github.com/soerenwolfers/swutil/blob/2d598f2deac8b7e20df95dbc68017e5ab5d6180c/swutil/np_tools.py#L212-L237
|
deducting the median from each column
|
python
|
def median_filter(tr, multiplier=10, windowlength=0.5,
interp_len=0.05, debug=0):
"""
Filter out spikes in data above a multiple of MAD of the data.
Currently only has the ability to replaces spikes with linear
interpolation. In the future we would aim to fill the gap with something
more appropriate. Works in-place on data.
:type tr: obspy.core.trace.Trace
:param tr: trace to despike
:type multiplier: float
:param multiplier:
median absolute deviation multiplier to find spikes above.
:type windowlength: float
:param windowlength: Length of window to look for spikes in in seconds.
:type interp_len: float
:param interp_len: Length in seconds to interpolate around spikes.
:type debug: int
:param debug: Debug output level between 0 and 5, higher is more output.
:returns: :class:`obspy.core.trace.Trace`
.. warning::
Not particularly effective, and may remove earthquake signals, use with
caution.
"""
num_cores = cpu_count()
if debug >= 1:
data_in = tr.copy()
# Note - might be worth finding spikes in filtered data
filt = tr.copy()
filt.detrend('linear')
try:
filt.filter('bandpass', freqmin=10.0,
freqmax=(tr.stats.sampling_rate / 2) - 1)
except Exception as e:
print("Could not filter due to error: {0}".format(e))
data = filt.data
del filt
# Loop through windows
_windowlength = int(windowlength * tr.stats.sampling_rate)
_interp_len = int(interp_len * tr.stats.sampling_rate)
peaks = []
with Timer() as t:
pool = Pool(processes=num_cores)
results = [pool.apply_async(_median_window,
args=(data[chunk * _windowlength:
(chunk + 1) * _windowlength],
chunk * _windowlength, multiplier,
tr.stats.starttime + windowlength,
tr.stats.sampling_rate,
debug))
for chunk in range(int(len(data) / _windowlength))]
pool.close()
for p in results:
peaks += p.get()
pool.join()
for peak in peaks:
tr.data = _interp_gap(tr.data, peak[1], _interp_len)
print("Despiking took: %s s" % t.secs)
if debug >= 1:
plt.plot(data_in.data, 'r', label='raw')
plt.plot(tr.data, 'k', label='despiked')
plt.legend()
plt.show()
return tr
|
https://github.com/eqcorrscan/EQcorrscan/blob/3121b4aca801ee5d38f56ca297ce1c0f9515d9ff/eqcorrscan/utils/despike.py#L33-L99
|
deducting the median from each column
|
python
|
def weighted_median(data, weights=None):
"""Calculate the weighted median of a list."""
if weights is None:
return median(data)
midpoint = 0.5 * sum(weights)
if any([j > midpoint for j in weights]):
return data[weights.index(max(weights))]
if any([j > 0 for j in weights]):
sorted_data, sorted_weights = zip(*sorted(zip(data, weights)))
cumulative_weight = 0
below_midpoint_index = 0
while cumulative_weight <= midpoint:
below_midpoint_index += 1
cumulative_weight += sorted_weights[below_midpoint_index-1]
cumulative_weight -= sorted_weights[below_midpoint_index-1]
if cumulative_weight - midpoint < sys.float_info.epsilon:
bounds = sorted_data[below_midpoint_index-2:below_midpoint_index]
return sum(bounds) / float(len(bounds))
return sorted_data[below_midpoint_index-1]
|
https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L69-L87
|
deducting the median from each column
|
python
|
def fast_median(a):
"""Fast median operation for masked array using 50th-percentile
"""
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
|
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/malib.py#L1494-L1503
|
deducting the median from each column
|
python
|
def compute_geometric_median(X, eps=1e-5):
"""
Estimate the geometric median of points in 2D.
Code from https://stackoverflow.com/a/30305181
Parameters
----------
X : (N,2) ndarray
Points in 2D. Second axis must be given in xy-form.
eps : float, optional
Distance threshold when to return the median.
Returns
-------
(2,) ndarray
Geometric median as xy-coordinate.
"""
y = np.mean(X, 0)
while True:
D = scipy.spatial.distance.cdist(X, [y])
nonzeros = (D != 0)[:, 0]
Dinv = 1 / D[nonzeros]
Dinvs = np.sum(Dinv)
W = Dinv / Dinvs
T = np.sum(W * X[nonzeros], 0)
num_zeros = len(X) - np.sum(nonzeros)
if num_zeros == 0:
y1 = T
elif num_zeros == len(X):
return y
else:
R = (T - y) * Dinvs
r = np.linalg.norm(R)
rinv = 0 if r == 0 else num_zeros/r
y1 = max(0, 1-rinv)*T + min(1, rinv)*y
if scipy.spatial.distance.euclidean(y, y1) < eps:
return y1
y = y1
|
https://github.com/aleju/imgaug/blob/786be74aa855513840113ea523c5df495dc6a8af/imgaug/augmentables/kps.py#L13-L58
|
deducting the median from each column
|
python
|
def column(self, i):
"""from right"""
return ''.join([str(digitat2(r,i)) for r in self])
|
https://github.com/pyfca/pyfca/blob/cf8cea9e76076dbf4bb3f38996dcb5491b0eb0b0/pyfca/implications.py#L432-L434
|
deducting the median from each column
|
python
|
def _column_width(self, index=None, name=None, max_width=300, **kwargs):
"""
:param index: int of the column index
:param name: str of the name of the column
:param max_width: int of the max size of characters in the width
:return: int of the width of this column
"""
assert name is not None or index is not None
if name and name not in self._column_index:
return min(max_width, name)
if index is not None:
name = self.columns[index]
else:
index = self._column_index[name]
values_width = [len(name)]
if isinstance(self._parameters.get(name, None), list):
values_width += [len(self._safe_str(p, **kwargs))
for p in self._parameters[name]]
values_width += [len(self._safe_str(row[index], **kwargs))
for row in self.table]
ret = max(values_width)
return min(max_width, ret) if max_width else ret
|
https://github.com/SeabornGames/Table/blob/0c474ef2fb00db0e7cf47e8af91e3556c2e7485a/seaborn_table/table.py#L1709-L1734
|
deducting the median from each column
|
python
|
def mad(data):
r"""Median absolute deviation
This method calculates the median absolute deviation of the input data.
Parameters
----------
data : np.ndarray
Input data array
Returns
-------
float MAD value
Examples
--------
>>> from modopt.math.stats import mad
>>> a = np.arange(9).reshape(3, 3)
>>> mad(a)
2.0
Notes
-----
The MAD is calculated as follows:
.. math::
\mathrm{MAD} = \mathrm{median}\left(|X_i - \mathrm{median}(X)|\right)
"""
return np.median(np.abs(data - np.median(data)))
|
https://github.com/CEA-COSMIC/ModOpt/blob/019b189cb897cbb4d210c44a100daaa08468830c/modopt/math/stats.py#L75-L106
|
deducting the median from each column
|
python
|
def median_filter(data, mask, radius, percent=50):
'''Masked median filter with octagonal shape
data - array of data to be median filtered.
mask - mask of significant pixels in data
radius - the radius of a circle inscribed into the filtering octagon
percent - conceptually, order the significant pixels in the octagon,
count them and choose the pixel indexed by the percent
times the count divided by 100. More simply, 50 = median
returns a filtered array. In areas where the median filter does
not overlap the mask, the filtered result is undefined, but in
practice, it will be the lowest value in the valid area.
'''
if mask is None:
mask = np.ones(data.shape, dtype=bool)
if np.all(~ mask):
return data.copy()
#
# Normalize the ranked data to 0-255
#
if (not np.issubdtype(data.dtype, np.int) or
np.min(data) < 0 or np.max(data) > 255):
ranked_data, translation = rank_order(data[mask], nbins=255)
was_ranked = True
else:
ranked_data = data[mask]
was_ranked = False
input = np.zeros(data.shape, np.uint8 )
input[mask] = ranked_data
mmask = np.ascontiguousarray(mask, np.uint8)
output = np.zeros(data.shape, np.uint8)
_filter.median_filter(input, mmask, output, radius, percent)
if was_ranked:
result = translation[output]
else:
result = output
return result
|
https://github.com/CellProfiler/centrosome/blob/7bd9350a2d4ae1b215b81eabcecfe560bbb1f32a/centrosome/filter.py#L68-L107
|
deducting the median from each column
|
python
|
def median_interval(data, alpha=_alpha):
"""
Median including bayesian credible interval.
"""
q = [100*alpha/2., 50, 100*(1-alpha/2.)]
lo,med,hi = np.percentile(data,q)
return interval(med,lo,hi)
|
https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/stats.py#L43-L49
|
deducting the median from each column
|
python
|
def flag_calcmad(data):
""" Calculate median absolute deviation of data array """
absdev = np.abs(data - np.median(data))
return np.median(absdev)
|
https://github.com/caseyjlaw/rtpipe/blob/ac33e4332cf215091a63afbb3137850876d73ec0/rtpipe/rtlib_numba.py#L17-L21
|
deducting the median from each column
|
python
|
def get_range_values_per_column(df):
"""
Retrieves the finite max, min and mean values per column in the DataFrame `df` and stores them in three
dictionaries. Those dictionaries `col_to_max`, `col_to_min`, `col_to_median` map the columnname to the maximal,
minimal or median value of that column.
If a column does not contain any finite values at all, a 0 is stored instead.
:param df: the Dataframe to get columnswise max, min and median from
:type df: pandas.DataFrame
:return: Dictionaries mapping column names to max, min, mean values
:rtype: (dict, dict, dict)
"""
data = df.get_values()
masked = np.ma.masked_invalid(data)
columns = df.columns
is_col_non_finite = masked.mask.sum(axis=0) == masked.data.shape[0]
if np.any(is_col_non_finite):
# We have columns that does not contain any finite value at all, so we will store 0 instead.
_logger.warning("The columns {} did not have any finite values. Filling with zeros.".format(
df.iloc[:, np.where(is_col_non_finite)[0]].columns.values))
masked.data[:, is_col_non_finite] = 0 # Set the values of the columns to 0
masked.mask[:, is_col_non_finite] = False # Remove the mask for this column
# fetch max, min and median for all columns
col_to_max = dict(zip(columns, np.max(masked, axis=0)))
col_to_min = dict(zip(columns, np.min(masked, axis=0)))
col_to_median = dict(zip(columns, np.ma.median(masked, axis=0)))
return col_to_max, col_to_min, col_to_median
|
https://github.com/blue-yonder/tsfresh/blob/c72c9c574371cf7dd7d54e00a466792792e5d202/tsfresh/utilities/dataframe_functions.py#L150-L183
|
deducting the median from each column
|
python
|
def medianscore(inlist):
"""
Returns the 'middle' score of the passed list. If there is an even
number of scores, the mean of the 2 middle scores is returned.
Usage: lmedianscore(inlist)
"""
newlist = copy.deepcopy(inlist)
newlist.sort()
if len(newlist) % 2 == 0: # if even number of scores, average middle 2
index = len(newlist) / 2 # integer division correct
median = float(newlist[index] + newlist[index - 1]) / 2
else:
index = len(newlist) / 2 # int divsion gives mid value when count from 0
median = newlist[index]
return median
|
https://github.com/klahnakoski/pyLibrary/blob/fa2dcbc48fda8d26999baef400e9a98149e0b982/mo_math/vendor/strangman/stats.py#L306-L322
|
deducting the median from each column
|
python
|
def complex_median(complex_list):
""" Get the median value of a list of complex numbers.
Parameters
----------
complex_list: list
List of complex numbers to calculate the median.
Returns
-------
a + 1.j*b: complex number
The median of the real and imaginary parts.
"""
median_real = numpy.median([complex_number.real
for complex_number in complex_list])
median_imag = numpy.median([complex_number.imag
for complex_number in complex_list])
return median_real + 1.j*median_imag
|
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/strain/lines.py#L22-L39
|
deducting the median from each column
|
python
|
def _masked_median(data, axis=None):
"""
Calculate the median of a (masked) array.
This function is necessary for a consistent interface across all
numpy versions. A bug was introduced in numpy v1.10 where
`numpy.ma.median` (with ``axis=None``) returns a single-valued
`~numpy.ma.MaskedArray` if the input data is a `~numpy.ndarray` or
if the data is a `~numpy.ma.MaskedArray`, but the mask is `False`
everywhere.
Parameters
----------
data : array-like
The input data.
axis : int or `None`, optional
The array axis along which the median is calculated. If
`None`, then the entire array is used.
Returns
-------
result : float or `~numpy.ma.MaskedArray`
The resulting median. If ``axis`` is `None`, then a float is
returned, otherwise a `~numpy.ma.MaskedArray` is returned.
"""
_median = np.ma.median(data, axis=axis)
if axis is None and np.ma.isMaskedArray(_median):
_median = _median.item()
return _median
|
https://github.com/astropy/photutils/blob/cc9bb4534ab76bac98cb5f374a348a2573d10401/photutils/background/core.py#L32-L62
|
deducting the median from each column
|
python
|
def median_min_distance(data, metric):
"""This function computes a graph of nearest-neighbors for each sample point in
'data' and returns the median of the distribution of distances between those
nearest-neighbors, the distance metric being specified by 'metric'.
Parameters
----------
data : array of shape (n_samples, n_features)
The data-set, a fraction of whose sample points will be extracted
by density sampling.
metric : string
The distance metric used to determine the nearest-neighbor to each data-point.
The DistanceMetric class defined in scikit-learn's library lists all available
metrics.
Returns
-------
median_min_dist : float
The median of the distribution of distances between nearest-neighbors.
"""
data = np.atleast_2d(data)
nearest_distances = kneighbors_graph(data, 1, mode = 'distance', metric = metric, include_self = False).data
median_min_dist = np.median(nearest_distances, overwrite_input = True)
return round(median_min_dist, 4)
|
https://github.com/GGiecold/Density_Sampling/blob/8c8e6c63a97fecf958238e12947e5e6542b64102/Density_Sampling.py#L116-L144
|
deducting the median from each column
|
python
|
def expect_column_mean_to_be_between(self,
column,
min_value=None,
max_value=None,
result_format=None, include_config=False, catch_exceptions=None, meta=None
):
"""Expect the column mean to be between a minimum value and a maximum value (inclusive).
expect_column_mean_to_be_between is a :func:`column_aggregate_expectation <great_expectations.data_asset.dataset.Dataset.column_aggregate_expectation>`.
Args:
column (str): \
The column name.
min_value (float or None): \
The minimum value for the column mean.
max_value (float or None): \
The maximum value for the column mean.
Other Parameters:
result_format (str or None): \
Which output mode to use: `BOOLEAN_ONLY`, `BASIC`, `COMPLETE`, or `SUMMARY`.
For more detail, see :ref:`result_format <result_format>`.
include_config (boolean): \
If True, then include the expectation config as part of the result object. \
For more detail, see :ref:`include_config`.
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see :ref:`catch_exceptions`.
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without modification. \
For more detail, see :ref:`meta`.
Returns:
A JSON-serializable expectation result object.
Exact fields vary depending on the values passed to :ref:`result_format <result_format>` and
:ref:`include_config`, :ref:`catch_exceptions`, and :ref:`meta`.
Notes:
These fields in the result object are customized for this expectation:
::
{
"observed_value": (float) The true mean for the column
}
* min_value and max_value are both inclusive.
* If min_value is None, then max_value is treated as an upper bound.
* If max_value is None, then min_value is treated as a lower bound.
See Also:
expect_column_median_to_be_between
expect_column_stdev_to_be_between
"""
raise NotImplementedError
|
https://github.com/great-expectations/great_expectations/blob/08385c40529d4f14a1c46916788aecc47f33ee9d/great_expectations/dataset/dataset.py#L1384-L1438
|
deducting the median from each column
|
python
|
def medfilt(vector, window):
"""
Apply a window-length median filter to a 1D array vector.
Should get rid of 'spike' value 15.
>>> print(medfilt(np.array([1., 15., 1., 1., 1.]), 3))
[1. 1. 1. 1. 1.]
The 'edge' case is a bit tricky...
>>> print(medfilt(np.array([15., 1., 1., 1., 1.]), 3))
[15. 1. 1. 1. 1.]
Inspired by: https://gist.github.com/bhawkins/3535131
"""
if not window % 2 == 1:
raise ValueError("Median filter length must be odd.")
if not vector.ndim == 1:
raise ValueError("Input must be one-dimensional.")
k = (window - 1) // 2 # window movement
result = np.zeros((len(vector), window), dtype=vector.dtype)
result[:, k] = vector
for i in range(k):
j = k - i
result[j:, i] = vector[:-j]
result[:j, i] = vector[0]
result[:-j, -(i + 1)] = vector[j:]
result[-j:, -(i + 1)] = vector[-1]
return np.median(result, axis=1)
|
https://github.com/DataMedSci/beprof/blob/f94c10929ea357bd0e5ead8f7a2d3061acfd6494/beprof/functions.py#L27-L56
|
deducting the median from each column
|
python
|
def argmin(df, column: str, groups: Union[str, List[str]] = None):
"""
Keep the row of the data corresponding to the minimal value in a column
---
### Parameters
*mandatory :*
- `column` (str): name of the column containing the value you want to keep the minimum
*optional :*
- `groups` (*str or list(str)*): name of the column(s) used for 'groupby' logic
(the function will return the argmax by group)
---
### Example
**Input**
| variable | wave | year | value |
|:--------:|:-------:|:--------:|:-----:|
| toto | wave 1 | 2014 | 300 |
| toto | wave 1 | 2015 | 250 |
| toto | wave 1 | 2016 | 450 |
```cson
argmin:
column: 'year'
]
```
**Output**
| variable | wave | year | value |
|:--------:|:-------:|:--------:|:-----:|
| toto | wave 1 | 2015 | 250 |
"""
if groups is None:
df = df[df[column] == df[column].min()].reset_index(drop=True)
else:
group_min = df.groupby(groups)[column].transform('min')
df = (df
.loc[df[column] == group_min, :]
.drop_duplicates()
.reset_index(drop=True)
)
return df
|
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/argmax.py#L54-L101
|
deducting the median from each column
|
python
|
def column_mask(self):
"""ndarray, True where column margin <= min_base_size, same shape as slice."""
margin = compress_pruned(
self._slice.margin(
axis=0,
weighted=False,
include_transforms_for_dims=self._hs_dims,
prune=self._prune,
)
)
mask = margin < self._size
if margin.shape == self._shape:
# If margin shape is the same as slice's (such as in a col margin for
# MR x CAT), don't broadcast the mask to the array shape, since
# they're already the same.
return mask
# If the row margin is a row vector - broadcast it's mask to the array shape
return np.logical_or(np.zeros(self._shape, dtype=bool), mask)
|
https://github.com/Crunch-io/crunch-cube/blob/a837840755690eb14b2ec8e8d93b4104e01c854f/src/cr/cube/min_base_size_mask.py#L28-L47
|
deducting the median from each column
|
python
|
def max(self):
"""
:returns the maximum of the column
"""
res = self._qexec("max(%s)" % self._name)
if len(res) > 0:
self._max = res[0][0]
return self._max
|
https://github.com/grundprinzip/pyxplorer/blob/34c1d166cfef4a94aeb6d5fcb3cbb726d48146e2/pyxplorer/types.py#L74-L81
|
deducting the median from each column
|
python
|
def column( self, name ):
"""
Returns the index of the column at the given name.
:param name | <str>
:return <int> (-1 if not found)
"""
columns = self.columns()
if ( name in columns ):
return columns.index(name)
return -1
|
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtablewidget.py#L43-L54
|
deducting the median from each column
|
python
|
def primary_dimensions(self):
"""Iterate over the primary dimension columns, columns which do not have a parent
"""
from ambry.valuetype.core import ROLE
for c in self.columns:
if not c.parent and c.role == ROLE.DIMENSION:
yield c
|
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/table.py#L94-L103
|
deducting the median from each column
|
python
|
def min(self, values, axis=0):
"""return the minimum within each group
Parameters
----------
values : array_like, [keys, ...]
values to take minimum of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over groups
"""
values = np.asarray(values)
return self.unique, self.reduce(values, np.minimum, axis)
|
https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP/blob/84dc8114bf8a79c3acb3f7f59128247b9fc97243/numpy_indexed/grouping.py#L409-L427
|
deducting the median from each column
|
python
|
def _filter_matrix_columns(cls, matrix, phandango_header, csv_header):
'''phandango_header, csv_header, matrix = output from _to_matrix'''
indexes_to_keep = set()
for row in matrix:
for i in range(len(row)):
if row[i] not in {'NA', 'no'}:
indexes_to_keep.add(i)
indexes_to_keep = sorted(list(indexes_to_keep))
for i in range(len(matrix)):
matrix[i] = [matrix[i][j] for j in indexes_to_keep]
phandango_header = [phandango_header[i] for i in indexes_to_keep]
csv_header = [csv_header[i] for i in indexes_to_keep]
return phandango_header, csv_header, matrix
|
https://github.com/sanger-pathogens/ariba/blob/16a0b1916ce0e886bd22550ba2d648542977001b/ariba/summary.py#L240-L256
|
deducting the median from each column
|
python
|
def numpy_weighted_median(data, weights=None):
"""Calculate the weighted median of an array/list using numpy."""
import numpy as np
if weights is None:
return np.median(np.array(data).flatten())
data, weights = np.array(data).flatten(), np.array(weights).flatten()
if any(weights > 0):
sorted_data, sorted_weights = map(np.array, zip(*sorted(zip(data, weights))))
midpoint = 0.5 * sum(sorted_weights)
if any(weights > midpoint):
return (data[weights == np.max(weights)])[0]
cumulative_weight = np.cumsum(sorted_weights)
below_midpoint_index = np.where(cumulative_weight <= midpoint)[0][-1]
if cumulative_weight[below_midpoint_index] - midpoint < sys.float_info.epsilon:
return np.mean(sorted_data[below_midpoint_index:below_midpoint_index+2])
return sorted_data[below_midpoint_index+1]
|
https://github.com/tinybike/weightedstats/blob/0e2638099dba7f288a1553a83e957a95522229da/weightedstats/__init__.py#L89-L104
|
deducting the median from each column
|
python
|
def _column_reduction(self):
"""
Column reduction and reduction transfer steps from LAPJV algorithm
"""
#assign each column to its lowest cost row, ensuring that only row
#or column is assigned once
i1, j = np.unique(np.argmin(self.c, axis=0), return_index=True)
self._x[i1] = j
#if problem is solved, return
if len(i1) == self.n:
return False
self._y[j] = i1
#reduction_transfer
#tempc is array with previously assigned matchings masked
self._v = np.min(self.c, axis=0)
tempc = self.c.copy()
tempc[i1, j] = np.inf
mu = np.min(tempc[i1, :] - self._v[None, :], axis=1)
self._v[j] -= mu
return True
|
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/optimization/linear_assignment_numpy.py#L100-L122
|
deducting the median from each column
|
python
|
def par_compute_residuals(i):
"""Compute components of the residual and stopping thresholds that
can be done in parallel.
Parameters
----------
i : int
Index of group to compute
"""
# Compute the residuals in parallel, need to check if the residuals
# depend on alpha
global mp_ry0
global mp_ry1
global mp_sy0
global mp_sy1
global mp_nrmAx
global mp_nrmBy
global mp_nrmu
mp_ry0[i] = np.sum((mp_DXnr[i] - mp_Y0[i])**2)
mp_ry1[i] = mp_alpha**2*np.sum((mp_Xnr[mp_grp[i]:mp_grp[i+1]]-
mp_Y1[mp_grp[i]:mp_grp[i+1]])**2)
mp_sy0[i] = np.sum((mp_Y0old[i] - mp_Y0[i])**2)
mp_sy1[i] = mp_alpha**2*np.sum((mp_Y1old[mp_grp[i]:mp_grp[i+1]]-
mp_Y1[mp_grp[i]:mp_grp[i+1]])**2)
mp_nrmAx[i] = np.sum(mp_DXnr[i]**2) + mp_alpha**2 * np.sum(
mp_Xnr[mp_grp[i]:mp_grp[i+1]]**2)
mp_nrmBy[i] = np.sum(mp_Y0[i]**2) + mp_alpha**2 * np.sum(
mp_Y1[mp_grp[i]:mp_grp[i+1]]**2)
mp_nrmu[i] = np.sum(mp_U0[i]**2) + np.sum(mp_U1[mp_grp[i]:mp_grp[i+1]]**2)
|
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/admm/parcbpdn.py#L317-L346
|
deducting the median from each column
|
python
|
def mad(a, axis=None, c=1.4826, return_med=False):
"""Compute normalized median absolute difference
Can also return median array, as this can be expensive, and often we want both med and nmad
Note: 1.4826 = 1/0.6745
"""
a = checkma(a)
#return np.ma.median(np.fabs(a - np.ma.median(a))) / c
if a.count() > 0:
if axis is None:
med = fast_median(a)
out = fast_median(np.fabs(a - med)) * c
else:
med = np.ma.median(a, axis=axis)
#This is necessary for broadcasting
med = np.expand_dims(med, axis=axis)
out = np.ma.median(np.ma.fabs(a - med), axis=axis) * c
else:
out = np.ma.masked
if return_med:
out = (out, med)
return out
|
https://github.com/dshean/pygeotools/blob/5ac745717c0098d01eb293ff1fe32fd7358c76ab/pygeotools/lib/malib.py#L1505-L1527
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.