本文整理汇总了Python中numpy.find_common_type函数的典型用法代码示例。如果您正苦于以下问题:Python find_common_type函数的具体用法?Python find_common_type怎么用?Python find_common_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了find_common_type函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: na_op
def na_op(x, y):
try:
result = expressions.evaluate(
op, str_rep, x, y, raise_on_error=True, **eval_kwargs)
except TypeError:
xrav = x.ravel()
if isinstance(y, (np.ndarray, pd.Series)):
dtype = np.find_common_type([x.dtype, y.dtype], [])
result = np.empty(x.size, dtype=dtype)
yrav = y.ravel()
mask = notnull(xrav) & notnull(yrav)
xrav = xrav[mask]
yrav = yrav[mask]
if np.prod(xrav.shape) and np.prod(yrav.shape):
result[mask] = op(xrav, yrav)
elif hasattr(x,'size'):
result = np.empty(x.size, dtype=x.dtype)
mask = notnull(xrav)
xrav = xrav[mask]
if np.prod(xrav.shape):
result[mask] = op(xrav, y)
else:
raise TypeError("cannot perform operation {op} between objects "
"of type {x} and {y}".format(op=name,x=type(x),y=type(y)))
result, changed = com._maybe_upcast_putmask(result, ~mask, np.nan)
result = result.reshape(x.shape)
result = com._fill_zeros(result, x, y, name, fill_zeros)
return result
开发者ID:agijsberts,项目名称:pandas,代码行数:31,代码来源:ops.py
示例2: __init__
def __init__(self, dfs, column_name):
self.dfs = dfs
self.column_name = column_name
dtypes = [df.dtype(column_name) for df in dfs]
self.is_masked = any([df.is_masked(column_name) for df in dfs])
if self.is_masked:
self.fill_value = dfs[0].columns[self.column_name].fill_value
# np.datetime64 and find_common_type don't mix very well
any_strings = any([dtype == str_type for dtype in dtypes])
if any_strings:
self.dtype = str_type
else:
if all([dtype.type == np.datetime64 for dtype in dtypes]):
self.dtype = dtypes[0]
else:
if all([dtype == dtypes[0] for dtype in dtypes]): # find common types doesn't always behave well
self.dtype = dtypes[0]
if any([dtype.kind in 'SU' for dtype in dtypes]): # strings are also done manually
if all([dtype.kind in 'SU' for dtype in dtypes]):
index = np.argmax([dtype.itemsize for dtype in dtypes])
self.dtype = dtypes[index]
else:
index = np.argmax([df.columns[self.column_name].astype('O').astype('U').dtype.itemsize for df in dfs])
self.dtype = dfs[index].columns[self.column_name].astype('O').astype('U').dtype
else:
self.dtype = np.find_common_type(dtypes, [])
logger.debug("common type for %r is %r", dtypes, self.dtype)
self.shape = (len(self), ) + self.dfs[0].evaluate(self.column_name, i1=0, i2=1).shape[1:]
for i in range(1, len(dfs)):
shape_i = (len(self), ) + self.dfs[i].evaluate(self.column_name, i1=0, i2=1).shape[1:]
if self.shape != shape_i:
raise ValueError("shape of of column %s, array index 0, is %r and is incompatible with the shape of the same column of array index %d, %r" % (self.column_name, self.shape, i, shape_i))
开发者ID:maartenbreddels,项目名称:vaex,代码行数:32,代码来源:column.py
示例3: _common_dtype
def _common_dtype(x, y):
"""Determines common numpy DTYPE for arrays."""
dtype = np.find_common_type([x.dtype, y.dtype], [])
if x.dtype != dtype: x = x.astype(dtype)
if y.dtype != dtype: y = y.astype(dtype)
return x, y
开发者ID:laszukdawid,项目名称:PyEMD,代码行数:7,代码来源:EMD.py
示例4: _bmat
def _bmat(blocks, dtypes):
from pytools import single_valued
from pytential.symbolic.matrix import is_zero
nrows = blocks.shape[0]
ncolumns = blocks.shape[1]
# "block row starts"/"block column starts"
brs = np.cumsum([0]
+ [single_valued(blocks[ibrow, ibcol].shape[0]
for ibcol in range(ncolumns)
if not is_zero(blocks[ibrow, ibcol]))
for ibrow in range(nrows)])
bcs = np.cumsum([0]
+ [single_valued(blocks[ibrow, ibcol].shape[1]
for ibrow in range(nrows)
if not is_zero(blocks[ibrow, ibcol]))
for ibcol in range(ncolumns)])
result = np.zeros((brs[-1], bcs[-1]),
dtype=np.find_common_type(dtypes, []))
for ibcol in range(ncolumns):
for ibrow in range(nrows):
result[brs[ibrow]:brs[ibrow + 1], bcs[ibcol]:bcs[ibcol + 1]] = \
blocks[ibrow, ibcol]
return result
开发者ID:inducer,项目名称:pytential,代码行数:28,代码来源:execution.py
示例5: __imul__
def __imul__(self,other):
'''
Overloaded self-multiplication(*=) operator, which supports the self-multiplication by a scalar.
'''
self[0]*=other
self.dtype=np.find_common_type([self.dtype,np.asarray(other).dtype],[])
return self
开发者ID:waltergu,项目名称:HamiltonianPy,代码行数:7,代码来源:MPO.py
示例6: upcast
def upcast(*args):
"""Returns the nearest supported sparse dtype for the
combination of one or more types.
upcast(t0, t1, ..., tn) -> T where T is a supported dtype
Examples
--------
>>> upcast('int32')
<type 'numpy.int32'>
>>> upcast('bool')
<type 'numpy.int8'>
>>> upcast('int32','float32')
<type 'numpy.float64'>
>>> upcast('bool',complex,float)
<type 'numpy.complex128'>
"""
t = _upcast_memo.get(hash(args))
if t is not None:
return t
upcast = np.find_common_type(args, [])
for t in supported_dtypes:
if np.can_cast(upcast, t):
_upcast_memo[hash(args)] = t
return t
raise TypeError('no supported conversion for types: %s' % args)
开发者ID:87,项目名称:scipy,代码行数:32,代码来源:sputils.py
示例7: common_dtype
def common_dtype (vars):
# {{{
import numpy as np
from pygeode.var import Var
import re
# Can work on PyGeode variables, numpy arrays, lists, tuples, or scalars
dtypes = []
for v in vars:
if isinstance(v, (Var,np.ndarray)):
dtypes.append(v.dtype)
elif isinstance(v, (list,tuple)):
dtypes.append(np.asarray(v).dtype)
else:
dtypes.append(np.asarray([v]).dtype)
# raise Exception ("unrecognized type '%s'"%type(v))
# Unfortunately, find_common_type is not available in older versions of numpy :(
try:
return np.find_common_type(dtypes, [])
except AttributeError:
from warnings import warn
warn ("numpy.find_common_type not supported in this version of numpy. Using an alternative method.")
# Create some empty arrays of the given types, and see what happens
# when we combine them together
arrays = [np.empty(0,dtype=d) for d in dtypes]
return sum(arrays,arrays[0]).dtype
开发者ID:neishm,项目名称:pygeode,代码行数:28,代码来源:tools.py
示例8: common_type
def common_type(arrays):
"""
Returns a type which is common to the input arrays.
All input arrays can be safely cast to the returned dtype without loss of information.
Notes
-----
If list of arrays mixes 'numeric' and 'string' types, the function returns 'object' as common type.
"""
arrays = [np.asarray(a) for a in arrays]
dtypes = [a.dtype for a in arrays]
meta_kinds = [_meta_kind.get(dt.kind, 'other') for dt in dtypes]
# mixing string and numeric => object
if any(mk != meta_kinds[0] for mk in meta_kinds[1:]):
return object
elif meta_kinds[0] == 'numeric':
return np.find_common_type(dtypes, [])
elif meta_kinds[0] == 'str':
need_unicode = any(dt.kind == 'U' for dt in dtypes)
# unicode are coded with 4 bytes
max_size = max(dt.itemsize // 4 if dt.kind == 'U' else dt.itemsize
for dt in dtypes)
return np.dtype(('U' if need_unicode else 'S', max_size))
else:
return object
开发者ID:liam2,项目名称:larray,代码行数:25,代码来源:misc.py
示例9: _get_dtype
def _get_dtype(operators, dtypes=None):
if dtypes is None:
dtypes = []
for obj in operators:
if obj is not None and hasattr(obj, 'dtype'):
dtypes.append(obj.dtype)
return np.find_common_type(dtypes, [])
开发者ID:dyao-vu,项目名称:meta-core,代码行数:7,代码来源:interface.py
示例10: inverse_transform
def inverse_transform(self, X):
"""Convert the data back to the original representation.
Parameters
----------
X : array-like or sparse matrix, shape [n_samples, n_encoded_features]
The transformed data.
Returns
-------
X_tr : array-like, shape [n_samples, n_features]
Inverse transformed array.
"""
check_is_fitted(self, 'categories_')
X = check_array(X, accept_sparse='csr')
n_samples, _ = X.shape
n_features = len(self.categories_)
# validate shape of passed X
msg = ("Shape of the passed X data is not correct. Expected {0} "
"columns, got {1}.")
if X.shape[1] != n_features:
raise ValueError(msg.format(n_features, X.shape[1]))
# create resulting array of appropriate dtype
dt = np.find_common_type([cat.dtype for cat in self.categories_], [])
X_tr = np.empty((n_samples, n_features), dtype=dt)
for i in range(n_features):
labels = X[:, i].astype('int64')
X_tr[:, i] = self.categories_[i][labels]
return X_tr
开发者ID:kjacks21,项目名称:scikit-learn,代码行数:35,代码来源:_encoders.py
示例11: fromoperator
def fromoperator(operator,degfres,layer=0):
'''
Constructor, which converts an operator to an optstr.
Parameters
----------
operator : SOperator/FockOperator
The operator to be converted to an optstr.
degfres : DegFreTree
The degfretree of the system.
layer : int/tuple-of-str, optional
The layer where the converted optstr lives.
Returns
-------
OptStr
The corresponding OptStr.
'''
assert isinstance(operator,SOperator) or isinstance(operator,FockOperator)
layer=degfres.layers[layer] if type(layer) is int else layer
table,sites=degfres.table(degfres.layers[-1]),degfres.labels('S',degfres.layers[-1])
operator=operator if isinstance(operator,SOperator) else JWBosonization(operator,table)
opts=[]
permutation=sorted(range(len(operator.indices)),key=lambda k: table[operator.indices[k]])
for i,k in enumerate(permutation):
index,matrix=operator.indices[k],operator.spins[k]
opts.append(Opt(sites[table[index]],{matrix.tag:[operator.value if i==0 else 1.0,np.asarray(matrix)]}))
return OptStr(opts,np.find_common_type([np.asarray(operator.value).dtype]+[matrix.dtype for matrix in operator.spins],[])).relayer(degfres,layer)
开发者ID:waltergu,项目名称:HamiltonianPy,代码行数:28,代码来源:MPO.py
示例12: _find_common_type
def _find_common_type(types):
"""Find a common data type among the given dtypes."""
# TODO: enable using pandas-specific types
if any(isinstance(t, ExtensionDtype) for t in types):
raise TypeError("Common type discovery is currently only "
"supported for pure numpy dtypes.")
return np.find_common_type(types, [])
开发者ID:arkiv2,项目名称:pandas,代码行数:7,代码来源:cast.py
示例13: _filled
def _filled(self, data, wcs=None, fill=np.nan, view=()):
"""
Replace the exluded elements of *array* with *fill*.
Parameters
----------
data : array-like
Input array
fill : number
Replacement value
view : tuple, optional
Any slicing to apply to the data before flattening
Returns
-------
filled_array : `~numpy.ndarray`
A 1-D ndarray containing the filled output
Notes
-----
This is an internal method used by :class:`SpectralCube`.
Users should use the property :meth:`MaskBase.filled_data`
"""
# Must convert to floating point, but should not change from inherited
# type otherwise
dt = np.find_common_type([data.dtype], [np.float])
sliced_data = data[view].astype(dt)
ex = self.exclude(data=data, wcs=wcs, view=view)
sliced_data[ex] = fill
return sliced_data
开发者ID:eteq,项目名称:spectral-cube,代码行数:30,代码来源:masks.py
示例14: _common_dtype
def _common_dtype(x, y):
dtype = np.find_common_type([x.dtype, y.dtype], [])
if x.dtype != dtype: x = x.astype(dtype)
if y.dtype != dtype: y = y.astype(dtype)
return x, y
开发者ID:laszukdawid,项目名称:PyEMD,代码行数:7,代码来源:EMD_matlab.py
示例15: __init__
def __init__(self, c1, c2, line_offset=0):
"""Create the comparitor instance
@param offset: a tuple containing the spatial offset of the smaller
cube inside the larger cube as (line_offset, sample_offset)
"""
# Set up the cube attributes so cube1 holds the bigger cube
if c1.lines >= c2.lines and c1.samples >= c2.samples and c1.bands == c2.bands:
self.cube1 = c1
self.cube2 = c2
elif c2.lines > c1.lines and c2.samples > c1.samples and c1.bands == c2.bands:
self.cube1 = c2
self.cube2 = c1
else:
raise ValueError("Can't determine which cube is supposed to be the subset of the other: if cubes aren't the same size, one cube must be a spatial subset of the other and both must have the same number of bands")
# common dimensions are from the smaller cube
self.lines = self.cube2.lines
self.bands = self.cube2.bands
self.samples = self.cube2.samples
if line_offset > 0:
self.line_offset = line_offset
else:
self.line_offset = 0
# Parameters common to both cubes
self.bbl = self.cube1.getBadBandList(self.cube2)
# The data type that can hold both types without losing precision
self.dtype = numpy.find_common_type([self.cube1.data_type, self.cube2.data_type], [])
self.histogram=None
self.hashPrintCount=100000
开发者ID:betsegaw,项目名称:peppy,代码行数:34,代码来源:utils.py
示例16: get_columns
def get_columns(row_indices, src_cols, n_rows):
if not len(src_cols):
return np.zeros((n_rows, 0), dtype=source.X.dtype)
n_src_attrs = len(source.domain.attributes)
if all(isinstance(x, int) and 0 <= x < n_src_attrs
for x in src_cols):
return source.X[row_indices, src_cols]
if all(isinstance(x, int) and x < 0 for x in src_cols):
return source.metas[row_indices, [-1 - x for x in src_cols]]
if all(isinstance(x, int) and x >= n_src_attrs for x in src_cols):
return source.Y[row_indices, [x - n_src_attrs for x in
src_cols]]
types = []
if any(isinstance(x, int) and 0 <= x < n_src_attrs
for x in src_cols):
types.append(source.X.dtype)
if any(isinstance(x, int) and x < 0 for x in src_cols):
types.append(source.metas.dtype)
if any(isinstance(x, int) and x >= n_src_attrs for x in src_cols):
types.append(source.Y.dtype)
new_type = np.find_common_type(types, [])
a = np.empty((n_rows, len(src_cols)), dtype=new_type)
for i, col in enumerate(src_cols):
if not isinstance(col, int):
a[:, i] = col(source)
elif col < 0:
a[:, i] = source.metas[row_indices, -1 - col]
elif col < n_src_attrs:
a[:, i] = source.X[row_indices, col]
else:
a[:, i] = source.Y[row_indices, col - n_src_attrs]
return a
开发者ID:amela,项目名称:orange3,代码行数:34,代码来源:table.py
示例17: na_op
def na_op(x, y):
try:
result = expressions.evaluate(
op, str_rep, x, y, raise_on_error=True, **eval_kwargs)
except TypeError:
xrav = x.ravel()
if isinstance(y, (np.ndarray, pd.Series)):
dtype = np.find_common_type([x.dtype, y.dtype], [])
result = np.empty(x.size, dtype=dtype)
yrav = y.ravel()
mask = notnull(xrav) & notnull(yrav)
xrav = xrav[mask]
yrav = yrav[mask]
if np.prod(xrav.shape) and np.prod(yrav.shape):
result[mask] = op(xrav, yrav)
else:
result = np.empty(x.size, dtype=x.dtype)
mask = notnull(xrav)
xrav = xrav[mask]
if np.prod(xrav.shape):
result[mask] = op(xrav, y)
result, changed = com._maybe_upcast_putmask(result, ~mask, np.nan)
result = result.reshape(x.shape)
result = com._fill_zeros(result, x, y, name, fill_zeros)
return result
开发者ID:ChihChengLiang,项目名称:pandas,代码行数:28,代码来源:ops.py
示例18: mean_images
def mean_images(list_spatial_images, list_spatial_masks=None,
param_str_1=MEANIMAGES_DEFAULT, param_str_2=None):
"""
Mean image algorithms.
Parameters
----------
:param list list_spatial_images: input list of *SpatialImage* (grayscale)
:param list list_spatial_masks: optional, input list of *SpatialImages* (binary)
:param str param_str_1: MEANIMAGES_DEFAULT, by default a mean image is computed
:param str param_str_2: optional, optional parameters
Returns
----------
:return: *SpatialImage* output image
Example
-------
>>> from timagetk.util import data_path
>>> from timagetk.components import imread
>>> from timagetk.algorithms import mean_images
>>> img_path = data_path('time_0_cut.inr')
>>> input_image = imread(img_path)
>>> output_image = mean_images([input_image, input_image, input_image])
"""
conds = [True if isinstance(val, SpatialImage) else False
for ind, val in enumerate(list_spatial_images)]
if False not in conds:
dtype_list = [sp_img.dtype for ind, sp_img in enumerate(list_spatial_images)]
comm_type = np.find_common_type(dtype_list, [])
if list_spatial_masks is None:
mask_ptr = None
else:
list_c_vt_spatial_masks = POINTER(_VT_IMAGE) * len(list_spatial_images)
c_input_masks = []
for ind, spatial_mask in enumerate(list_spatial_masks):
vt_input_mask = vt_image(spatial_mask)
c_input_masks.append(vt_input_mask.get_vt_image())
mask_ptr = list_c_vt_spatial_masks( *[pointer(c_input_mask)
for c_input_mask in c_input_masks])
list_c_vt_images = POINTER(_VT_IMAGE) * len(list_spatial_images)
c_input_images = []
for ind, spatial_image in enumerate(list_spatial_images):
vt_input = vt_image(spatial_image)
c_input_images.append(vt_input.get_vt_image())
sp_img_ptr = list_c_vt_images(*[pointer(c_input)
for c_input in c_input_images])
vt_res = new_vt_image(list_spatial_images[0], dtype=comm_type)
rvalue = libvtexec.API_meanImages(sp_img_ptr, mask_ptr,
len(list_spatial_images), vt_res.c_ptr,
param_str_1, param_str_2)
out_sp_img = return_value(vt_res.get_spatial_image(), rvalue)
return out_sp_img
else:
raise TypeError('Input images must be a list of SpatialImage')
return
开发者ID:VirtualPlants,项目名称:timagetk,代码行数:59,代码来源:mean_images.py
示例19: find_best_blas_type
def find_best_blas_type(arrays=(), dtype=None):
"""Find best-matching BLAS/LAPACK type.
Arrays are used to determine the optimal prefix of BLAS routines.
Parameters
----------
arrays : sequence of ndarrays, optional
Arrays can be given to determine optimal prefix of BLAS
routines. If not given, double-precision routines will be
used, otherwise the most generic type in arrays will be used.
dtype : str or dtype, optional
Data-type specifier. Not used if `arrays` is non-empty.
Returns
-------
prefix : str
BLAS/LAPACK prefix character.
dtype : dtype
Inferred Numpy data type.
prefer_fortran : bool
Whether to prefer Fortran order routines over C order.
Examples
--------
>>> import scipy.linalg.blas as bla
>>> a = np.random.rand(10,15)
>>> b = np.asfortranarray(a) # Change the memory layout order
>>> bla.find_best_blas_type((a,))
('d', dtype('float64'), False)
>>> bla.find_best_blas_type((a*1j,))
('z', dtype('complex128'), False)
>>> bla.find_best_blas_type((b,))
('d', dtype('float64'), True)
"""
dtype = _np.dtype(dtype)
prefer_fortran = False
if arrays:
# use the most generic type in arrays
dtypes = [ar.dtype for ar in arrays]
dtype = _np.find_common_type(dtypes, ())
try:
index = dtypes.index(dtype)
except ValueError:
index = 0
if arrays[index].flags['FORTRAN']:
# prefer Fortran for leading array with column major order
prefer_fortran = True
prefix = _type_conv.get(dtype.char, 'd')
if dtype.char == 'G':
# complex256 -> complex128 (i.e., C long double -> C double)
dtype = _np.dtype('D')
elif dtype.char not in 'fdFD':
dtype = _np.dtype('d')
return prefix, dtype, prefer_fortran
开发者ID:Brucechen13,项目名称:scipy,代码行数:59,代码来源:blas.py
示例20: __mul__
def __mul__(self,other):
'''
Overloaded multiplication(*) operator, which supports the multiplication of an optstr with a scalar.
'''
result=copy(self)
result[0]=result[0]*other
result.dtype=np.find_common_type([result.dtype,np.asarray(other).dtype],[])
return result
开发者ID:waltergu,项目名称:HamiltonianPy,代码行数:8,代码来源:MPO.py
注:本文中的numpy.find_common_type函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论