本文整理汇总了Python中numpy.iterable方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.iterable方法的具体用法?Python numpy.iterable怎么用?Python numpy.iterable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.iterable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _verify_config
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def _verify_config(model_config, feature_columns):
"""Verifies that the config is setup correctly and ready for model_fn."""
if feature_columns:
feature_configs = [
model_config.feature_config_by_name(feature_column.name)
for feature_column in feature_columns
]
else:
feature_configs = model_config.feature_configs or []
for feature_config in feature_configs:
if not feature_config.num_buckets:
if (not np.iterable(feature_config.pwl_calibration_input_keypoints) or
any(not isinstance(x, float)
for x in feature_config.pwl_calibration_input_keypoints)):
raise ValueError(
'Input keypoints are invalid for feature {}: {}'.format(
feature_config.name,
feature_config.pwl_calibration_input_keypoints))
if (not np.iterable(model_config.output_initialization) or any(
not isinstance(x, float) for x in model_config.output_initialization)):
raise ValueError('Output initilization is invalid: {}'.format(
model_config.output_initialization))
示例2: _broadcast_to
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def _broadcast_to(array, shape, subok, readonly):
shape = tuple(shape) if np.iterable(shape) else (shape,)
array = np.array(array, copy=False, subok=subok)
if not shape and array.shape:
raise ValueError('cannot broadcast a non-scalar to a scalar array')
if any(size < 0 for size in shape):
raise ValueError('all elements of broadcast shape must be non-'
'negative')
needs_writeable = not readonly and array.flags.writeable
extras = ['reduce_ok'] if needs_writeable else []
op_flag = 'readwrite' if needs_writeable else 'readonly'
it = np.nditer(
(array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
op_flags=[op_flag], itershape=shape, order='C')
with it:
# never really has writebackifcopy semantics
broadcast = it.itviews[0]
result = _maybe_view_as_subclass(array, broadcast)
if needs_writeable and not result.flags.writeable:
result.flags.writeable = True
return result
示例3: spread
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def spread(verb):
key = verb.key
value = verb.value
if isinstance(key, str) or not np.iterable(key):
key = [key]
if isinstance(value, str) or not np.iterable(key):
value = [value]
key_value = pd.Index(list(chain(key, value))).drop_duplicates()
index = verb.data.columns.difference(key_value).tolist()
data = pd.pivot_table(
verb.data,
values=value,
index=index,
columns=key,
aggfunc=identity,
)
clean_indices(data, verb.sep, inplace=True)
data = data.infer_objects()
return data
示例4: _broadcast_to
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def _broadcast_to(array, shape, subok, readonly):
shape = tuple(shape) if np.iterable(shape) else (shape,)
array = np.array(array, copy=False, subok=subok)
if not shape and array.shape:
raise ValueError('cannot broadcast a non-scalar to a scalar array')
if any(size < 0 for size in shape):
raise ValueError('all elements of broadcast shape must be non-'
'negative')
needs_writeable = not readonly and array.flags.writeable
extras = ['reduce_ok'] if needs_writeable else []
op_flag = 'readwrite' if needs_writeable else 'readonly'
broadcast = np.nditer(
(array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
op_flags=[op_flag], itershape=shape, order='C').itviews[0]
result = _maybe_view_as_subclass(array, broadcast)
if needs_writeable and not result.flags.writeable:
result.flags.writeable = True
return result
示例5: get_converter
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def get_converter(self, x):
"""Get the converter interface instance for *x*, or None."""
if hasattr(x, "values"):
x = x.values # Unpack pandas Series and DataFrames.
if isinstance(x, np.ndarray):
# In case x in a masked array, access the underlying data (only its
# type matters). If x is a regular ndarray, getdata() just returns
# the array itself.
x = np.ma.getdata(x).ravel()
# If there are no elements in x, infer the units from its dtype
if not x.size:
return self.get_converter(np.array([0], dtype=x.dtype))
try: # Look up in the cache.
return self[type(x)]
except KeyError:
try: # If cache lookup fails, look up based on first element...
first = cbook.safe_first_element(x)
except (TypeError, StopIteration):
pass
else:
# ... and avoid infinite recursion for pathological iterables
# where indexing returns instances of the same iterable class.
if type(first) is not type(x):
return self.get_converter(first)
return None
示例6: set_ticks
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def set_ticks(self, ticks, update_ticks=True):
"""
Set tick locations.
Parameters
----------
ticks : {None, sequence, :class:`~matplotlib.ticker.Locator` instance}
If None, a default Locator will be used.
update_ticks : {True, False}, optional
If True, tick locations are updated immediately. If False,
use :meth:`update_ticks` to manually update the ticks.
"""
if np.iterable(ticks):
self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
else:
self.locator = ticks
if update_ticks:
self.update_ticks()
self.stale = True
示例7: draw
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def draw(self, renderer):
if not self.get_visible():
return
# FancyArrowPatch has traditionally forced the capstyle and joinstyle.
with cbook._setattr_cm(self, _capstyle='round', _joinstyle='round'), \
self._bind_draw_path_function(renderer) as draw_path:
# FIXME : dpi_cor is for the dpi-dependency of the linewidth. There
# could be room for improvement.
self.set_dpi_cor(renderer.points_to_pixels(1.))
path, fillable = self.get_path_in_displaycoord()
if not np.iterable(fillable):
path = [path]
fillable = [fillable]
affine = transforms.IdentityTransform()
for p, f in zip(path, fillable):
draw_path(
p, affine,
self._facecolor if f and self._facecolor[3] else None)
示例8: _validate_steps
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def _validate_steps(steps):
if not np.iterable(steps):
raise ValueError('steps argument must be a sequence of numbers '
'from 1 to 10')
steps = np.asarray(steps)
if np.any(np.diff(steps) <= 0):
raise ValueError('steps argument must be uniformly increasing')
if steps[-1] > 10 or steps[0] < 1:
warnings.warn('Steps argument should be a sequence of numbers\n'
'increasing from 1 to 10, inclusive. Behavior with\n'
'values outside this range is undefined, and will\n'
'raise a ValueError in future versions of mpl.')
if steps[0] != 1:
steps = np.hstack((1, steps))
if steps[-1] != 10:
steps = np.hstack((steps, 10))
return steps
示例9: julian2num
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def julian2num(j):
"""
Convert a Julian date (or sequence) to a Matplotlib date (or sequence).
Parameters
----------
j : float or sequence of floats
Julian date(s)
Returns
-------
float or sequence of floats
Matplotlib date(s)
"""
if cbook.iterable(j):
j = np.asarray(j)
return j - JULIAN_OFFSET
示例10: num2timedelta
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def num2timedelta(x):
"""
Convert number of days to a `~datetime.timedelta` object.
If *x* is a sequence, a sequence of `~datetime.timedelta` objects will
be returned.
Parameters
----------
x : float, sequence of floats
Number of days. The fraction part represents hours, minutes, seconds.
Returns
-------
`datetime.timedelta` or list[`datetime.timedelta`]
"""
if not cbook.iterable(x):
return _ordinalf_to_timedelta(x)
else:
x = np.asarray(x)
if not x.size:
return x
return _ordinalf_to_timedelta_np_vectorized(x).tolist()
示例11: iterable
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def iterable(y):
"""
Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : bool
Return ``True`` if the object has an iterator method or is a
sequence and ``False`` otherwise.
Examples
--------
>>> np.iterable([1, 2, 3])
True
>>> np.iterable(2)
False
"""
try:
iter(y)
except TypeError:
return False
return True
示例12: _piecewise_dispatcher
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def _piecewise_dispatcher(x, condlist, funclist, *args, **kw):
yield x
# support the undocumented behavior of allowing scalars
if np.iterable(condlist):
for c in condlist:
yield c
示例13: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def __init__(self, pyfunc, otypes=None, doc=None, excluded=None,
cache=False, signature=None):
self.pyfunc = pyfunc
self.cache = cache
self.signature = signature
self._ufunc = None # Caching to improve default performance
if doc is None:
self.__doc__ = pyfunc.__doc__
else:
self.__doc__ = doc
if isinstance(otypes, str):
for char in otypes:
if char not in typecodes['All']:
raise ValueError("Invalid otype specified: %s" % (char,))
elif iterable(otypes):
otypes = ''.join([_nx.dtype(x).char for x in otypes])
elif otypes is not None:
raise ValueError("Invalid otype specification")
self.otypes = otypes
# Excluded variable support
if excluded is None:
excluded = set()
self.excluded = set(excluded)
if signature is not None:
self._in_and_out_core_dims = _parse_gufunc_signature(signature)
else:
self._in_and_out_core_dims = None
示例14: _broadcast_to
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def _broadcast_to(array, shape, subok, readonly):
shape = tuple(shape) if np.iterable(shape) else (shape,)
array = np.array(array, copy=False, subok=subok)
if not shape and array.shape:
raise ValueError('cannot broadcast a non-scalar to a scalar array')
if any(size < 0 for size in shape):
raise ValueError('all elements of broadcast shape must be non-'
'negative')
broadcast = np.nditer(
(array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'],
op_flags=['readonly'], itershape=shape, order='C').itviews[0]
result = _maybe_view_as_subclass(array, broadcast)
if not readonly and array.flags.writeable:
result.flags.writeable = True
return result
示例15: iterable
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import iterable [as 别名]
def iterable(y):
"""
Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : {0, 1}
Return 1 if the object has an iterator method or is a sequence,
and 0 otherwise.
Examples
--------
>>> np.iterable([1, 2, 3])
1
>>> np.iterable(2)
0
"""
try:
iter(y)
except:
return 0
return 1