本文整理匯總了Python中numpy.putmask方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.putmask方法的具體用法?Python numpy.putmask怎麽用?Python numpy.putmask使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.putmask方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_frame_getitem_setitem_boolean
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def test_frame_getitem_setitem_boolean(
self, multiindex_dataframe_random_data):
frame = multiindex_dataframe_random_data
df = frame.T.copy()
values = df.values
result = df[df > 0]
expected = df.where(df > 0)
tm.assert_frame_equal(result, expected)
df[df > 0] = 5
values[values > 0] = 5
tm.assert_almost_equal(df.values, values)
df[df == 5] = 0
values[values == 5] = 0
tm.assert_almost_equal(df.values, values)
# a df that needs alignment first
df[df[:-1] < 0] = 2
np.putmask(values[:-1], values[:-1] < 0, 2)
tm.assert_almost_equal(df.values, values)
with pytest.raises(TypeError, match='boolean values only'):
df[df * 0] = 2
示例2: _join_non_unique
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _join_non_unique(self, other, how='left', return_indexers=False):
from pandas.core.reshape.merge import _get_join_indexers
left_idx, right_idx = _get_join_indexers([self._ndarray_values],
[other._ndarray_values],
how=how,
sort=True)
left_idx = ensure_platform_int(left_idx)
right_idx = ensure_platform_int(right_idx)
join_index = np.asarray(self._ndarray_values.take(left_idx))
mask = left_idx == -1
np.putmask(join_index, mask, other._ndarray_values.take(right_idx))
join_index = self._wrap_joined_index(join_index, other)
if return_indexers:
return join_index, left_idx, right_idx
else:
return join_index
示例3: putmask
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def putmask(self, mask, value):
"""
Return a new Index of the values set with the mask.
See Also
--------
numpy.ndarray.putmask
"""
values = self.values.copy()
try:
np.putmask(values, mask, self._convert_for_op(value))
return self._shallow_copy(values)
except (ValueError, TypeError) as err:
if is_object_dtype(self):
raise err
# coerces to object
return self.astype(object).putmask(mask, value)
示例4: decons_group_index
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def decons_group_index(comp_labels, shape):
# reconstruct labels
if is_int64_overflow_possible(shape):
# at some point group indices are factorized,
# and may not be deconstructed here! wrong path!
raise ValueError('cannot deconstruct factorized group indices!')
label_list = []
factor = 1
y = 0
x = comp_labels
for i in reversed(range(len(shape))):
labels = (x - y) % (factor * shape[i]) // factor
np.putmask(labels, comp_labels < 0, -1)
label_list.append(labels)
y = labels * factor
factor *= shape[i]
return label_list[::-1]
示例5: _reorder_by_uniques
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _reorder_by_uniques(uniques, labels):
# sorter is index where elements ought to go
sorter = uniques.argsort()
# reverse_indexer is where elements came from
reverse_indexer = np.empty(len(sorter), dtype=np.int64)
reverse_indexer.put(sorter, np.arange(len(sorter)))
mask = labels < 0
# move labels to right locations (ie, unsort ascending labels)
labels = algorithms.take_nd(reverse_indexer, labels, allow_fill=False)
np.putmask(labels, mask, -1)
# sort observed ids
uniques = algorithms.take_nd(uniques, sorter, allow_fill=False)
return uniques, labels
示例6: _get_counts_nanvar
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _get_counts_nanvar(mask, axis, ddof, dtype=float):
dtype = _get_dtype(dtype)
count = _get_counts(mask, axis, dtype=dtype)
d = count - dtype.type(ddof)
# always return NaN, never inf
if is_scalar(count):
if count <= ddof:
count = np.nan
d = np.nan
else:
mask2 = count <= ddof
if mask2.any():
np.putmask(d, mask2, np.nan)
np.putmask(count, mask2, np.nan)
return count, d
示例7: make_nancomp
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def make_nancomp(op):
def f(x, y):
xmask = isna(x)
ymask = isna(y)
mask = xmask | ymask
with np.errstate(all='ignore'):
result = op(x, y)
if mask.any():
if is_bool_dtype(result):
result = result.astype('O')
np.putmask(result, mask, np.nan)
return result
return f
示例8: test_frame_getitem_setitem_boolean
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def test_frame_getitem_setitem_boolean(self):
df = self.frame.T.copy()
values = df.values
result = df[df > 0]
expected = df.where(df > 0)
tm.assert_frame_equal(result, expected)
df[df > 0] = 5
values[values > 0] = 5
tm.assert_almost_equal(df.values, values)
df[df == 5] = 0
values[values == 5] = 0
tm.assert_almost_equal(df.values, values)
# a df that needs alignment first
df[df[:-1] < 0] = 2
np.putmask(values[:-1], values[:-1] < 0, 2)
tm.assert_almost_equal(df.values, values)
with tm.assert_raises_regex(TypeError, 'boolean values only'):
df[df * 0] = 2
示例9: _join_non_unique
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _join_non_unique(self, other, how='left', return_indexers=False):
from pandas.core.reshape.merge import _get_join_indexers
left_idx, right_idx = _get_join_indexers([self._ndarray_values],
[other._ndarray_values],
how=how,
sort=True)
left_idx = _ensure_platform_int(left_idx)
right_idx = _ensure_platform_int(right_idx)
join_index = np.asarray(self._ndarray_values.take(left_idx))
mask = left_idx == -1
np.putmask(join_index, mask, other._ndarray_values.take(right_idx))
join_index = self._wrap_joined_index(join_index, other)
if return_indexers:
return join_index, left_idx, right_idx
else:
return join_index
示例10: DiscretizeDistMatrix
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def DiscretizeDistMatrix(distm, bins=None, invalidDistanceSeparated=False):
assert (bins is not None)
result = np.digitize(distm, bins) - 1
if invalidDistanceSeparated:
## -1 and the maximum distance bin are separated
np.putmask(result, result == -1, len(bins) )
labels = range( len(bins) + 1 )
else:
## -1 and the maximum distance bin are merged into a single bin
np.putmask(result, result == -1, len(bins) -1 )
labels = range( len(bins) )
return result.astype(np.int32), np.int32(labels), bins
## calculate the natural logarithm of a matrix
示例11: _sort_labels
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _sort_labels(uniques, left, right):
if not isinstance(uniques, np.ndarray):
# tuplesafe
uniques = Index(uniques).values
sorter = uniques.argsort()
reverse_indexer = np.empty(len(sorter), dtype=np.int64)
reverse_indexer.put(sorter, np.arange(len(sorter)))
new_left = reverse_indexer.take(com._ensure_platform_int(left))
np.putmask(new_left, left == -1, -1)
new_right = reverse_indexer.take(com._ensure_platform_int(right))
np.putmask(new_right, right == -1, -1)
return new_left, new_right
示例12: get_group_index
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def get_group_index(label_list, shape):
"""
For the particular label_list, gets the offsets into the hypothetical list
representing the totally ordered cartesian product of all possible label
combinations.
"""
if len(label_list) == 1:
return label_list[0]
n = len(label_list[0])
group_index = np.zeros(n, dtype=np.int64)
mask = np.zeros(n, dtype=bool)
for i in range(len(shape)):
stride = np.prod([x for x in shape[i + 1:]], dtype=np.int64)
group_index += com._ensure_int64(label_list[i]) * stride
mask |= label_list[i] < 0
np.putmask(group_index, mask, -1)
return group_index
示例13: _reorder_by_uniques
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _reorder_by_uniques(uniques, labels):
# sorter is index where elements ought to go
sorter = uniques.argsort()
# reverse_indexer is where elements came from
reverse_indexer = np.empty(len(sorter), dtype=np.int64)
reverse_indexer.put(sorter, np.arange(len(sorter)))
mask = labels < 0
# move labels to right locations (ie, unsort ascending labels)
labels = com.take_nd(reverse_indexer, labels, allow_fill=False)
np.putmask(labels, mask, -1)
# sort observed ids
uniques = com.take_nd(uniques, sorter, allow_fill=False)
return uniques, labels
示例14: _map
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _map(f, arr, na_mask=False, na_value=np.nan):
if isinstance(arr, Series):
arr = arr.values
if not isinstance(arr, np.ndarray):
arr = np.asarray(arr, dtype=object)
if na_mask:
mask = isnull(arr)
try:
result = lib.map_infer_mask(arr, f, mask.view(np.uint8))
except (TypeError, AttributeError):
def g(x):
try:
return f(x)
except (TypeError, AttributeError):
return na_value
return _map(g, arr)
if na_value is not np.nan:
np.putmask(result, mask, na_value)
if result.dtype == object:
result = lib.maybe_convert_objects(result)
return result
else:
return lib.map_infer(arr, f)
示例15: _convert_types
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import putmask [as 別名]
def _convert_types(self, a):
"""
Converts object arrays of strings to numpy string arrays
"""
# No conversion for scalar type
if a.dtype != 'object':
return a, None
# We can't infer the type of an empty array, so just
# assume strings
if len(a) == 0:
return a.astype('U1'), None
# Compute a mask of missing values. Replace NaNs and Nones with
# empty strings so that type inference has a chance.
mask = pd.isnull(a)
if mask.sum() > 0:
a = a.copy()
np.putmask(a, mask, '')
else:
mask = None
if infer_dtype(a, skipna=False) == 'mixed':
# assume its a string, otherwise raise an error
try:
a = np.array([s.encode('ascii') for s in a])
a = a.astype('O')
except:
raise ValueError("Column of type 'mixed' cannot be converted to string")
type_ = infer_dtype(a, skipna=False)
if type_ in ['unicode', 'string']:
max_len = max_len_string_array(a)
return a.astype('U{:d}'.format(max_len)), mask
else:
raise ValueError('Cannot store arrays with {} dtype'.format(type_))