Python numpy.iterable() Examples

The following are 30 code examples of numpy.iterable(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: stride_tricks.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: stride_tricks.py    From recruit with Apache License 2.0 6 votes vote down vote up
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
Source File: stride_tricks.py    From lambda-packs with MIT License 6 votes vote down vote up
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 #4
Source File: tidy.py    From plydata with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #5
Source File: estimators.py    From lattice with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: stride_tricks.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
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
Source File: stride_tricks.py    From vnpy_crypto with MIT License 6 votes vote down vote up
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 #8
Source File: stride_tricks.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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 #9
Source File: units.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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 #10
Source File: colorbar.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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 #11
Source File: patches.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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 #12
Source File: stride_tricks.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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 #13
Source File: ticker.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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
Source File: ticker.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #15
Source File: dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #16
Source File: dates.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #17
Source File: function_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
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
Source File: envi.py    From spectral with MIT License 5 votes vote down vote up
def _has_frame_offset(params):
    '''
    Returns True if header params indicate non-zero frame offsets.

    Arguments:

        `params` (dict):

            Dictionary of header parameters assocaited with hdr file.

    Returns:

        bool

    This function returns True when either "major frame offsets" or
    "minor frame offsets" is specified and contains a non-zero value.
    '''
    for param in ['major frame offsets', 'minor frame offsets']:
        if param in params:
            val = params[param]
            if np.iterable(val):
                offsets = [int(x) for x in val]
            else:
                offsets = [int(val)] * 2
            if not np.all(np.equal(offsets, 0)):
                return True
    return False 
Example #19
Source File: _broadcast.py    From sdeint with GNU General Public License v3.0 5 votes vote down vote up
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 #20
Source File: function_base.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
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 #21
Source File: function_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
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 #22
Source File: function_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
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 #23
Source File: function_base.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
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
Source File: function_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
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
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def set_ybound(self, lower=None, upper=None):
        """
        Set the lower and upper numerical bounds of the y-axis.

        This method will honor axes inversion regardless of parameter order.
        It will not change the autoscaling setting (``Axes._autoscaleYon``).

        Parameters
        ----------
        lower, upper : float or None
            The lower and upper bounds. If *None*, the respective axis bound
            is not modified.

        See Also
        --------
        get_ybound
        get_ylim, set_ylim
        invert_yaxis, yaxis_inverted
        """
        if upper is None and np.iterable(lower):
            lower, upper = lower

        old_lower, old_upper = self.get_ybound()

        if lower is None:
            lower = old_lower
        if upper is None:
            upper = old_upper

        if self.yaxis_inverted():
            if lower < upper:
                self.set_ylim(upper, lower, auto=None)
            else:
                self.set_ylim(lower, upper, auto=None)
        else:
            if lower < upper:
                self.set_ylim(lower, upper, auto=None)
            else:
                self.set_ylim(upper, lower, auto=None) 
Example #26
Source File: _base.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def set_xbound(self, lower=None, upper=None):
        """
        Set the lower and upper numerical bounds of the x-axis.

        This method will honor axes inversion regardless of parameter order.
        It will not change the autoscaling setting (``Axes._autoscaleXon``).

        Parameters
        ----------
        lower, upper : float or None
            The lower and upper bounds. If *None*, the respective axis bound
            is not modified.

        See Also
        --------
        get_xbound
        get_xlim, set_xlim
        invert_xaxis, xaxis_inverted
        """
        if upper is None and np.iterable(lower):
            lower, upper = lower

        old_lower, old_upper = self.get_xbound()

        if lower is None:
            lower = old_lower
        if upper is None:
            upper = old_upper

        if self.xaxis_inverted():
            if lower < upper:
                self.set_xlim(upper, lower, auto=None)
            else:
                self.set_xlim(lower, upper, auto=None)
        else:
            if lower < upper:
                self.set_xlim(lower, upper, auto=None)
            else:
                self.set_xlim(upper, lower, auto=None) 
Example #27
Source File: __init__.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def is_scalar_or_string(val):
    """Return whether the given object is a scalar or string like."""
    return isinstance(val, str) or not np.iterable(val) 
Example #28
Source File: ticker.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _validate_steps(steps):
        if not np.iterable(steps):
            raise ValueError('steps argument must be an increasing sequence '
                             'of numbers between 1 and 10 inclusive')
        steps = np.asarray(steps)
        if np.any(np.diff(steps) <= 0) or steps[-1] > 10 or steps[0] < 1:
            raise ValueError('steps argument must be an increasing sequence '
                             'of numbers between 1 and 10 inclusive')
        if steps[0] != 1:
            steps = np.hstack((1, steps))
        if steps[-1] != 10:
            steps = np.hstack((steps, 10))
        return steps 
Example #29
Source File: patches.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def get_path(self):
        """
        Return the path of the arrow in the data coordinates. Use
        get_path_in_displaycoord() method to retrieve the arrow path
        in display coordinates.
        """
        _path, fillable = self.get_path_in_displaycoord()

        if np.iterable(fillable):
            _path = concatenate_paths(_path)

        return self.get_transform().inverted().transform_path(_path) 
Example #30
Source File: test_units.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __getitem__(self, item):
        if iterable(self.magnitude):
            return Quantity(self.magnitude[item], self.units)
        else:
            return Quantity(self.magnitude, self.units)