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


Python generic.ABCSeries方法代碼示例

本文整理匯總了Python中pandas.core.dtypes.generic.ABCSeries方法的典型用法代碼示例。如果您正苦於以下問題:Python generic.ABCSeries方法的具體用法?Python generic.ABCSeries怎麽用?Python generic.ABCSeries使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pandas.core.dtypes.generic的用法示例。


在下文中一共展示了generic.ABCSeries方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _stack_arrays

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _stack_arrays(tuples, dtype):

    # fml
    def _asarray_compat(x):
        if isinstance(x, ABCSeries):
            return x._values
        else:
            return np.asarray(x)

    def _shape_compat(x):
        if isinstance(x, ABCSeries):
            return len(x),
        else:
            return x.shape

    placement, names, arrays = zip(*tuples)

    first = arrays[0]
    shape = (len(arrays),) + _shape_compat(first)

    stacked = np.empty(shape, dtype=dtype)
    for i, arr in enumerate(arrays):
        stacked[i] = _asarray_compat(arr)

    return stacked, placement 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:27,代碼來源:managers.py

示例2: _create_arithmetic_method

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _create_arithmetic_method(cls, op):
        def arithmetic_method(self, other):
            if isinstance(other, (ABCIndexClass, ABCSeries)):
                return NotImplemented

            elif isinstance(other, cls):
                other = other._ndarray

            with np.errstate(all="ignore"):
                result = op(self._ndarray, other)

            if op is divmod:
                a, b = result
                return cls(a), cls(b)

            return cls(result)

        return compat.set_function_name(arithmetic_method,
                                        "__{}__".format(op.__name__),
                                        cls) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:numpy_.py

示例3: _create_comparison_method

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _create_comparison_method(cls, op):
        """
        Create a comparison method that dispatches to ``cls.values``.
        """
        def wrapper(self, other):
            if isinstance(other, ABCSeries):
                # the arrays defer to Series for comparison ops but the indexes
                #  don't, so we have to unwrap here.
                other = other._values

            result = op(self._data, maybe_unwrap_index(other))
            return result

        wrapper.__doc__ = op.__doc__
        wrapper.__name__ = '__{}__'.format(op.__name__)
        return wrapper 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:datetimelike.py

示例4: _join_i8_wrapper

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _join_i8_wrapper(joinf, dtype, with_indexers=True):
        """
        Create the join wrapper methods.
        """
        from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin

        @staticmethod
        def wrapper(left, right):
            if isinstance(left, (np.ndarray, ABCIndex, ABCSeries,
                                 DatetimeLikeArrayMixin)):
                left = left.view('i8')
            if isinstance(right, (np.ndarray, ABCIndex, ABCSeries,
                                  DatetimeLikeArrayMixin)):
                right = right.view('i8')
            results = joinf(left, right)
            if with_indexers:
                join_index, left_indexer, right_indexer = results
                join_index = join_index.view(dtype)
                return join_index, left_indexer, right_indexer
            return results

        return wrapper 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:datetimelike.py

示例5: wrap_results_for_axis

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def wrap_results_for_axis(self):
        """ return the results for the rows """

        results = self.results
        result = self.obj._constructor(data=results)

        if not isinstance(results[0], ABCSeries):
            try:
                result.index = self.res_columns
            except ValueError:
                pass

        try:
            result.columns = self.res_index
        except ValueError:
            pass

        return result 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:apply.py

示例6: __getitem__

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def __getitem__(self, key):
        if self._selection is not None:
            raise IndexError('Column(s) {selection} already selected'
                             .format(selection=self._selection))

        if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass,
                            np.ndarray)):
            if len(self.obj.columns.intersection(key)) != len(key):
                bad_keys = list(set(key).difference(self.obj.columns))
                raise KeyError("Columns not found: {missing}"
                               .format(missing=str(bad_keys)[1:-1]))
            return self._gotitem(list(key), ndim=2)

        elif not getattr(self, 'as_index', False):
            if key not in self.obj.columns:
                raise KeyError("Column not found: {key}".format(key=key))
            return self._gotitem(key, ndim=2)

        else:
            if key not in self.obj:
                raise KeyError("Column not found: {key}".format(key=key))
            return self._gotitem(key, ndim=1) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:24,代碼來源:base.py

示例7: check_bool_indexer

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def check_bool_indexer(ax, key):
    # boolean indexing, need to check that the data are aligned, otherwise
    # disallowed

    # this function assumes that is_bool_indexer(key) == True

    result = key
    if isinstance(key, ABCSeries) and not key.index.equals(ax):
        result = result.reindex(ax)
        mask = isna(result._values)
        if mask.any():
            raise IndexingError('Unalignable boolean Series provided as '
                                'indexer (index of the boolean Series and of '
                                'the indexed object do not match')
        result = result.astype(bool)._values
    elif is_sparse(result):
        result = result.to_dense()
        result = np.asarray(result, dtype=bool)
    else:
        # is_bool_indexer has already checked for nulls in the case of an
        # object array key, so no check needed here
        result = np.asarray(result, dtype=bool)

    return result 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:26,代碼來源:indexing.py

示例8: _get_rename_function

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _get_rename_function(mapper):
    """
    Returns a function that will map names/labels, dependent if mapper
    is a dict, Series or just a function.
    """
    if isinstance(mapper, (compat.Mapping, ABCSeries)):

        def f(x):
            if x in mapper:
                return mapper[x]
            else:
                return x
    else:
        f = mapper

    return f 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:18,代碼來源:common.py

示例9: _evaluate_with_timedelta_like

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _evaluate_with_timedelta_like(self, other, op):
        if isinstance(other, ABCSeries):
            # GH#19042
            return NotImplemented

        opstr = '__{opname}__'.format(opname=op.__name__).replace('__r', '__')
        # allow division by a timedelta
        if opstr in ['__div__', '__truediv__', '__floordiv__']:
            if _is_convertible_to_td(other):
                other = Timedelta(other)
                if isna(other):
                    raise NotImplementedError(
                        "division by pd.NaT not implemented")

                i8 = self.asi8
                left, right = i8, other.value

                if opstr in ['__floordiv__']:
                    result = op(left, right)
                else:
                    result = op(left, np.float64(right))
                result = self._maybe_mask_results(result, convert='float64')
                return Index(result, name=self.name, copy=False)

        return NotImplemented 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:27,代碼來源:timedeltas.py

示例10: __getitem__

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def __getitem__(self, key):
        if self._selection is not None:
            raise Exception('Column(s) {selection} already selected'
                            .format(selection=self._selection))

        if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass,
                            np.ndarray)):
            if len(self.obj.columns.intersection(key)) != len(key):
                bad_keys = list(set(key).difference(self.obj.columns))
                raise KeyError("Columns not found: {missing}"
                               .format(missing=str(bad_keys)[1:-1]))
            return self._gotitem(list(key), ndim=2)

        elif not getattr(self, 'as_index', False):
            if key not in self.obj.columns:
                raise KeyError("Column not found: {key}".format(key=key))
            return self._gotitem(key, ndim=2)

        else:
            if key not in self.obj:
                raise KeyError("Column not found: {key}".format(key=key))
            return self._gotitem(key, ndim=1) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:24,代碼來源:base.py

示例11: is_bool_indexer

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def is_bool_indexer(key):
    if isinstance(key, (ABCSeries, np.ndarray, ABCIndex)):
        if key.dtype == np.object_:
            key = np.asarray(_values_from_object(key))

            if not lib.is_bool_array(key):
                if isna(key).any():
                    raise ValueError('cannot index with vector containing '
                                     'NA / NaN values')
                return False
            return True
        elif key.dtype == np.bool_:
            return True
    elif isinstance(key, list):
        try:
            arr = np.asarray(key)
            return arr.dtype == np.bool_ and len(arr) == len(key)
        except TypeError:  # pragma: no cover
            return False

    return False 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:23,代碼來源:common.py

示例12: _dt_to_float_ordinal

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _dt_to_float_ordinal(dt):
    """
    Convert :mod:`datetime` to the Gregorian date as UTC float days,
    preserving hours, minutes, seconds and microseconds.  Return value
    is a :func:`float`.
    """
    if (isinstance(dt, (np.ndarray, Index, ABCSeries)
                   ) and is_datetime64_ns_dtype(dt)):
        base = dates.epoch2num(dt.asi8 / 1.0E9)
    else:
        base = dates.date2num(dt)
    return base


# Datetime Conversion 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:17,代碼來源:_converter.py

示例13: _convert_1d

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def _convert_1d(values, unit, axis):
        def try_parse(values):
            try:
                return _dt_to_float_ordinal(tools.to_datetime(values))
            except Exception:
                return values

        if isinstance(values, (datetime, pydt.date)):
            return _dt_to_float_ordinal(values)
        elif isinstance(values, np.datetime64):
            return _dt_to_float_ordinal(tslibs.Timestamp(values))
        elif isinstance(values, pydt.time):
            return dates.date2num(values)
        elif (is_integer(values) or is_float(values)):
            return values
        elif isinstance(values, compat.string_types):
            return try_parse(values)
        elif isinstance(values, (list, tuple, np.ndarray, Index, ABCSeries)):
            if isinstance(values, ABCSeries):
                # https://github.com/matplotlib/matplotlib/issues/11391
                # Series was skipped. Convert to DatetimeIndex to get asi8
                values = Index(values)
            if isinstance(values, Index):
                values = values.values
            if not isinstance(values, np.ndarray):
                values = com.asarray_tuplesafe(values)

            if is_integer_dtype(values) or is_float_dtype(values):
                return values

            try:
                values = tools.to_datetime(values)
                if isinstance(values, Index):
                    values = _dt_to_float_ordinal(values)
                else:
                    values = [_dt_to_float_ordinal(x) for x in values]
            except Exception:
                values = _dt_to_float_ordinal(values)

        return values 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:42,代碼來源:_converter.py

示例14: table

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def table(ax, data, rowLabels=None, colLabels=None, **kwargs):
    """
    Helper function to convert DataFrame and Series to matplotlib.table

    Parameters
    ----------
    ax : Matplotlib axes object
    data : DataFrame or Series
        data for table contents
    kwargs : keywords, optional
        keyword arguments which passed to matplotlib.table.table.
        If `rowLabels` or `colLabels` is not specified, data index or column
        name will be used.

    Returns
    -------
    matplotlib table object
    """
    if isinstance(data, ABCSeries):
        data = data.to_frame()
    elif isinstance(data, ABCDataFrame):
        pass
    else:
        raise ValueError('Input data must be DataFrame or Series')

    if rowLabels is None:
        rowLabels = data.index

    if colLabels is None:
        colLabels = data.columns

    cellText = data.values

    import matplotlib.table
    table = matplotlib.table.table(ax, cellText=cellText,
                                   rowLabels=rowLabels,
                                   colLabels=colLabels, **kwargs)
    return table 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:40,代碼來源:_tools.py

示例15: test_abc_types

# 需要導入模塊: from pandas.core.dtypes import generic [as 別名]
# 或者: from pandas.core.dtypes.generic import ABCSeries [as 別名]
def test_abc_types(self):
        assert isinstance(pd.Index(['a', 'b', 'c']), gt.ABCIndex)
        assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCInt64Index)
        assert isinstance(pd.UInt64Index([1, 2, 3]), gt.ABCUInt64Index)
        assert isinstance(pd.Float64Index([1, 2, 3]), gt.ABCFloat64Index)
        assert isinstance(self.multi_index, gt.ABCMultiIndex)
        assert isinstance(self.datetime_index, gt.ABCDatetimeIndex)
        assert isinstance(self.timedelta_index, gt.ABCTimedeltaIndex)
        assert isinstance(self.period_index, gt.ABCPeriodIndex)
        assert isinstance(self.categorical_df.index, gt.ABCCategoricalIndex)
        assert isinstance(pd.Index(['a', 'b', 'c']), gt.ABCIndexClass)
        assert isinstance(pd.Int64Index([1, 2, 3]), gt.ABCIndexClass)
        assert isinstance(pd.Series([1, 2, 3]), gt.ABCSeries)
        assert isinstance(self.df, gt.ABCDataFrame)
        with catch_warnings(record=True):
            simplefilter('ignore', FutureWarning)
            assert isinstance(self.df.to_panel(), gt.ABCPanel)
        assert isinstance(self.sparse_series, gt.ABCSparseSeries)
        assert isinstance(self.sparse_array, gt.ABCSparseArray)
        assert isinstance(self.sparse_frame, gt.ABCSparseDataFrame)
        assert isinstance(self.categorical, gt.ABCCategorical)
        assert isinstance(pd.Period('2012', freq='A-DEC'), gt.ABCPeriod)

        assert isinstance(pd.DateOffset(), gt.ABCDateOffset)
        assert isinstance(pd.Period('2012', freq='A-DEC').freq,
                          gt.ABCDateOffset)
        assert not isinstance(pd.Period('2012', freq='A-DEC'),
                              gt.ABCDateOffset)
        assert isinstance(pd.Interval(0, 1.5), gt.ABCInterval)
        assert not isinstance(pd.Period('2012', freq='A-DEC'), gt.ABCInterval)

        assert isinstance(self.datetime_array, gt.ABCDatetimeArray)
        assert not isinstance(self.datetime_index, gt.ABCDatetimeArray)

        assert isinstance(self.timedelta_array, gt.ABCTimedeltaArray)
        assert not isinstance(self.timedelta_index, gt.ABCTimedeltaArray) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:38,代碼來源:test_generic.py


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