本文整理匯總了Python中numpy.in1d方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.in1d方法的具體用法?Python numpy.in1d怎麽用?Python numpy.in1d使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.in1d方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: map_values
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def map_values(values, pos, target_pos, dtype=None, nan=dat.CPG_NAN):
"""Maps `values` array at positions `pos` to `target_pos`.
Inserts `nan` for uncovered positions.
"""
assert len(values) == len(pos)
assert np.all(pos == np.sort(pos))
assert np.all(target_pos == np.sort(target_pos))
values = values.ravel()
pos = pos.ravel()
target_pos = target_pos.ravel()
idx = np.in1d(pos, target_pos)
pos = pos[idx]
values = values[idx]
if not dtype:
dtype = values.dtype
target_values = np.empty(len(target_pos), dtype=dtype)
target_values.fill(nan)
idx = np.in1d(target_pos, pos).nonzero()[0]
assert len(idx) == len(values)
assert np.all(target_pos[idx] == pos)
target_values[idx] = values
return target_values
示例2: _fit
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def _fit(self, classif, X, a, r, p, rs):
obs_take = np.in1d(a, self.tree.node_comparisons[classif][0])
X_node = X[obs_take, :]
a_node = a[obs_take]
r_node = r[obs_take]
p_node = p[obs_take]
r_more_onehalf = r_node >= .5
y = ( np.in1d(a_node, self.tree.node_comparisons[classif][2]) ).astype('uint8')
y_node = y.copy()
y_node[r_more_onehalf] = 1. - y[r_more_onehalf]
w_node = (.5 - r_node) / p_node
w_node[r_more_onehalf] = ( (r_node - .5) / p_node )[r_more_onehalf]
w_node = w_node * (w_node.shape[0] / np.sum(w_node))
n_pos = y_node.sum()
if y_node.shape[0] == 0:
self._oracles[classif] = _RandomPredictor(_check_random_state(rs[classif]))
elif n_pos == y_node.shape[0]:
self._oracles[classif] = _OnePredictor()
elif n_pos == 0:
self._oracles[classif] = _ZeroPredictor()
else:
self._oracles[classif].fit(X_node, y_node, sample_weight = w_node)
示例3: read_file
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def read_file(file, participant):
"""Utility function
"""
# Get signal
data = pd.DataFrame({"ECG": wfdb.rdsamp(file[:-4])[0][:, 0]})
data["Participant"] = "MIT-Arrhythmia_%.2i" %(participant)
data["Sample"] = range(len(data))
data["Sampling_Rate"] = 360
data["Database"] = "MIT-Arrhythmia-x" if "x_mitdb" in file else "MIT-Arrhythmia"
# getting annotations
anno = wfdb.rdann(file[:-4], 'atr')
anno = np.unique(anno.sample[np.in1d(anno.symbol, ['N', 'L', 'R', 'B', 'A', 'a', 'J', 'S', 'V', 'r', 'F', 'e', 'j', 'n', 'E', '/', 'f', 'Q', '?'])])
anno = pd.DataFrame({"Rpeaks": anno})
anno["Participant"] = "MIT-Arrhythmia_%.2i" %(participant)
anno["Sampling_Rate"] = 360
anno["Database"] = "MIT-Arrhythmia-x" if "x_mitdb" in file else "MIT-Arrhythmia"
return data, anno
示例4: _get_roi
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def _get_roi(center, radius, mesh, mesh_surface=[5, 1005], min_cos=.1):
''' Defines the region of interest of a given radius. Around a given center. Only
node with normals pointing in the given direction are
considered. Returns a list of triangles with at least 1 element in the ROI'''
center = np.array(center, dtype=float)
nodes_in_surface = _get_nodes_in_surface(mesh, mesh_surface)
if len(nodes_in_surface) == 0:
raise ValueError('Could not find surface {0} in mesh'.format(mesh_surface))
distances = np.linalg.norm(center - mesh.nodes[nodes_in_surface], axis=1)
normals = mesh.nodes_normals()[nodes_in_surface]
center_normal = normals[np.argmin(distances)]
in_roi = nodes_in_surface[(distances <= radius) *
(center_normal.dot(normals.T) > min_cos)]
tr_in_roi = np.any(
np.in1d(mesh.elm[mesh.elm.triangles, :3], in_roi).reshape(-1, 3), axis=1)
roi_nodes, roi_triangles_reordering = \
np.unique(mesh.elm[mesh.elm.triangles[tr_in_roi], :3], return_inverse=True)
return mesh.elm.triangles[tr_in_roi], roi_nodes, roi_triangles_reordering.reshape(-1,
3)
示例5: _move_point
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def _move_point(new_position, to_be_moved, nodes, triangles, min_angle=0.25,
edge_list=None, kdtree=None):
'''Moves one point to the new_position. The angle of the patch should not become less
than min_angle (in radians) '''
# Certify that the new_position is inside the patch
tr = _triangle_with_points(np.atleast_2d(new_position), triangles, nodes,
edge_list=edge_list, kdtree=kdtree)
tr_with_node = np.where(np.any(triangles == to_be_moved, axis=1))[0]
patch = triangles[tr_with_node]
if not np.in1d(tr, tr_with_node):
return None, None
new_nodes = np.copy(nodes)
position = nodes[to_be_moved]
d = new_position - position
# Start from the full move and go back
for t in np.linspace(0, 1, num=10)[::-1]:
new_nodes[to_be_moved] = position + t*d
angle = np.min(_calc_triangle_angles(new_nodes[patch]))
if angle > min_angle:
break
# Return the new node list and the minimum angle in the patch
return new_nodes, angle
示例6: apply_to_solution
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def apply_to_solution(self, x, dof_map):
''' Applies the dirichlet BC to a solution
Parameters:
-------
x: numpy array
Righ-hand side
dof_map: dofMap
Mapping of node indexes to rows and columns in A and b
Returns:
------
x: numpy array
Righ-hand side, modified
dof_map: dofMap
Mapping of node indexes to rows and columns in A and b, modified
'''
if np.any(np.in1d(self.nodes, dof_map.inverse)):
raise ValueError('Found DOFs already defined')
dof_inverse = np.hstack((dof_map.inverse, self.nodes))
x = np.atleast_2d(x)
if x.shape[0] < x.shape[1]:
x = x.T
x = np.vstack((x, np.tile(self.values, (x.shape[1], 1)).T))
return x, dofMap(dof_inverse)
示例7: test_join_mesh_data
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def test_join_mesh_data(self, sphere3_msh):
m1 = sphere3_msh.crop_mesh([3, 1003])
m1.nodedata = [mesh_io.NodeData(value=m1.nodes.node_coord)]
m1.elmdata = [m1.elements_baricenters()]
m2 = sphere3_msh.crop_mesh([5, 1005])
m2.nodedata = [mesh_io.NodeData(value=m2.nodes.node_number)]
m2.elmdata = [mesh_io.ElementData(value=m2.elm.tag1)]
m = m1.join_mesh(m2)
assert np.all(np.isclose(m.nodedata[0].value[:m1.nodes.nr],m1.nodes.node_coord))
assert np.all(np.isnan(m.nodedata[0].value[m1.nodes.nr:]))
v = m.elmdata[0].value
ref = m1.elmdata[0].value
assert np.all(np.isclose(v[np.in1d(m.elm.tag1, [3, 1003])], ref))
assert np.all(np.isnan(v[~np.in1d(m.elm.tag1, [3, 1003])]))
assert np.all(np.isclose(m.nodedata[1].value[m1.nodes.nr:],m2.nodes.node_number))
assert np.all(np.isnan(m.nodedata[1].value[:m1.nodes.nr]))
v = m.elmdata[1].value
ref = m2.elmdata[0].value
assert np.all(np.isclose(v[np.in1d(m.elm.tag1, [5, 1005])], ref))
assert np.all(np.isnan(v[~np.in1d(m.elm.tag1, [5, 1005])]))
示例8: group_years
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def group_years(years, interval=3):
""" Return integers representing sequential groupings of years
Note: years specified must be sorted
Args:
years (np.ndarray): the year corresponding to each EVI value
interval (int, optional): number of years to group together
(default: 3)
Returns:
np.ndarray: integers representing sequential year groupings
"""
n_groups = math.ceil((years.max() - years.min()) / interval)
if n_groups <= 1:
return np.zeros_like(years, dtype=np.uint16)
splits = np.array_split(np.arange(years.min(), years.max() + 1), n_groups)
groups = np.zeros_like(years, dtype=np.uint16)
for i, s in enumerate(splits):
groups[np.in1d(years, s)] = i
return groups
示例9: __iter__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def __iter__(self):
n = self.n
n_folds = self.n_folds
fold_sizes = (n // n_folds) * np.ones(n_folds, dtype=np.int)
fold_sizes[:n % n_folds] += 1
current = 0
for fold_size in fold_sizes:
start, stop = current, current + fold_size
test_i = np.in1d(self.indices[:, 0], self.labels[start:stop])
train_i = np.in1d(self.indices[:, 0], self.labels[stop:])
yield ((self.indices[test_i, 1], self.indices[test_i, 2]),
(self.indices[train_i, 1], self.indices[train_i, 2]))
current = stop
示例10: _label_roi
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def _label_roi(self):
""" Internal method to label region of interest image
"""
labeled, n = scipy.ndimage.label(self.roi)
labels = np.unique(labeled)
self.labels = labels[~np.in1d(labels, self.mask_values)]
self.n = self.labels.size
n_samples = (~np.in1d(self.roi, self.mask_values)).sum()
self.indices = np.zeros((n_samples, 3), dtype=np.int)
_start = 0
for l in self.labels:
_n = (labeled == l).sum()
_row, _col = np.where(labeled == l)
self.indices[_start:_start + _n, 0] = l
self.indices[_start:_start + _n, 1] = _row
self.indices[_start:_start + _n, 2] = _col
_start += _n
if self.shuffle:
self.rng.shuffle(self.labels)
示例11: plot_TS
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def plot_TS(dates, y, seasons):
""" Create a standard timeseries plot
Args:
dates (iterable): sequence of datetime
y (np.ndarray): variable to plot
seasons (bool): Plot seasonal symbology
"""
# Plot data
if seasons:
months = np.array([d.month for d in dates])
for season_months, color, alpha in SEASONS.values():
season_idx = np.in1d(months, season_months)
plt.plot(dates[season_idx], y[season_idx], marker='o',
mec=color, mfc=color, alpha=alpha, ls='')
else:
plt.scatter(dates, y, c='k', marker='o', edgecolors='none', s=35)
plt.xlabel('Date')
示例12: ensure_resampled_obs_ids_in_df
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def ensure_resampled_obs_ids_in_df(resampled_obs_ids, orig_obs_id_array):
"""
Checks whether all ids in `resampled_obs_ids` are in `orig_obs_id_array`.
Raises a helpful ValueError if not.
Parameters
----------
resampled_obs_ids : 1D ndarray of ints.
Should contain the observation ids of the observational units that will
be used in the current bootstrap sample.
orig_obs_id_array : 1D ndarray of ints.
Should countain the observation ids of the observational units in the
original dataframe containing the data for this model.
Returns
-------
None.
"""
if not np.in1d(resampled_obs_ids, orig_obs_id_array).all():
msg =\
"All values in `resampled_obs_ids` MUST be in `orig_obs_id_array`."
raise ValueError(msg)
return None
示例13: clear_dust
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def clear_dust(data, min_size=10):
"""Removes small objects from a segmentation array.
Replaces objects smaller than `min_size` with 0 (background).
Args:
data: numpy array of segment IDs
min_size: minimum size in voxels of an object to be retained
Returns:
the data array (modified in place)
"""
ids, sizes = np.unique(data, return_counts=True)
small = ids[sizes < min_size]
small_mask = np.in1d(data.flat, small).reshape(data.shape)
data[small_mask] = 0
return data
示例14: subset
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def subset(self, query_ids, name=None):
"""
This method return a subset of the dataset according to the query_ids
parameter.
Parameters
----------
query_ids : numpy 1d array of int
It is a ndarray with the query_ids to select
name : str
The name to give to the dataset
Returns
-------
datasets : rankeval.dataset.Dataset
The resulting dataset with only the query_ids requested
"""
qid_map = self.get_qids_dataset()
mask = np.in1d(qid_map, query_ids)
return Dataset(self.X[mask], self.y[mask],
qid_map[mask], name=name)
示例15: _update_material_types
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import in1d [as 別名]
def _update_material_types(self):
# What do the materials (in air/sediment terms) look like now?
if self.Model.mesh.dim == 3:
material_flags = self._determine_particle_state()
if self.Model.mesh.dim == 2:
material_flags = self._determine_particle_state_2D()
# If any materials changed state, update the Underworld material types
mi = self.Model.materialField.data
# convert air to sediment
for air_material in self.airIndex:
sedimented_mask = np.logical_and(np.in1d(mi, air_material), material_flags)
mi[sedimented_mask] = self.sedimentIndex
# convert sediment to air
for air_material in self.airIndex:
eroded_mask = np.logical_and(~np.in1d(mi, air_material), ~material_flags)
mi[eroded_mask] = self.airIndex[0]