Python pandas.compat.signature() Examples

The following are 20 code examples of pandas.compat.signature(). 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 pandas.compat , or try the search function .
Example #1
Source File: _decorators.py    From recruit with Apache License 2.0 5 votes vote down vote up
def make_signature(func):
    """
    Returns a tuple containing the paramenter list with defaults
    and parameter list.

    Examples
    --------
    >>> def f(a, b, c=2):
    >>>     return a * b * c
    >>> print(make_signature(f))
    (['a', 'b', 'c=2'], ['a', 'b', 'c'])
    """

    spec = signature(func)
    if spec.defaults is None:
        n_wo_defaults = len(spec.args)
        defaults = ('',) * n_wo_defaults
    else:
        n_wo_defaults = len(spec.args) - len(spec.defaults)
        defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
    args = []
    for var, default in zip(spec.args, defaults):
        args.append(var if default == '' else var + '=' + repr(default))
    if spec.varargs:
        args.append('*' + spec.varargs)
    if spec.keywords:
        args.append('**' + spec.keywords)
    return args, spec.args 
Example #2
Source File: test_panel.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True,
                       skipna_alternative=None):
        if obj is None:
            obj = self.panel

            # # set some NAs
            # obj.loc[5:10] = np.nan
            # obj.loc[15:20, -2:] = np.nan

        f = getattr(obj, name)

        if has_skipna:

            skipna_wrapper = tm._make_skipna_wrapper(alternative,
                                                     skipna_alternative)

            def wrapper(x):
                return alternative(np.asarray(x))

            for i in range(obj.ndim):
                result = f(axis=i, skipna=False)
                assert_frame_equal(result, obj.apply(wrapper, axis=i))
        else:
            skipna_wrapper = alternative
            wrapper = alternative

        for i in range(obj.ndim):
            result = f(axis=i)
            if name in ['sum', 'prod']:
                assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))

        pytest.raises(Exception, f, axis=obj.ndim)

        # Unimplemented numeric_only parameter.
        if 'numeric_only' in signature(f).args:
            tm.assert_raises_regex(NotImplementedError, name, f,
                                   numeric_only=True) 
Example #3
Source File: test_panel.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True,
                       skipna_alternative=None):
        if obj is None:
            obj = self.panel

            # # set some NAs
            # obj.loc[5:10] = np.nan
            # obj.loc[15:20, -2:] = np.nan

        f = getattr(obj, name)

        if has_skipna:

            skipna_wrapper = tm._make_skipna_wrapper(alternative,
                                                     skipna_alternative)

            def wrapper(x):
                return alternative(np.asarray(x))

            for i in range(obj.ndim):
                result = f(axis=i, skipna=False)
                assert_frame_equal(result, obj.apply(wrapper, axis=i))
        else:
            skipna_wrapper = alternative
            wrapper = alternative

        for i in range(obj.ndim):
            result = f(axis=i)
            if name in ['sum', 'prod']:
                assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))

        pytest.raises(Exception, f, axis=obj.ndim)

        # Unimplemented numeric_only parameter.
        if 'numeric_only' in signature(f).args:
            tm.assert_raises_regex(NotImplementedError, name, f,
                                   numeric_only=True) 
Example #4
Source File: test_panel.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True,
                       skipna_alternative=None):
        if obj is None:
            obj = self.panel

            # # set some NAs
            # obj.loc[5:10] = np.nan
            # obj.loc[15:20, -2:] = np.nan

        f = getattr(obj, name)

        if has_skipna:

            skipna_wrapper = tm._make_skipna_wrapper(alternative,
                                                     skipna_alternative)

            def wrapper(x):
                return alternative(np.asarray(x))

            for i in range(obj.ndim):
                result = f(axis=i, skipna=False)
                assert_frame_equal(result, obj.apply(wrapper, axis=i))
        else:
            skipna_wrapper = alternative
            wrapper = alternative

        for i in range(obj.ndim):
            result = f(axis=i)
            if name in ['sum', 'prod']:
                assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))

        pytest.raises(Exception, f, axis=obj.ndim)

        # Unimplemented numeric_only parameter.
        if 'numeric_only' in signature(f).args:
            with pytest.raises(NotImplementedError, match=name):
                f(numeric_only=True) 
Example #5
Source File: _decorators.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def make_signature(func):
    """
    Returns a string repr of the arg list of a func call, with any defaults.

    Examples
    --------
    >>> def f(a,b,c=2) :
    >>>     return a*b*c
    >>> print(_make_signature(f))
    a,b,c=2
    """

    spec = signature(func)
    if spec.defaults is None:
        n_wo_defaults = len(spec.args)
        defaults = ('',) * n_wo_defaults
    else:
        n_wo_defaults = len(spec.args) - len(spec.defaults)
        defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
    args = []
    for i, (var, default) in enumerate(zip(spec.args, defaults)):
        args.append(var if default == '' else var + '=' + repr(default))
    if spec.varargs:
        args.append('*' + spec.varargs)
    if spec.keywords:
        args.append('**' + spec.keywords)
    return args, spec.args 
Example #6
Source File: _decorators.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def make_signature(func):
    """
    Returns a string repr of the arg list of a func call, with any defaults.

    Examples
    --------
    >>> def f(a,b,c=2) :
    >>>     return a*b*c
    >>> print(_make_signature(f))
    a,b,c=2
    """

    spec = signature(func)
    if spec.defaults is None:
        n_wo_defaults = len(spec.args)
        defaults = ('',) * n_wo_defaults
    else:
        n_wo_defaults = len(spec.args) - len(spec.defaults)
        defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
    args = []
    for i, (var, default) in enumerate(zip(spec.args, defaults)):
        args.append(var if default == '' else var + '=' + repr(default))
    if spec.varargs:
        args.append('*' + spec.varargs)
    if spec.keywords:
        args.append('**' + spec.keywords)
    return args, spec.args 
Example #7
Source File: apply.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def get_result(self):
        """ compute the results """

        # all empty
        if len(self.columns) == 0 and len(self.index) == 0:
            return self.apply_empty_result()

        # string dispatch
        if isinstance(self.f, compat.string_types):
            # Support for `frame.transform('method')`
            # Some methods (shift, etc.) require the axis argument, others
            # don't, so inspect and insert if nescessary.
            func = getattr(self.obj, self.f)
            sig = compat.signature(func)
            if 'axis' in sig.args:
                self.kwds['axis'] = self.axis
            return func(*self.args, **self.kwds)

        # ufunc
        elif isinstance(self.f, np.ufunc):
            with np.errstate(all='ignore'):
                results = self.f(self.values)
            return self.obj._constructor(data=results, index=self.index,
                                         columns=self.columns, copy=False)

        # broadcasting
        if self.result_type == 'broadcast':
            return self.apply_broadcast()

        # one axis empty
        elif not all(self.obj.shape):
            return self.apply_empty_result()

        # raw
        elif self.raw and not self.obj._is_mixed_type:
            return self.apply_raw()

        return self.apply_standard() 
Example #8
Source File: test_panel.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True,
                       skipna_alternative=None):
        if obj is None:
            obj = self.panel

            # # set some NAs
            # obj.loc[5:10] = np.nan
            # obj.loc[15:20, -2:] = np.nan

        f = getattr(obj, name)

        if has_skipna:

            skipna_wrapper = tm._make_skipna_wrapper(alternative,
                                                     skipna_alternative)

            def wrapper(x):
                return alternative(np.asarray(x))

            for i in range(obj.ndim):
                result = f(axis=i, skipna=False)
                assert_frame_equal(result, obj.apply(wrapper, axis=i))
        else:
            skipna_wrapper = alternative
            wrapper = alternative

        for i in range(obj.ndim):
            result = f(axis=i)
            if name in ['sum', 'prod']:
                assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))

        pytest.raises(Exception, f, axis=obj.ndim)

        # Unimplemented numeric_only parameter.
        if 'numeric_only' in signature(f).args:
            with pytest.raises(NotImplementedError, match=name):
                f(numeric_only=True) 
Example #9
Source File: test_panel.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True,
                       skipna_alternative=None):
        if obj is None:
            obj = self.panel

            # # set some NAs
            # obj.loc[5:10] = np.nan
            # obj.loc[15:20, -2:] = np.nan

        f = getattr(obj, name)

        if has_skipna:

            skipna_wrapper = tm._make_skipna_wrapper(alternative,
                                                     skipna_alternative)

            def wrapper(x):
                return alternative(np.asarray(x))

            for i in range(obj.ndim):
                result = f(axis=i, skipna=False)
                assert_frame_equal(result, obj.apply(wrapper, axis=i))
        else:
            skipna_wrapper = alternative
            wrapper = alternative

        for i in range(obj.ndim):
            result = f(axis=i)
            if name in ['sum', 'prod']:
                assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))

        pytest.raises(Exception, f, axis=obj.ndim)

        # Unimplemented numeric_only parameter.
        if 'numeric_only' in signature(f).args:
            with pytest.raises(NotImplementedError, match=name):
                f(numeric_only=True) 
Example #10
Source File: _decorators.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def make_signature(func):
    """
    Returns a tuple containing the paramenter list with defaults
    and parameter list.

    Examples
    --------
    >>> def f(a, b, c=2):
    >>>     return a * b * c
    >>> print(make_signature(f))
    (['a', 'b', 'c=2'], ['a', 'b', 'c'])
    """

    spec = signature(func)
    if spec.defaults is None:
        n_wo_defaults = len(spec.args)
        defaults = ('',) * n_wo_defaults
    else:
        n_wo_defaults = len(spec.args) - len(spec.defaults)
        defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
    args = []
    for var, default in zip(spec.args, defaults):
        args.append(var if default == '' else var + '=' + repr(default))
    if spec.varargs:
        args.append('*' + spec.varargs)
    if spec.keywords:
        args.append('**' + spec.keywords)
    return args, spec.args 
Example #11
Source File: _decorators.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_signature(func):
    """
    Returns a string repr of the arg list of a func call, with any defaults.

    Examples
    --------
    >>> def f(a,b,c=2) :
    >>>     return a*b*c
    >>> print(_make_signature(f))
    a,b,c=2
    """

    spec = signature(func)
    if spec.defaults is None:
        n_wo_defaults = len(spec.args)
        defaults = ('',) * n_wo_defaults
    else:
        n_wo_defaults = len(spec.args) - len(spec.defaults)
        defaults = ('',) * n_wo_defaults + tuple(spec.defaults)
    args = []
    for i, (var, default) in enumerate(zip(spec.args, defaults)):
        args.append(var if default == '' else var + '=' + repr(default))
    if spec.varargs:
        args.append('*' + spec.varargs)
    if spec.keywords:
        args.append('**' + spec.keywords)
    return args, spec.args 
Example #12
Source File: test_panel.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True):
        if obj is None:
            obj = self.panel

            # # set some NAs
            # obj.loc[5:10] = np.nan
            # obj.loc[15:20, -2:] = np.nan

        f = getattr(obj, name)

        if has_skipna:

            def skipna_wrapper(x):
                nona = remove_na_arraylike(x)
                if len(nona) == 0:
                    return np.nan
                return alternative(nona)

            def wrapper(x):
                return alternative(np.asarray(x))

            for i in range(obj.ndim):
                result = f(axis=i, skipna=False)
                assert_frame_equal(result, obj.apply(wrapper, axis=i))
        else:
            skipna_wrapper = alternative
            wrapper = alternative

        for i in range(obj.ndim):
            result = f(axis=i)
            if name in ['sum', 'prod']:
                assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))

        pytest.raises(Exception, f, axis=obj.ndim)

        # Unimplemented numeric_only parameter.
        if 'numeric_only' in signature(f).args:
            tm.assert_raises_regex(NotImplementedError, name, f,
                                   numeric_only=True) 
Example #13
Source File: test_stat_reductions.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 4 votes vote down vote up
def _check_stat_op(self, name, alternate, string_series_,
                       check_objects=False, check_allna=False):

        with pd.option_context('use_bottleneck', False):
            f = getattr(Series, name)

            # add some NaNs
            string_series_[5:15] = np.NaN

            # mean, idxmax, idxmin, min, and max are valid for dates
            if name not in ['max', 'min', 'mean']:
                ds = Series(pd.date_range('1/1/2001', periods=10))
                with pytest.raises(TypeError):
                    f(ds)

            # skipna or no
            assert pd.notna(f(string_series_))
            assert pd.isna(f(string_series_, skipna=False))

            # check the result is correct
            nona = string_series_.dropna()
            tm.assert_almost_equal(f(nona), alternate(nona.values))
            tm.assert_almost_equal(f(string_series_), alternate(nona.values))

            allna = string_series_ * np.nan

            if check_allna:
                assert np.isnan(f(allna))

            # dtype=object with None, it works!
            s = Series([1, 2, 3, None, 5])
            f(s)

            # GH#2888
            items = [0]
            items.extend(lrange(2 ** 40, 2 ** 40 + 1000))
            s = Series(items, dtype='int64')
            tm.assert_almost_equal(float(f(s)), float(alternate(s.values)))

            # check date range
            if check_objects:
                s = Series(pd.bdate_range('1/1/2000', periods=10))
                res = f(s)
                exp = alternate(s)
                assert res == exp

            # check on string data
            if name not in ['sum', 'min', 'max']:
                with pytest.raises(TypeError):
                    f(Series(list('abc')))

            # Invalid axis.
            with pytest.raises(ValueError):
                f(string_series_, axis=1)

            # Unimplemented numeric_only parameter.
            if 'numeric_only' in compat.signature(f).args:
                with pytest.raises(NotImplementedError, match=name):
                    f(string_series_, numeric_only=True) 
Example #14
Source File: test_analytics.py    From twitter-stock-recommendation with MIT License 4 votes vote down vote up
def _check_stat_op(self, name, alternate, check_objects=False,
                       check_allna=False):

        with pd.option_context('use_bottleneck', False):
            f = getattr(Series, name)

            # add some NaNs
            self.series[5:15] = np.NaN

            # idxmax, idxmin, min, and max are valid for dates
            if name not in ['max', 'min']:
                ds = Series(date_range('1/1/2001', periods=10))
                pytest.raises(TypeError, f, ds)

            # skipna or no
            assert notna(f(self.series))
            assert isna(f(self.series, skipna=False))

            # check the result is correct
            nona = self.series.dropna()
            assert_almost_equal(f(nona), alternate(nona.values))
            assert_almost_equal(f(self.series), alternate(nona.values))

            allna = self.series * nan

            if check_allna:
                assert np.isnan(f(allna))

            # dtype=object with None, it works!
            s = Series([1, 2, 3, None, 5])
            f(s)

            # 2888
            l = [0]
            l.extend(lrange(2 ** 40, 2 ** 40 + 1000))
            s = Series(l, dtype='int64')
            assert_almost_equal(float(f(s)), float(alternate(s.values)))

            # check date range
            if check_objects:
                s = Series(bdate_range('1/1/2000', periods=10))
                res = f(s)
                exp = alternate(s)
                assert res == exp

            # check on string data
            if name not in ['sum', 'min', 'max']:
                pytest.raises(TypeError, f, Series(list('abc')))

            # Invalid axis.
            pytest.raises(ValueError, f, self.series, axis=1)

            # Unimplemented numeric_only parameter.
            if 'numeric_only' in compat.signature(f).args:
                tm.assert_raises_regex(NotImplementedError, name, f,
                                       self.series, numeric_only=True) 
Example #15
Source File: test_analytics.py    From elasticintel with GNU General Public License v3.0 4 votes vote down vote up
def _check_stat_op(self, name, alternate, check_objects=False,
                       check_allna=False):

        with pd.option_context('use_bottleneck', False):
            f = getattr(Series, name)

            # add some NaNs
            self.series[5:15] = np.NaN

            # idxmax, idxmin, min, and max are valid for dates
            if name not in ['max', 'min']:
                ds = Series(date_range('1/1/2001', periods=10))
                pytest.raises(TypeError, f, ds)

            # skipna or no
            assert notna(f(self.series))
            assert isna(f(self.series, skipna=False))

            # check the result is correct
            nona = self.series.dropna()
            assert_almost_equal(f(nona), alternate(nona.values))
            assert_almost_equal(f(self.series), alternate(nona.values))

            allna = self.series * nan

            if check_allna:
                assert np.isnan(f(allna))

            # dtype=object with None, it works!
            s = Series([1, 2, 3, None, 5])
            f(s)

            # 2888
            l = [0]
            l.extend(lrange(2 ** 40, 2 ** 40 + 1000))
            s = Series(l, dtype='int64')
            assert_almost_equal(float(f(s)), float(alternate(s.values)))

            # check date range
            if check_objects:
                s = Series(bdate_range('1/1/2000', periods=10))
                res = f(s)
                exp = alternate(s)
                assert res == exp

            # check on string data
            if name not in ['sum', 'min', 'max']:
                pytest.raises(TypeError, f, Series(list('abc')))

            # Invalid axis.
            pytest.raises(ValueError, f, self.series, axis=1)

            # Unimplemented numeric_only parameter.
            if 'numeric_only' in compat.signature(f).args:
                tm.assert_raises_regex(NotImplementedError, name, f,
                                       self.series, numeric_only=True) 
Example #16
Source File: apply.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 4 votes vote down vote up
def get_result(self):
        """ compute the results """

        # dispatch to agg
        if is_list_like(self.f) or is_dict_like(self.f):
            return self.obj.aggregate(self.f, axis=self.axis,
                                      *self.args, **self.kwds)

        # all empty
        if len(self.columns) == 0 and len(self.index) == 0:
            return self.apply_empty_result()

        # string dispatch
        if isinstance(self.f, compat.string_types):
            # Support for `frame.transform('method')`
            # Some methods (shift, etc.) require the axis argument, others
            # don't, so inspect and insert if necessary.
            func = getattr(self.obj, self.f)
            sig = compat.signature(func)
            if 'axis' in sig.args:
                self.kwds['axis'] = self.axis
            return func(*self.args, **self.kwds)

        # ufunc
        elif isinstance(self.f, np.ufunc):
            with np.errstate(all='ignore'):
                results = self.obj._data.apply('apply', func=self.f)
            return self.obj._constructor(data=results, index=self.index,
                                         columns=self.columns, copy=False)

        # broadcasting
        if self.result_type == 'broadcast':
            return self.apply_broadcast()

        # one axis empty
        elif not all(self.obj.shape):
            return self.apply_empty_result()

        # raw
        elif self.raw and not self.obj._is_mixed_type:
            return self.apply_raw()

        return self.apply_standard() 
Example #17
Source File: _decorators.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def deprecate(name, alternative, version, alt_name=None,
              klass=None, stacklevel=2, msg=None):
    """Return a new function that emits a deprecation warning on use.

    To use this method for a deprecated function, another function
    `alternative` with the same signature must exist. The deprecated
    function will emit a deprecation warning, and in the docstring
    it will contain the deprecation directive with the provided version
    so it can be detected for future removal.

    Parameters
    ----------
    name : str
        Name of function to deprecate.
    alternative : func
        Function to use instead.
    version : str
        Version of pandas in which the method has been deprecated.
    alt_name : str, optional
        Name to use in preference of alternative.__name__.
    klass : Warning, default FutureWarning
    stacklevel : int, default 2
    msg : str
        The message to display in the warning.
        Default is '{name} is deprecated. Use {alt_name} instead.'
    """

    alt_name = alt_name or alternative.__name__
    klass = klass or FutureWarning
    warning_msg = msg or '{} is deprecated, use {} instead'.format(name,
                                                                   alt_name)

    # adding deprecated directive to the docstring
    msg = msg or 'Use `{alt_name}` instead.'.format(alt_name=alt_name)
    msg = '\n    '.join(wrap(msg, 70))

    @Substitution(version=version, msg=msg)
    @Appender(alternative.__doc__)
    def wrapper(*args, **kwargs):
        """
        .. deprecated:: %(version)s

           %(msg)s

        """
        warnings.warn(warning_msg, klass, stacklevel=stacklevel)
        return alternative(*args, **kwargs)

    # Since we are using Substitution to create the required docstring,
    # remove that from the attributes that should be assigned to the wrapper
    assignments = tuple(x for x in WRAPPER_ASSIGNMENTS if x != '__doc__')
    update_wrapper(wrapper, alternative, assigned=assignments)

    return wrapper 
Example #18
Source File: test_analytics.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def _check_stat_op(self, name, alternate, check_objects=False,
                       check_allna=False):

        with pd.option_context('use_bottleneck', False):
            f = getattr(Series, name)

            # add some NaNs
            self.series[5:15] = np.NaN

            # idxmax, idxmin, min, and max are valid for dates
            if name not in ['max', 'min']:
                ds = Series(date_range('1/1/2001', periods=10))
                pytest.raises(TypeError, f, ds)

            # skipna or no
            assert notna(f(self.series))
            assert isna(f(self.series, skipna=False))

            # check the result is correct
            nona = self.series.dropna()
            assert_almost_equal(f(nona), alternate(nona.values))
            assert_almost_equal(f(self.series), alternate(nona.values))

            allna = self.series * nan

            if check_allna:
                assert np.isnan(f(allna))

            # dtype=object with None, it works!
            s = Series([1, 2, 3, None, 5])
            f(s)

            # 2888
            l = [0]
            l.extend(lrange(2 ** 40, 2 ** 40 + 1000))
            s = Series(l, dtype='int64')
            assert_almost_equal(float(f(s)), float(alternate(s.values)))

            # check date range
            if check_objects:
                s = Series(bdate_range('1/1/2000', periods=10))
                res = f(s)
                exp = alternate(s)
                assert res == exp

            # check on string data
            if name not in ['sum', 'min', 'max']:
                pytest.raises(TypeError, f, Series(list('abc')))

            # Invalid axis.
            pytest.raises(ValueError, f, self.series, axis=1)

            # Unimplemented numeric_only parameter.
            if 'numeric_only' in compat.signature(f).args:
                tm.assert_raises_regex(NotImplementedError, name, f,
                                       self.series, numeric_only=True) 
Example #19
Source File: apply.py    From recruit with Apache License 2.0 4 votes vote down vote up
def get_result(self):
        """ compute the results """

        # dispatch to agg
        if is_list_like(self.f) or is_dict_like(self.f):
            return self.obj.aggregate(self.f, axis=self.axis,
                                      *self.args, **self.kwds)

        # all empty
        if len(self.columns) == 0 and len(self.index) == 0:
            return self.apply_empty_result()

        # string dispatch
        if isinstance(self.f, compat.string_types):
            # Support for `frame.transform('method')`
            # Some methods (shift, etc.) require the axis argument, others
            # don't, so inspect and insert if necessary.
            func = getattr(self.obj, self.f)
            sig = compat.signature(func)
            if 'axis' in sig.args:
                self.kwds['axis'] = self.axis
            return func(*self.args, **self.kwds)

        # ufunc
        elif isinstance(self.f, np.ufunc):
            with np.errstate(all='ignore'):
                results = self.obj._data.apply('apply', func=self.f)
            return self.obj._constructor(data=results, index=self.index,
                                         columns=self.columns, copy=False)

        # broadcasting
        if self.result_type == 'broadcast':
            return self.apply_broadcast()

        # one axis empty
        elif not all(self.obj.shape):
            return self.apply_empty_result()

        # raw
        elif self.raw and not self.obj._is_mixed_type:
            return self.apply_raw()

        return self.apply_standard() 
Example #20
Source File: test_stat_reductions.py    From recruit with Apache License 2.0 4 votes vote down vote up
def _check_stat_op(self, name, alternate, string_series_,
                       check_objects=False, check_allna=False):

        with pd.option_context('use_bottleneck', False):
            f = getattr(Series, name)

            # add some NaNs
            string_series_[5:15] = np.NaN

            # mean, idxmax, idxmin, min, and max are valid for dates
            if name not in ['max', 'min', 'mean']:
                ds = Series(pd.date_range('1/1/2001', periods=10))
                with pytest.raises(TypeError):
                    f(ds)

            # skipna or no
            assert pd.notna(f(string_series_))
            assert pd.isna(f(string_series_, skipna=False))

            # check the result is correct
            nona = string_series_.dropna()
            tm.assert_almost_equal(f(nona), alternate(nona.values))
            tm.assert_almost_equal(f(string_series_), alternate(nona.values))

            allna = string_series_ * np.nan

            if check_allna:
                assert np.isnan(f(allna))

            # dtype=object with None, it works!
            s = Series([1, 2, 3, None, 5])
            f(s)

            # GH#2888
            items = [0]
            items.extend(lrange(2 ** 40, 2 ** 40 + 1000))
            s = Series(items, dtype='int64')
            tm.assert_almost_equal(float(f(s)), float(alternate(s.values)))

            # check date range
            if check_objects:
                s = Series(pd.bdate_range('1/1/2000', periods=10))
                res = f(s)
                exp = alternate(s)
                assert res == exp

            # check on string data
            if name not in ['sum', 'min', 'max']:
                with pytest.raises(TypeError):
                    f(Series(list('abc')))

            # Invalid axis.
            with pytest.raises(ValueError):
                f(string_series_, axis=1)

            # Unimplemented numeric_only parameter.
            if 'numeric_only' in compat.signature(f).args:
                with pytest.raises(NotImplementedError, match=name):
                    f(string_series_, numeric_only=True)