Python numpy.iterable() Examples
The following are 30 code examples for showing how to use numpy.iterable(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example 1
Project: lattice Author: tensorflow File: estimators.py License: Apache License 2.0 | 6 votes |
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))
Example 2
Project: recruit Author: Frank-qlu File: stride_tricks.py License: Apache License 2.0 | 6 votes |
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
Example 3
Project: plydata Author: has2k1 File: tidy.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example 4
Project: lambda-packs Author: ryfeus File: stride_tricks.py License: MIT License | 6 votes |
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
Example 5
Project: auto-alt-text-lambda-api Author: abhisuri97 File: stride_tricks.py License: MIT License | 6 votes |
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
Example 6
Project: vnpy_crypto Author: birforce File: stride_tricks.py License: MIT License | 6 votes |
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
Example 7
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: stride_tricks.py License: MIT License | 6 votes |
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
Example 8
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: units.py License: MIT License | 6 votes |
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
Example 9
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: colorbar.py License: MIT License | 6 votes |
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
Example 10
Project: Mastering-Elasticsearch-7.0 Author: PacktPublishing File: patches.py License: MIT License | 6 votes |
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)
Example 11
Project: GraphicDesignPatternByPython Author: Relph1119 File: stride_tricks.py License: MIT License | 6 votes |
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
Example 12
Project: GraphicDesignPatternByPython Author: Relph1119 File: ticker.py License: MIT License | 6 votes |
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
Example 13
Project: python3_ios Author: holzschu File: ticker.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example 14
Project: python3_ios Author: holzschu File: dates.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example 15
Project: python3_ios Author: holzschu File: dates.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
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()
Example 16
Project: predictive-maintenance-using-machine-learning Author: awslabs File: stride_tricks.py License: Apache License 2.0 | 6 votes |
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
Example 17
Project: recruit Author: Frank-qlu File: function_base.py License: Apache License 2.0 | 5 votes |
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
Example 18
Project: recruit Author: Frank-qlu File: function_base.py License: Apache License 2.0 | 5 votes |
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
Example 19
Project: recruit Author: Frank-qlu File: function_base.py License: Apache License 2.0 | 5 votes |
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
Example 20
Project: lambda-packs Author: ryfeus File: function_base.py License: MIT License | 5 votes |
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
Example 21
Project: lambda-packs Author: ryfeus File: function_base.py License: MIT License | 5 votes |
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
Example 22
Project: lambda-packs Author: ryfeus File: _numpy_compat.py License: MIT License | 5 votes |
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
Example 23
Project: lambda-packs Author: ryfeus File: function_base.py License: MIT License | 5 votes |
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
Example 24
Project: lambda-packs Author: ryfeus File: function_base.py License: MIT License | 5 votes |
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
Example 25
Project: auto-alt-text-lambda-api Author: abhisuri97 File: function_base.py License: MIT License | 5 votes |
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
Example 26
Project: auto-alt-text-lambda-api Author: abhisuri97 File: function_base.py License: MIT License | 5 votes |
def __init__(self, pyfunc, otypes='', doc=None, excluded=None, cache=False): self.pyfunc = pyfunc self.cache = cache self._ufunc = None # Caching to improve default performance if doc is None: self.__doc__ = pyfunc.__doc__ else: self.__doc__ = doc if isinstance(otypes, str): self.otypes = otypes for char in self.otypes: if char not in typecodes['All']: raise ValueError( "Invalid otype specified: %s" % (char,)) elif iterable(otypes): self.otypes = ''.join([_nx.dtype(x).char for x in otypes]) else: raise ValueError( "Invalid otype specification") # Excluded variable support if excluded is None: excluded = set() self.excluded = set(excluded)
Example 27
Project: vnpy_crypto Author: birforce File: function_base.py License: MIT License | 5 votes |
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
Example 28
Project: vnpy_crypto Author: birforce File: function_base.py License: MIT License | 5 votes |
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
Example 29
Project: vnpy_crypto Author: birforce File: mosaicplot.py License: MIT License | 5 votes |
def _normalize_split(proportion): """ return a list of proportions of the available space given the division if only a number is given, it will assume a split in two pieces """ if not iterable(proportion): if proportion == 0: proportion = array([0.0, 1.0]) elif proportion >= 1: proportion = array([1.0, 0.0]) elif proportion < 0: raise ValueError("proportions should be positive," "given value: {}".format(proportion)) else: proportion = array([proportion, 1.0 - proportion]) proportion = np.asarray(proportion, dtype=float) if np.any(proportion < 0): raise ValueError("proportions should be positive," "given value: {}".format(proportion)) if np.allclose(proportion, 0): raise ValueError("at least one proportion should be " "greater than zero".format(proportion)) # ok, data are meaningful, so go on if len(proportion) < 2: return array([0.0, 1.0]) left = r_[0, cumsum(proportion)] left /= left[-1] * 1.0 return left
Example 30
Project: vnpy_crypto Author: birforce File: indexing.py License: MIT License | 5 votes |
def __iter__(self): raise NotImplementedError('ix is not iterable')