本文整理汇总了Python中numpy.core.multiarray.dtype函数的典型用法代码示例。如果您正苦于以下问题:Python dtype函数的具体用法?Python dtype怎么用?Python dtype使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dtype函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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)
示例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
示例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
示例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
示例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)
示例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
示例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
示例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")
示例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)
示例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
示例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)
示例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
示例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