當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.iterable方法代碼示例

本文整理匯總了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)) 
開發者ID:tensorflow,項目名稱:lattice,代碼行數:26,代碼來源:estimators.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:23,代碼來源:stride_tricks.py

示例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 
開發者ID:has2k1,項目名稱:plydata,代碼行數:25,代碼來源:tidy.py

示例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 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:20,代碼來源:stride_tricks.py

示例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 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:27,代碼來源:units.py

示例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 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:24,代碼來源:colorbar.py

示例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) 
開發者ID:PacktPublishing,項目名稱:Mastering-Elasticsearch-7.0,代碼行數:25,代碼來源:patches.py

示例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 
開發者ID:Relph1119,項目名稱:GraphicDesignPatternByPython,代碼行數:19,代碼來源:ticker.py

示例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 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:19,代碼來源:dates.py

示例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() 
開發者ID:holzschu,項目名稱:python3_ios,代碼行數:26,代碼來源:dates.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:31,代碼來源:function_base.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:8,代碼來源:function_base.py

示例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 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:33,代碼來源:function_base.py

示例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 
開發者ID:ryfeus,項目名稱:lambda-packs,代碼行數:17,代碼來源:_numpy_compat.py

示例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 
開發者ID:abhisuri97,項目名稱:auto-alt-text-lambda-api,代碼行數:31,代碼來源:function_base.py


注:本文中的numpy.iterable方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。