本文整理汇总了Python中numpy.core.multiarray.dtype函数的典型用法代码示例。如果您正苦于以下问题:Python dtype函数的具体用法?Python dtype怎么用?Python dtype使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dtype函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _mean
def _mean(a, axis=None, dtype=None, out=None, keepdims=False):
arr = asanyarray(a)
is_float16_result = False
rcount = _count_reduce_items(arr, axis)
# Make this warning show up first
if rcount == 0:
warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
# Cast bool, unsigned int, and int to float64 by default
if dtype is None:
if issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
dtype = mu.dtype('f8')
elif issubclass(arr.dtype.type, nt.float16):
dtype = mu.dtype('f4')
is_float16_result = True
ret = umr_sum(arr, axis, dtype, out, keepdims)
if isinstance(ret, mu.ndarray):
ret = um.true_divide(
ret, rcount, out=ret, casting='unsafe', subok=False)
if is_float16_result and out is None:
ret = arr.dtype.type(ret)
elif hasattr(ret, 'dtype'):
if is_float16_result:
ret = arr.dtype.type(ret / rcount)
else:
ret = ret.dtype.type(ret / rcount)
else:
ret = ret / rcount
return ret
开发者ID:AlerzDev,项目名称:Brazo-Proyecto-Final,代码行数:32,代码来源:_methods.py
示例2: issubdtype
def issubdtype(arg1, arg2):
"""
Returns True if first argument is a typecode lower/equal in type hierarchy.
Parameters
----------
arg1, arg2 : dtype_like
dtype or string representing a typecode.
Returns
-------
out : bool
See Also
--------
issubsctype, issubclass_
numpy.core.numerictypes : Overview of numpy type hierarchy.
Examples
--------
>>> np.issubdtype('S1', np.string_)
True
>>> np.issubdtype(np.float64, np.float32)
False
"""
if not issubclass_(arg1, generic):
arg1 = dtype(arg1).type
if not issubclass_(arg2, generic):
arg2_orig = arg2
arg2 = dtype(arg2).type
if not isinstance(arg2_orig, dtype):
# weird deprecated behaviour, that tried to infer np.floating from
# float, and similar less obvious things, such as np.generic from
# basestring
mro = arg2.mro()
arg2 = mro[1] if len(mro) > 1 else mro[0]
def type_repr(x):
""" Helper to produce clear error messages """
if not isinstance(x, type):
return repr(x)
elif issubclass(x, generic):
return "np.{}".format(x.__name__)
else:
return x.__name__
# 1.14, 2017-08-01
warnings.warn(
"Conversion of the second argument of issubdtype from `{raw}` "
"to `{abstract}` is deprecated. In future, it will be treated "
"as `{concrete} == np.dtype({raw}).type`.".format(
raw=type_repr(arg2_orig),
abstract=type_repr(arg2),
concrete=type_repr(dtype(arg2_orig).type)
),
FutureWarning, stacklevel=2
)
return issubclass(arg1, arg2)
开发者ID:gabriekq,项目名称:Text-pic-Mendonca,代码行数:60,代码来源:numerictypes.py
示例3: issubdtype
def issubdtype(arg1, arg2):
"""
Returns True if first argument is a typecode lower/equal in type hierarchy.
Parameters
----------
arg1, arg2 : dtype_like
dtype or string representing a typecode.
Returns
-------
out : bool
See Also
--------
issubsctype, issubclass_
numpy.core.numerictypes : Overview of numpy type hierarchy.
Examples
--------
>>> np.issubdtype('S1', str)
True
>>> np.issubdtype(np.float64, np.float32)
False
"""
if issubclass_(arg2, generic):
return issubclass(dtype(arg1).type, arg2)
mro = dtype(arg2).type.mro()
if len(mro) > 1:
val = mro[1]
else:
val = mro[0]
return issubclass(dtype(arg1).type, val)
开发者ID:Alanchi,项目名称:numpy,代码行数:34,代码来源:numerictypes.py
示例4: _add_trailing_padding
def _add_trailing_padding(value, padding):
"""Inject the specified number of padding bytes at the end of a dtype"""
from numpy.core.multiarray import dtype
if value.fields is None:
vfields = {'f0': (value, 0)}
else:
vfields = dict(value.fields)
if value.names and value.names[-1] == '' and \
value[''].char == 'V':
# A trailing padding field is already present
vfields[''] = ('V%d' % (vfields[''][0].itemsize + padding),
vfields[''][1])
value = dtype(vfields)
else:
# Get a free name for the padding field
j = 0
while True:
name = 'pad%d' % j
if name not in vfields:
vfields[name] = ('V%d' % padding, value.itemsize)
break
j += 1
value = dtype(vfields)
if '' not in vfields:
# Strip out the name of the padding field
names = list(value.names)
names[-1] = ''
value.names = tuple(names)
return value
开发者ID:MolecularFlipbook,项目名称:FlipbookApp,代码行数:32,代码来源:_internal.py
示例5: bincount
def bincount(x, weights=None, minlength=None):
if minlength is None:
minlength = 0
else:
if not isinstance(minlength, (int, long)):
raise TypeError("an integer is required")
if minlength <= 0:
raise ValueError("minlength must be positive")
x = array(x)
len_output = minlength
if len(x) > 0:
if x.min() < 0:
raise ValueError("x must not be negative")
len_output = max(len_output, x.max() + 1)
if x.dtype.kind not in 'ui':
raise ValueError("x must be integer")
if weights is None:
output = zeros(len_output, dtype=dtype('int'))
for elem in x:
output[elem] += 1
else:
if len(weights) != len(x):
raise ValueError("x and weights arrays must have the same size")
output = zeros(len_output, dtype=dtype('float'))
for i in range(len(x)):
output[x[i]] += weights[i]
return output
开发者ID:k3331863,项目名称:IR2,代码行数:30,代码来源:bincount.py
示例6: find_common_type
def find_common_type(array_types, scalar_types):
"""
Determine common type following standard coercion rules
Parameters
----------
array_types : sequence
A list of dtype convertible objects representing arrays
scalar_types : sequence
A list of dtype convertible objects representing scalars
Returns
-------
datatype : dtype
The common data-type which is the maximum of the array_types
ignoring the scalar_types unless the maximum of the scalar_types
is of a different kind.
If the kinds is not understood, then None is returned.
See Also
--------
dtype
"""
array_types = [dtype(x) for x in array_types]
scalar_types = [dtype(x) for x in scalar_types]
if len(scalar_types) == 0:
if len(array_types) == 0:
return None
else:
return max(array_types)
if len(array_types) == 0:
return max(scalar_types)
maxa = max(array_types)
maxsc = max(scalar_types)
try:
index_a = _kind_list.index(maxa.kind)
index_sc = _kind_list.index(maxsc.kind)
except ValueError:
return None
if index_sc > index_a:
return _find_common_coerce(maxsc,maxa)
else:
return maxa
开发者ID:AndreI11,项目名称:SatStressGui,代码行数:49,代码来源:numerictypes.py
示例7: _usefields
def _usefields(adict, align):
from .multiarray import dtype
try:
names = adict[-1]
except KeyError:
names = None
if names is None:
names, formats, offsets, titles = _makenames_list(adict, align)
else:
formats = []
offsets = []
titles = []
for name in names:
res = adict[name]
formats.append(res[0])
offsets.append(res[1])
if (len(res) > 2):
titles.append(res[2])
else:
titles.append(None)
return dtype({"names" : names,
"formats" : formats,
"offsets" : offsets,
"titles" : titles}, align)
开发者ID:MolecularFlipbook,项目名称:FlipbookApp,代码行数:25,代码来源:_internal.py
示例8: _makenames_list
def _makenames_list(adict, align):
from .multiarray import dtype
allfields = []
fnames = list(adict.keys())
for fname in fnames:
obj = adict[fname]
n = len(obj)
if not isinstance(obj, tuple) or n not in [2,3]:
raise ValueError("entry not a 2- or 3- tuple")
if (n > 2) and (obj[2] == fname):
continue
num = int(obj[1])
if (num < 0):
raise ValueError("invalid offset.")
format = dtype(obj[0], align=align)
if (format.itemsize == 0):
raise ValueError("all itemsizes must be fixed.")
if (n > 2):
title = obj[2]
else:
title = None
allfields.append((fname, format, num, title))
# sort by offsets
allfields.sort(key=lambda x: x[2])
names = [x[0] for x in allfields]
formats = [x[1] for x in allfields]
offsets = [x[2] for x in allfields]
titles = [x[3] for x in allfields]
return names, formats, offsets, titles
开发者ID:MolecularFlipbook,项目名称:FlipbookApp,代码行数:30,代码来源:_internal.py
示例9: obj2sctype
def obj2sctype(rep, default=None):
"""
Return the scalar dtype or NumPy equivalent of Python type of an object.
Parameters
----------
rep : any
The object of which the type is returned.
default : any, optional
If given, this is returned for objects whose types can not be
determined. If not given, None is returned for those objects.
Returns
-------
dtype : dtype or Python type
The data type of `rep`.
See Also
--------
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype
Examples
--------
>>> np.obj2sctype(np.int32)
<type 'numpy.int32'>
>>> np.obj2sctype(np.array([1., 2.]))
<type 'numpy.float64'>
>>> np.obj2sctype(np.array([1.j]))
<type 'numpy.complex128'>
>>> np.obj2sctype(dict)
<type 'numpy.object_'>
>>> np.obj2sctype('string')
<type 'numpy.string_'>
>>> np.obj2sctype(1, default=list)
<type 'list'>
"""
try:
if issubclass(rep, generic):
return rep
except TypeError:
pass
if isinstance(rep, dtype):
return rep.type
if isinstance(rep, type):
return _python_type(rep)
if isinstance(rep, ndarray):
return rep.dtype.type
try:
res = dtype(rep)
except:
return default
return res.type
开发者ID:Alanchi,项目名称:numpy,代码行数:55,代码来源:numerictypes.py
示例10: _check_field_overlap
def _check_field_overlap(new_fields, old_fields):
""" Perform object memory overlap tests for two data-types (see
_view_is_safe).
This function checks that new fields only access memory contained in old
fields, and that non-object fields are not interpreted as objects and vice
versa.
Parameters
----------
new_fields : list of (data-type, int) pairs
Flat list of (dtype, byte offset) pairs for the new data type, as
returned by _get_all_field_offsets.
old_fields: list of (data-type, int) pairs
Flat list of (dtype, byte offset) pairs for the old data type, as
returned by _get_all_field_offsets.
Raises
------
TypeError
If the new fields are incompatible with the old fields
"""
from .numerictypes import object_
from .multiarray import dtype
#first go byte by byte and check we do not access bytes not in old_fields
new_bytes = set()
for tp, off in new_fields:
new_bytes.update(set(range(off, off+tp.itemsize)))
old_bytes = set()
for tp, off in old_fields:
old_bytes.update(set(range(off, off+tp.itemsize)))
if new_bytes.difference(old_bytes):
raise TypeError("view would access data parent array doesn't own")
#next check that we do not interpret non-Objects as Objects, and vv
obj_offsets = [off for (tp, off) in old_fields if tp.type is object_]
obj_size = dtype(object_).itemsize
for fld_dtype, fld_offset in new_fields:
if fld_dtype.type is object_:
# check we do not create object views where
# there are no objects.
if fld_offset not in obj_offsets:
raise TypeError("cannot view non-Object data as Object type")
else:
# next check we do not create non-object views
# where there are already objects.
# see validate_object_field_overlap for a similar computation.
for obj_offset in obj_offsets:
if (fld_offset < obj_offset + obj_size and
obj_offset < fld_offset + fld_dtype.itemsize):
raise TypeError("cannot view Object as non-Object type")
开发者ID:aeklant,项目名称:numpy,代码行数:54,代码来源:_internal.py
示例11: _set_array_types
def _set_array_types():
ibytes = [1, 2, 4, 8, 16, 32, 64]
fbytes = [2, 4, 8, 10, 12, 16, 32, 64]
for bytes in ibytes:
bits = 8 * bytes
_add_array_type("int", bits)
_add_array_type("uint", bits)
for bytes in fbytes:
bits = 8 * bytes
_add_array_type("float", bits)
_add_array_type("complex", 2 * bits)
_gi = dtype("p")
if _gi.type not in sctypes["int"]:
indx = 0
sz = _gi.itemsize
_lst = sctypes["int"]
while indx < len(_lst) and sz >= _lst[indx](0).itemsize:
indx += 1
sctypes["int"].insert(indx, _gi.type)
sctypes["uint"].insert(indx, dtype("P").type)
开发者ID:kgabor,项目名称:numpy,代码行数:20,代码来源:numerictypes.py
示例12: _bits_of
def _bits_of(obj):
try:
info = next(v for v in _concrete_typeinfo.values() if v.type is obj)
except StopIteration:
if obj in _abstract_types.values():
raise ValueError("Cannot count the bits of an abstract type")
# some third-party type - make a best-guess
return dtype(obj).itemsize * 8
else:
return info.bits
开发者ID:ovillellas,项目名称:numpy,代码行数:11,代码来源:_type_aliases.py
示例13: _set_array_types
def _set_array_types():
ibytes = [1, 2, 4, 8, 16, 32, 64]
fbytes = [2, 4, 8, 10, 12, 16, 32, 64]
for bytes in ibytes:
bits = 8*bytes
_add_array_type('int', bits)
_add_array_type('uint', bits)
for bytes in fbytes:
bits = 8*bytes
_add_array_type('float', bits)
_add_array_type('complex', 2*bits)
_gi = dtype('p')
if _gi.type not in sctypes['int']:
indx = 0
sz = _gi.itemsize
_lst = sctypes['int']
while (indx < len(_lst) and sz >= _lst[indx](0).itemsize):
indx += 1
sctypes['int'].insert(indx, _gi.type)
sctypes['uint'].insert(indx, dtype('P').type)
开发者ID:8848,项目名称:Pymol-script-repo,代码行数:20,代码来源:numerictypes.py
示例14: obj2sctype
def obj2sctype(rep, default=None):
"""
Return the scalar dtype or NumPy equivalent of Python type of an object.
Parameters
----------
rep : any
The object of which the type is returned.
default : any, optional
If given, this is returned for objects whose types can not be
determined. If not given, None is returned for those objects.
Returns
-------
dtype : dtype or Python type
The data type of `rep`.
See Also
--------
sctype2char, issctype, issubsctype, issubdtype, maximum_sctype
Examples
--------
>>> np.obj2sctype(np.int32)
<type 'numpy.int32'>
>>> np.obj2sctype(np.array([1., 2.]))
<type 'numpy.float64'>
>>> np.obj2sctype(np.array([1.j]))
<type 'numpy.complex128'>
>>> np.obj2sctype(dict)
<type 'numpy.object_'>
>>> np.obj2sctype('string')
<type 'numpy.string_'>
>>> np.obj2sctype(1, default=list)
<type 'list'>
"""
# prevent abtract classes being upcast
if isinstance(rep, type) and issubclass(rep, generic):
return rep
# extract dtype from arrays
if isinstance(rep, ndarray):
return rep.dtype.type
# fall back on dtype to convert
try:
res = dtype(rep)
except Exception:
return default
else:
return res.type
开发者ID:gabriekq,项目名称:Text-pic-Mendonca,代码行数:52,代码来源:numerictypes.py
示例15: bitname
def bitname(obj):
"""Return a bit-width name for a given type object"""
bits = _bits_of(obj)
char = dtype(obj).kind
base = _kind_to_stem[char]
if base == 'object':
bits = 0
if bits != 0:
char = "%s%d" % (char, bits // 8)
return base, bits, char
开发者ID:sciunto,项目名称:numpy,代码行数:13,代码来源:_type_aliases.py
示例16: _find_common_coerce
def _find_common_coerce(a, b):
if a > b:
return a
try:
thisind = __test_types.index(a.char)
except ValueError:
return None
while thisind < __len_test_types:
newdtype = dtype(__test_types[thisind])
if newdtype >= b and newdtype >= a:
return newdtype
thisind += 1
return None
开发者ID:8848,项目名称:Pymol-script-repo,代码行数:13,代码来源:numerictypes.py
示例17: _can_coerce_all
def _can_coerce_all(dtypelist, start=0):
N = len(dtypelist)
if N == 0:
return None
if N == 1:
return dtypelist[0]
thisind = start
while thisind < __len_test_types:
newdtype = dtype(__test_types[thisind])
numcoerce = len([x for x in dtypelist if newdtype >= x])
if numcoerce == N:
return newdtype
thisind += 1
return None
开发者ID:Alanchi,项目名称:numpy,代码行数:14,代码来源:numerictypes.py
示例18: sctype2char
def sctype2char(sctype):
"""
Return the string representation of a scalar dtype.
Parameters
----------
sctype : scalar dtype or object
If a scalar dtype, the corresponding string character is
returned. If an object, `sctype2char` tries to infer its scalar type
and then return the corresponding string character.
Returns
-------
typechar : str
The string character corresponding to the scalar type.
Raises
------
ValueError
If `sctype` is an object for which the type can not be inferred.
See Also
--------
obj2sctype, issctype, issubsctype, mintypecode
Examples
--------
>>> for sctype in [np.int32, float, complex, np.string_, np.ndarray]:
... print(np.sctype2char(sctype))
l
d
D
S
O
>>> x = np.array([1., 2-1.j])
>>> np.sctype2char(x)
'D'
>>> np.sctype2char(list)
'O'
"""
sctype = obj2sctype(sctype)
if sctype is None:
raise ValueError("unrecognized type")
if sctype not in _concrete_types:
# for compatibility
raise KeyError(sctype)
return dtype(sctype).char
开发者ID:gabriekq,项目名称:Text-pic-Mendonca,代码行数:49,代码来源:numerictypes.py
示例19: maximum_sctype
def maximum_sctype(t):
"""
Return the scalar type of highest precision of the same kind as the input.
Parameters
----------
t : dtype or dtype specifier
The input data type. This can be a `dtype` object or an object that
is convertible to a `dtype`.
Returns
-------
out : dtype
The highest precision data type of the same kind (`dtype.kind`) as `t`.
See Also
--------
obj2sctype, mintypecode, sctype2char
dtype
Examples
--------
>>> np.maximum_sctype(int)
<type 'numpy.int64'>
>>> np.maximum_sctype(np.uint8)
<type 'numpy.uint64'>
>>> np.maximum_sctype(complex)
<type 'numpy.complex192'>
>>> np.maximum_sctype(str)
<type 'numpy.string_'>
>>> np.maximum_sctype('i2')
<type 'numpy.int64'>
>>> np.maximum_sctype('f4')
<type 'numpy.float96'>
"""
g = obj2sctype(t)
if g is None:
return t
t = g
bits = _bits_of(t)
base = _kind_to_stem[dtype(t).kind]
if base in sctypes:
return sctypes[base][-1]
else:
return t
开发者ID:sciunto,项目名称:numpy,代码行数:48,代码来源:numerictypes.py
示例20: _var
def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
arr = asanyarray(a)
rcount = _count_reduce_items(arr, axis)
# Make this warning show up on top.
if ddof >= rcount:
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
stacklevel=2)
# Cast bool, unsigned int, and int to float64 by default
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
dtype = mu.dtype('f8')
# Compute the mean.
# Note that if dtype is not of inexact type then arraymean will
# not be either.
arrmean = umr_sum(arr, axis, dtype, keepdims=True)
if isinstance(arrmean, mu.ndarray):
arrmean = um.true_divide(
arrmean, rcount, out=arrmean, casting='unsafe', subok=False)
else:
arrmean = arrmean.dtype.type(arrmean / rcount)
# Compute sum of squared deviations from mean
# Note that x may not be inexact and that we need it to be an array,
# not a scalar.
x = asanyarray(arr - arrmean)
if issubclass(arr.dtype.type, (nt.floating, nt.integer)):
x = um.multiply(x, x, out=x)
else:
x = um.multiply(x, um.conjugate(x), out=x).real
ret = umr_sum(x, axis, dtype, out, keepdims)
# Compute degrees of freedom and make sure it is not negative.
rcount = max([rcount - ddof, 0])
# divide by degrees of freedom
if isinstance(ret, mu.ndarray):
ret = um.true_divide(
ret, rcount, out=ret, casting='unsafe', subok=False)
elif hasattr(ret, 'dtype'):
ret = ret.dtype.type(ret / rcount)
else:
ret = ret / rcount
return ret
开发者ID:gerritholl,项目名称:numpy,代码行数:47,代码来源:_methods.py
注:本文中的numpy.core.multiarray.dtype函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论