本文整理汇总了Python中numpy.select方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.select方法的具体用法?Python numpy.select怎么用?Python numpy.select使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gsea_pval
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def gsea_pval(es, esnull):
"""Compute nominal p-value.
From article (PNAS):
estimate nominal p-value for S from esnull by using the positive
or negative portion of the distribution corresponding to the sign
of the observed ES(S).
"""
# to speed up, using numpy function to compute pval in parallel.
condlist = [ es < 0, es >=0]
choicelist = [(esnull < es.reshape(len(es),1)).sum(axis=1)/ (esnull < 0).sum(axis=1),
(esnull >= es.reshape(len(es),1)).sum(axis=1)/ (esnull >= 0).sum(axis=1)]
pvals = np.select(condlist, choicelist)
return pvals
示例2: test_searched_case_column
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def test_searched_case_column(batting, batting_df):
t = batting
df = batting_df
expr = (
ibis.case()
.when(t.RBI < 5, 'really bad team')
.when(t.teamID == 'PH1', 'ph1 team')
.else_(t.teamID)
.end()
)
result = expr.execute()
expected = pd.Series(
np.select(
[df.RBI < 5, df.teamID == 'PH1'],
['really bad team', 'ph1 team'],
df.teamID,
)
)
tm.assert_series_equal(result, expected)
示例3: test_simple_case_column
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def test_simple_case_column(batting, batting_df):
t = batting
df = batting_df
expr = (
t.RBI.case()
.when(5, 'five')
.when(4, 'four')
.when(3, 'three')
.else_('could be good?')
.end()
)
result = expr.execute()
expected = pd.Series(
np.select(
[df.RBI == 5, df.RBI == 4, df.RBI == 3],
['five', 'four', 'three'],
'could be good?',
)
)
tm.assert_series_equal(result, expected)
示例4: testSelect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def testSelect(self, rng_factory, shapes, dtypes):
rng = rng_factory()
n = len(dtypes) - 1
def args_maker():
condlist = [rng(shape, onp.bool_) for shape in shapes[:n]]
choicelist = [rng(shape, dtype)
for shape, dtype in zip(shapes[n:-1], dtypes[:n])]
default = rng(shapes[-1], dtypes[-1])
return condlist, choicelist, default
# TODO(phawkins): float32/float64 type mismatches
def onp_fun(condlist, choicelist, default):
choicelist = [x if lnp.bfloat16 != lnp.result_type(x)
else x.astype(onp.float32) for x in choicelist]
dtype = lnp.result_type(default, *choicelist)
return onp.select(condlist,
[onp.asarray(x, dtype=dtype) for x in choicelist],
onp.asarray(default, dtype=dtype))
self._CheckAgainstNumpy(onp_fun, lnp.select, args_maker,
check_dtypes=False)
self._CompileAndCheck(lnp.select, args_maker, check_dtypes=True,
check_incomplete_shape=True,
rtol={onp.float64: 1e-7, onp.complex128: 1e-7})
示例5: check_quantifier_results
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def check_quantifier_results(path):
"""Check quantifier vs results file in case of miscounts"""
resfile = glob.glob(os.path.join(path,'result*.csv'))[0]
df = read_results_file(resfile)
files = glob.glob(os.path.join(path,'miRNAs_expressed_all_samples*.csv'))
q = pd.read_csv(files[0],sep='\t')
key='provisional id'
m=q.merge(df,left_on='#miRNA',right_on=key).drop_duplicates('#miRNA')
m.sc = m['miRDeep2 score']
m['err'] = abs(m['read_count']-m['total read count'])
cols=['#miRNA','total read count','read_count','miRDeep2 score']
print (m[m.err>400].sort('total read count',ascending=False)[cols])
m['size'] = np.select([m.sc < 2, m.sc < 3, m.sc < 4], [20,40,50], 80)
f,ax=plt.subplots(1,1)
plt.xscale('log')
plt.yscale('log')
m.plot(x='total read count',y='read_count', kind='scatter',s=60,alpha=0.6,ax=ax)
#ax.plot([0, 1], [0, 1], transform=ax.transAxes,color='red',alpha=0.7)
plt.show()
return
示例6: take
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def take(a, indices, axis=None, out=None):
"""Takes elements of an array at specified indices along an axis.
This is an implementation of "fancy indexing" at single axis.
This function does not support ``mode`` option.
Args:
a (cupy.ndarray): Array to extract elements.
indices (int or array-like): Indices of elements that this function
takes.
axis (int): The axis along which to select indices. The flattened input
is used by default.
out (cupy.ndarray): Output array. If provided, it should be of
appropriate shape and dtype.
Returns:
cupy.ndarray: The result of fancy indexing.
.. seealso:: :func:`numpy.take`
"""
# TODO(okuta): check type
return a.take(indices, axis, out)
示例7: rgb_to_hsv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def rgb_to_hsv(rgb):
# Translated from source of colorsys.rgb_to_hsv
# r,g,b should be a numpy arrays with values between 0 and 255
# rgb_to_hsv returns an array of floats between 0.0 and 1.0.
rgb = rgb.astype('float')
hsv = np.zeros_like(rgb)
# in case an RGBA array was passed, just copy the A channel
hsv[..., 3:] = rgb[..., 3:]
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
maxc = np.max(rgb[..., :3], axis=-1)
minc = np.min(rgb[..., :3], axis=-1)
hsv[..., 2] = maxc
mask = maxc != minc
hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask]
rc = np.zeros_like(r)
gc = np.zeros_like(g)
bc = np.zeros_like(b)
rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask]
gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask]
bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask]
hsv[..., 0] = np.select([r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc)
hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0
return hsv
示例8: hsv_to_rgb
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def hsv_to_rgb(hsv):
# Translated from source of colorsys.hsv_to_rgb
# h,s should be a numpy arrays with values between 0.0 and 1.0
# v should be a numpy array with values between 0.0 and 255.0
# hsv_to_rgb returns an array of uints between 0 and 255.
rgb = np.empty_like(hsv)
rgb[..., 3:] = hsv[..., 3:]
h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2]
i = (h * 6.0).astype('uint8')
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i % 6
conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5]
rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v)
rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t)
rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p)
return rgb.astype('uint8')
示例9: simulate_conditional
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def simulate_conditional(self, X):
""" Draws random samples from the conditional distribution
Args:
X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x)
Returns:
Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)
"""
mean = self.arma_c * (1 - self.arma_a1) + self.arma_a1 * X
y_ar = self.random_state.normal(loc=mean, scale=self.std, size=X.shape[0])
mean_jump = mean + self.jump_mean
y_jump = self.random_state.normal(loc=mean_jump, scale=self.jump_std, size=X.shape[0])
jump_bernoulli = self.random_state.uniform(size=X.shape[0]) < self.jump_prob
return X, np.select([jump_bernoulli, np.bitwise_not(jump_bernoulli)], [y_jump, y_ar])
示例10: evaluate
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def evaluate(x, y, amplitude, x_0, y_0, a, b, theta):
"""Two dimensional Ellipse model function."""
xx = x - x_0
yy = y - y_0
cost = np.cos(theta)
sint = np.sin(theta)
numerator1 = (xx * cost) + (yy * sint)
numerator2 = -(xx * sint) + (yy * cost)
in_ellipse = (((numerator1 / a) ** 2 + (numerator2 / b) ** 2) <= 1.)
result = np.select([in_ellipse], [amplitude])
if isinstance(amplitude, Quantity):
return Quantity(result, unit=amplitude.unit, copy=False)
else:
return result
示例11: _lazyselect
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def _lazyselect(condlist, choicelist, arrays, default=0):
"""
Mimic `np.select(condlist, choicelist)`.
Notice it assumes that all `arrays` are of the same shape, or can be
broadcasted together.
All functions in `choicelist` must accept array arguments in the order
given in `arrays` and must return an array of the same shape as broadcasted
`arrays`.
Examples
--------
>>> x = np.arange(6)
>>> np.select([x <3, x > 3], [x**2, x**3], default=0)
array([ 0, 1, 4, 0, 64, 125])
>>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,))
array([ 0., 1., 4., 0., 64., 125.])
>>> a = -np.ones_like(x)
>>> _lazyselect([x < 3, x > 3],
... [lambda x, a: x**2, lambda x, a: a * x**3],
... (x, a), default=np.nan)
array([ 0., 1., 4., nan, -64., -125.])
"""
arrays = np.broadcast_arrays(*arrays)
tcode = np.mintypecode([a.dtype.char for a in arrays])
out = _valarray(np.shape(arrays[0]), value=default, typecode=tcode)
for index in range(len(condlist)):
func, cond = choicelist[index], condlist[index]
if np.all(cond is False):
continue
cond, _ = np.broadcast_arrays(cond, arrays[0])
temp = tuple(np.extract(cond, arr) for arr in arrays)
np.place(out, cond, func(*temp))
return out
示例12: _pdf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def _pdf(self, x, c, d):
u = 2 / (d - c + 1)
condlist = [x < c, x <= d, x > d]
choicelist = [u * x / c, u, u * (1 - x) / (1 - d)]
return np.select(condlist, choicelist)
示例13: _cdf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def _cdf(self, x, c, d):
condlist = [x < c, x <= d, x > d]
choicelist = [x**2 / c / (d - c + 1),
(c + 2 * (x - c)) / (d - c + 1),
1 - ((1 - x)**2 / (d - c + 1) / (1 - d))]
return np.select(condlist, choicelist)
示例14: _ppf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def _ppf(self, q, c, d):
qc, qd = self._cdf(c, c, d), self._cdf(d, c, d)
condlist = [q < qc, q <= qd, q > qd]
choicelist = [np.sqrt(q * c * (1 + d - c)),
0.5 * q * (1 + d - c) + 0.5 * c,
1 - np.sqrt((1 - q) * (d - c + 1) * (1 - d))]
return np.select(condlist, choicelist)
示例15: _pmf
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import select [as 别名]
def _pmf(self, x):
return np.select([x == k for k in self.xk],
[np.broadcast_arrays(p, x)[0] for p in self.pk], 0)