title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
Safely raise errors when object contains unicode
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 09bd09b06d9b9..ca46f94752731 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1165,3 +1165,4 @@ Other - Improved error message when attempting to use a Python keyword as an identifier in a ``numexpr`` backed query (:issue:`18221`) - Bug in accessing a :func:`pandas.get_option`, which raised ``KeyError`` rather than ``OptionError`` when looking up a non-existant option key in some cases (:issue:`19789`) +- Bug in :func:`assert_series_equal` and :func:`assert_frame_equal` for Series or DataFrames with differing unicode data (:issue:`20503`) diff --git a/pandas/tests/util/test_testing.py b/pandas/tests/util/test_testing.py index 1c878604b11a2..d6f58d16bcf64 100644 --- a/pandas/tests/util/test_testing.py +++ b/pandas/tests/util/test_testing.py @@ -290,6 +290,24 @@ def test_numpy_array_equal_message(self): assert_almost_equal(np.array([1, 2]), np.array([3, 4, 5]), obj='Index') + def test_numpy_array_equal_unicode_message(self): + # Test ensures that `assert_numpy_array_equals` raises the right + # exception when comparing np.arrays containing differing + # unicode objects (#20503) + + expected = """numpy array are different + +numpy array values are different \\(33\\.33333 %\\) +\\[left\\]: \\[á, à, ä\\] +\\[right\\]: \\[á, à, å\\]""" + + with tm.assert_raises_regex(AssertionError, expected): + assert_numpy_array_equal(np.array([u'á', u'à', u'ä']), + np.array([u'á', u'à', u'å'])) + with tm.assert_raises_regex(AssertionError, expected): + assert_almost_equal(np.array([u'á', u'à', u'ä']), + np.array([u'á', u'à', u'å'])) + @td.skip_if_windows def test_numpy_array_equal_object_message(self): @@ -499,10 +517,13 @@ def _assert_not_equal(self, a, b, **kwargs): def test_equal(self): self._assert_equal(Series(range(3)), Series(range(3))) self._assert_equal(Series(list('abc')), Series(list('abc'))) + self._assert_equal(Series(list(u'áàä')), Series(list(u'áàä'))) def test_not_equal(self): self._assert_not_equal(Series(range(3)), Series(range(3)) + 1) self._assert_not_equal(Series(list('abc')), Series(list('xyz'))) + self._assert_not_equal(Series(list(u'áàä')), Series(list(u'éèë'))) + self._assert_not_equal(Series(list(u'áàä')), Series(list(b'aaa'))) self._assert_not_equal(Series(range(3)), Series(range(4))) self._assert_not_equal( Series(range(3)), Series( @@ -678,6 +699,49 @@ def test_frame_equal_message(self): pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 7]}), by_blocks=True) + def test_frame_equal_message_unicode(self): + # Test ensures that `assert_frame_equals` raises the right + # exception when comparing DataFrames containing differing + # unicode objects (#20503) + + expected = """DataFrame\\.iloc\\[:, 1\\] are different + +DataFrame\\.iloc\\[:, 1\\] values are different \\(33\\.33333 %\\) +\\[left\\]: \\[é, è, ë\\] +\\[right\\]: \\[é, è, e̊\\]""" + + with tm.assert_raises_regex(AssertionError, expected): + assert_frame_equal(pd.DataFrame({'A': [u'á', u'à', u'ä'], + 'E': [u'é', u'è', u'ë']}), + pd.DataFrame({'A': [u'á', u'à', u'ä'], + 'E': [u'é', u'è', u'e̊']})) + + with tm.assert_raises_regex(AssertionError, expected): + assert_frame_equal(pd.DataFrame({'A': [u'á', u'à', u'ä'], + 'E': [u'é', u'è', u'ë']}), + pd.DataFrame({'A': [u'á', u'à', u'ä'], + 'E': [u'é', u'è', u'e̊']}), + by_blocks=True) + + expected = """DataFrame\\.iloc\\[:, 0\\] are different + +DataFrame\\.iloc\\[:, 0\\] values are different \\(100\\.0 %\\) +\\[left\\]: \\[á, à, ä\\] +\\[right\\]: \\[a, a, a\\]""" + + with tm.assert_raises_regex(AssertionError, expected): + assert_frame_equal(pd.DataFrame({'A': [u'á', u'à', u'ä'], + 'E': [u'é', u'è', u'ë']}), + pd.DataFrame({'A': ['a', 'a', 'a'], + 'E': ['e', 'e', 'e']})) + + with tm.assert_raises_regex(AssertionError, expected): + assert_frame_equal(pd.DataFrame({'A': [u'á', u'à', u'ä'], + 'E': [u'é', u'è', u'ë']}), + pd.DataFrame({'A': ['a', 'a', 'a'], + 'E': ['e', 'e', 'e']}), + by_blocks=True) + class TestAssertCategoricalEqual(object): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 6e13a17eba68c..e1484a9c1b390 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -38,7 +38,7 @@ import pandas.compat as compat from pandas.compat import ( filter, map, zip, range, unichr, lrange, lmap, lzip, u, callable, Counter, - raise_with_traceback, httplib, StringIO, PY3) + raise_with_traceback, httplib, StringIO, string_types, PY3, PY2) from pandas import (bdate_range, CategoricalIndex, Categorical, IntervalIndex, DatetimeIndex, TimedeltaIndex, PeriodIndex, RangeIndex, @@ -992,11 +992,20 @@ def raise_assert_detail(obj, message, left, right, diff=None): left = pprint_thing(left) elif is_categorical_dtype(left): left = repr(left) + + if PY2 and isinstance(left, string_types): + # left needs to be printable in native text type in python2 + left = left.encode('utf-8') + if isinstance(right, np.ndarray): right = pprint_thing(right) elif is_categorical_dtype(right): right = repr(right) + if PY2 and isinstance(right, string_types): + # right needs to be printable in native text type in python2 + right = right.encode('utf-8') + msg = """{obj} are different {message}
This safely turns nd.array objects that contain unicode into a representation that can be printed Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [x] closes #20503 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20593
2018-04-03T13:38:07Z
2018-04-09T18:33:59Z
2018-04-09T18:33:59Z
2018-04-10T10:21:42Z
API: rolling.apply will pass Series to function
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 18c4dca5b69da..110550d9f85cd 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -65,6 +65,35 @@ The :func:`get_dummies` now accepts a ``dtype`` argument, which specifies a dtyp pd.get_dummies(df, columns=['c'], dtype=bool).dtypes +.. _whatsnew_0230.enhancements.window_raw: + +Rolling/Expanding.apply() accepts a ``raw`` keyword to pass a ``Series`` to the function +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:func:`Series.rolling().apply() <pandas.core.window.Rolling.apply>`, :func:`DataFrame.rolling().apply() <pandas.core.window.Rolling.apply>`, +:func:`Series.expanding().apply() <pandas.core.window.Expanding.apply>`, and :func:`DataFrame.expanding().apply() <pandas.core.window.Expanding.apply>` have gained a ``raw=None`` parameter. +This is similar to :func:`DataFame.apply`. This parameter, if ``True`` allows one to send a ``np.ndarray`` to the applied function. If ``False`` a ``Series`` will be passed. The +default is ``None``, which preserves backward compatibility, so this will default to ``True``, sending an ``np.ndarray``. +In a future version the default will be changed to ``False``, sending a ``Series``. (:issue:`5071`, :issue:`20584`) + +.. ipython:: python + + s = pd.Series(np.arange(5), np.arange(5) + 1) + s + +Pass a ``Series``: + +.. ipython:: python + + s.rolling(2, min_periods=1).apply(lambda x: x.iloc[-1], raw=False) + +Mimic the original behavior of passing a ndarray: + +.. ipython:: python + + s.rolling(2, min_periods=1).apply(lambda x: x[-1], raw=True) + + .. _whatsnew_0230.enhancements.merge_on_columns_and_levels: Merging on a combination of columns and index levels @@ -815,6 +844,7 @@ Other API Changes - :func:`DatetimeIndex.strftime` and :func:`PeriodIndex.strftime` now return an ``Index`` instead of a numpy array to be consistent with similar accessors (:issue:`20127`) - Constructing a Series from a list of length 1 no longer broadcasts this list when a longer index is specified (:issue:`19714`, :issue:`20391`). - :func:`DataFrame.to_dict` with ``orient='index'`` no longer casts int columns to float for a DataFrame with only int and float columns (:issue:`18580`) +- A user-defined-function that is passed to :func:`Series.rolling().aggregate() <pandas.core.window.Rolling.aggregate>`, :func:`DataFrame.rolling().aggregate() <pandas.core.window.Rolling.aggregate>`, or its expanding cousins, will now *always* be passed a ``Series``, rather than an ``np.array``; ``.apply()`` only has the ``raw`` keyword, see :ref:`here <whatsnew_0230.enhancements.window_raw>`. This is consistent with the signatures of ``.aggregate()`` across pandas (:issue:`20584`) .. _whatsnew_0230.deprecations: @@ -843,6 +873,8 @@ Deprecations - ``Index.summary()`` is deprecated and will be removed in a future version (:issue:`18217`) - ``NDFrame.get_ftype_counts()`` is deprecated and will be removed in a future version (:issue:`18243`) - The ``convert_datetime64`` parameter in :func:`DataFrame.to_records` has been deprecated and will be removed in a future version. The NumPy bug motivating this parameter has been resolved. The default value for this parameter has also changed from ``True`` to ``None`` (:issue:`18160`). +- :func:`Series.rolling().apply() <pandas.core.window.Rolling.apply>`, :func:`DataFrame.rolling().apply() <pandas.core.window.Rolling.apply>`, + :func:`Series.expanding().apply() <pandas.core.window.Expanding.apply>`, and :func:`DataFrame.expanding().apply() <pandas.core.window.Expanding.apply>` have deprecated passing an ``np.array`` by default. One will need to pass the new ``raw`` parameter to be explicit about what is passed (:issue:`20584`) .. _whatsnew_0230.prior_deprecations: diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index aa13f03d8e9e4..e524f823605a4 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -1432,30 +1432,35 @@ def roll_quantile(ndarray[float64_t, cast=True] input, int64_t win, return output -def roll_generic(ndarray[float64_t, cast=True] input, +def roll_generic(object obj, int64_t win, int64_t minp, object index, object closed, - int offset, object func, + int offset, object func, bint raw, object args, object kwargs): cdef: ndarray[double_t] output, counts, bufarr + ndarray[float64_t, cast=True] arr float64_t *buf float64_t *oldbuf int64_t nobs = 0, i, j, s, e, N bint is_variable ndarray[int64_t] start, end - if not input.flags.c_contiguous: - input = input.copy('C') - - n = len(input) + n = len(obj) if n == 0: - return input + return obj + + arr = np.asarray(obj) + + # ndarray input + if raw: + if not arr.flags.c_contiguous: + arr = arr.copy('C') - counts = roll_sum(np.concatenate([np.isfinite(input).astype(float), + counts = roll_sum(np.concatenate([np.isfinite(arr).astype(float), np.array([0.] * offset)]), win, minp, index, closed)[offset:] - start, end, N, win, minp, is_variable = get_window_indexer(input, win, + start, end, N, win, minp, is_variable = get_window_indexer(arr, win, minp, index, closed, floor=0) @@ -1463,8 +1468,8 @@ def roll_generic(ndarray[float64_t, cast=True] input, output = np.empty(N, dtype=float) if is_variable: + # variable window arr or series - # variable window if offset != 0: raise ValueError("unable to roll_generic with a non-zero offset") @@ -1473,7 +1478,20 @@ def roll_generic(ndarray[float64_t, cast=True] input, e = end[i] if counts[i] >= minp: - output[i] = func(input[s:e], *args, **kwargs) + if raw: + output[i] = func(arr[s:e], *args, **kwargs) + else: + output[i] = func(obj.iloc[s:e], *args, **kwargs) + else: + output[i] = NaN + + elif not raw: + # series + for i from 0 <= i < N: + if counts[i] >= minp: + sl = slice(int_max(i + offset - win + 1, 0), + int_min(i + offset + 1, N)) + output[i] = func(obj.iloc[sl], *args, **kwargs) else: output[i] = NaN @@ -1482,12 +1500,12 @@ def roll_generic(ndarray[float64_t, cast=True] input, # truncated windows at the beginning, through first full-length window for i from 0 <= i < (int_min(win, N) - offset): if counts[i] >= minp: - output[i] = func(input[0: (i + offset + 1)], *args, **kwargs) + output[i] = func(arr[0: (i + offset + 1)], *args, **kwargs) else: output[i] = NaN # remaining full-length windows - buf = <float64_t *> input.data + buf = <float64_t *> arr.data bufarr = np.empty(win, dtype=float) oldbuf = <float64_t *> bufarr.data for i from (win - offset) <= i < (N - offset): @@ -1502,7 +1520,7 @@ def roll_generic(ndarray[float64_t, cast=True] input, # truncated windows at the end for i from int_max(N - offset, 0) <= i < N: if counts[i] >= minp: - output[i] = func(input[int_max(i + offset - win + 1, 0): N], + output[i] = func(arr[int_max(i + offset - win + 1, 0): N], *args, **kwargs) else: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ae9d160db08e9..d3ab7afc025c9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4292,6 +4292,8 @@ def pipe(self, func, *args, **kwargs): Notes ----- `agg` is an alias for `aggregate`. Use the alias. + + A passed user-defined-function will be passed a Series for evaluation. """) _shared_docs['transform'] = (""" diff --git a/pandas/core/window.py b/pandas/core/window.py index 5cd4fffb5d7dd..f8b5aa292f309 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -314,7 +314,7 @@ def _center_window(self, result, window): def aggregate(self, arg, *args, **kwargs): result, how = self._aggregate(arg, *args, **kwargs) if result is None: - return self.apply(arg, args=args, kwargs=kwargs) + return self.apply(arg, raw=False, args=args, kwargs=kwargs) return result agg = aggregate @@ -954,23 +954,53 @@ def count(self): Parameters ---------- func : function - Must produce a single value from an ndarray input - \*args and \*\*kwargs are passed to the function""") + Must produce a single value from an ndarray input if ``raw=True`` + or a Series if ``raw=False`` + raw : bool, default None + * ``False`` : passes each row or column as a Series to the + function. + * ``True`` or ``None`` : the passed function will receive ndarray + objects instead. + If you are just applying a NumPy reduction function this will + achieve much better performance. + + The `raw` parameter is required and will show a FutureWarning if + not passed. In the future `raw` will default to False. + + .. versionadded:: 0.23.0 + + \*args and \*\*kwargs are passed to the function""") + + def apply(self, func, raw=None, args=(), kwargs={}): + from pandas import Series - def apply(self, func, args=(), kwargs={}): # TODO: _level is unused? _level = kwargs.pop('_level', None) # noqa window = self._get_window() offset = _offset(window, self.center) index, indexi = self._get_index() + # TODO: default is for backward compat + # change to False in the future + if raw is None: + warnings.warn( + "Currently, 'apply' passes the values as ndarrays to the " + "applied function. In the future, this will change to passing " + "it as Series objects. You need to specify 'raw=True' to keep " + "the current behaviour, and you can pass 'raw=False' to " + "silence this warning", FutureWarning, stacklevel=3) + raw = True + def f(arg, window, min_periods, closed): minp = _use_window(min_periods, window) - return _window.roll_generic(arg, window, minp, indexi, closed, - offset, func, args, kwargs) + if not raw: + arg = Series(arg, index=self.obj.index) + return _window.roll_generic( + arg, window, minp, indexi, + closed, offset, func, raw, args, kwargs) return self._apply(f, func, args=args, kwargs=kwargs, - center=False) + center=False, raw=raw) def sum(self, *args, **kwargs): nv.validate_window_func('sum', args, kwargs) @@ -1498,8 +1528,9 @@ def count(self): @Substitution(name='rolling') @Appender(_doc_template) @Appender(_shared_docs['apply']) - def apply(self, func, args=(), kwargs={}): - return super(Rolling, self).apply(func, args=args, kwargs=kwargs) + def apply(self, func, raw=None, args=(), kwargs={}): + return super(Rolling, self).apply( + func, raw=raw, args=args, kwargs=kwargs) @Substitution(name='rolling') @Appender(_shared_docs['sum']) @@ -1756,8 +1787,9 @@ def count(self, **kwargs): @Substitution(name='expanding') @Appender(_doc_template) @Appender(_shared_docs['apply']) - def apply(self, func, args=(), kwargs={}): - return super(Expanding, self).apply(func, args=args, kwargs=kwargs) + def apply(self, func, raw=None, args=(), kwargs={}): + return super(Expanding, self).apply( + func, raw=raw, args=args, kwargs=kwargs) @Substitution(name='expanding') @Appender(_shared_docs['sum']) diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index dabdb1e8e689c..605230390ff1d 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -29,6 +29,22 @@ def assert_equal(left, right): tm.assert_frame_equal(left, right) +@pytest.fixture(params=[True, False]) +def raw(request): + return request.param + + +@pytest.fixture(params=['triang', 'blackman', 'hamming', 'bartlett', 'bohman', + 'blackmanharris', 'nuttall', 'barthann']) +def win_types(request): + return request.param + + +@pytest.fixture(params=['kaiser', 'gaussian', 'general_gaussian', 'slepian']) +def win_types_special(request): + return request.param + + class Base(object): _nan_locs = np.arange(20, 40) @@ -157,9 +173,16 @@ def test_agg(self): expected.columns = pd.MultiIndex.from_tuples(exp_cols) tm.assert_frame_equal(result, expected, check_like=True) + def test_agg_apply(self, raw): + # passed lambda + df = DataFrame({'A': range(5), 'B': range(0, 10, 2)}) + + r = df.rolling(window=3) + a_sum = r['A'].sum() + result = r.agg({'A': np.sum, 'B': lambda x: np.std(x, ddof=1)}) - rcustom = r['B'].apply(lambda x: np.std(x, ddof=1)) + rcustom = r['B'].apply(lambda x: np.std(x, ddof=1), raw=raw) expected = concat([a_sum, rcustom], axis=1) tm.assert_frame_equal(result, expected, check_like=True) @@ -289,43 +312,51 @@ def setup_method(self, method): self._create_data() @td.skip_if_no_scipy - def test_constructor(self): + @pytest.mark.parametrize( + 'which', ['series', 'frame']) + def test_constructor(self, which): # GH 12669 - for o in [self.series, self.frame]: - c = o.rolling + o = getattr(self, which) + c = o.rolling - # valid - c(win_type='boxcar', window=2, min_periods=1) - c(win_type='boxcar', window=2, min_periods=1, center=True) - c(win_type='boxcar', window=2, min_periods=1, center=False) + # valid + c(win_type='boxcar', window=2, min_periods=1) + c(win_type='boxcar', window=2, min_periods=1, center=True) + c(win_type='boxcar', window=2, min_periods=1, center=False) - for wt in ['boxcar', 'triang', 'blackman', 'hamming', 'bartlett', - 'bohman', 'blackmanharris', 'nuttall', 'barthann']: - c(win_type=wt, window=2) + # not valid + for w in [2., 'foo', np.array([2])]: + with pytest.raises(ValueError): + c(win_type='boxcar', window=2, min_periods=w) + with pytest.raises(ValueError): + c(win_type='boxcar', window=2, min_periods=1, center=w) - # not valid - for w in [2., 'foo', np.array([2])]: - with pytest.raises(ValueError): - c(win_type='boxcar', window=2, min_periods=w) - with pytest.raises(ValueError): - c(win_type='boxcar', window=2, min_periods=1, center=w) + for wt in ['foobar', 1]: + with pytest.raises(ValueError): + c(win_type=wt, window=2) - for wt in ['foobar', 1]: - with pytest.raises(ValueError): - c(win_type=wt, window=2) + @td.skip_if_no_scipy + @pytest.mark.parametrize( + 'which', ['series', 'frame']) + def test_constructor_with_win_type(self, which, win_types): + # GH 12669 + o = getattr(self, which) + c = o.rolling + c(win_type=win_types, window=2) - def test_numpy_compat(self): + @pytest.mark.parametrize( + 'method', ['sum', 'mean']) + def test_numpy_compat(self, method): # see gh-12811 w = rwindow.Window(Series([2, 4, 6]), window=[0, 2]) msg = "numpy operations are not valid with window objects" - for func in ('sum', 'mean'): - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(w, func), 1, 2, 3) - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(w, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(w, method), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(w, method), dtype=np.float64) class TestRolling(Base): @@ -340,59 +371,65 @@ def test_doc_string(self): df.rolling(2).sum() df.rolling(2, min_periods=1).sum() - def test_constructor(self): + @pytest.mark.parametrize( + 'which', ['series', 'frame']) + def test_constructor(self, which): # GH 12669 - for o in [self.series, self.frame]: - c = o.rolling + o = getattr(self, which) + c = o.rolling - # valid - c(window=2) - c(window=2, min_periods=1) - c(window=2, min_periods=1, center=True) - c(window=2, min_periods=1, center=False) + # valid + c(window=2) + c(window=2, min_periods=1) + c(window=2, min_periods=1, center=True) + c(window=2, min_periods=1, center=False) - # GH 13383 - c(0) - with pytest.raises(ValueError): - c(-1) + # GH 13383 + c(0) + with pytest.raises(ValueError): + c(-1) - # not valid - for w in [2., 'foo', np.array([2])]: - with pytest.raises(ValueError): - c(window=w) - with pytest.raises(ValueError): - c(window=2, min_periods=w) - with pytest.raises(ValueError): - c(window=2, min_periods=1, center=w) + # not valid + for w in [2., 'foo', np.array([2])]: + with pytest.raises(ValueError): + c(window=w) + with pytest.raises(ValueError): + c(window=2, min_periods=w) + with pytest.raises(ValueError): + c(window=2, min_periods=1, center=w) @td.skip_if_no_scipy - def test_constructor_with_win_type(self): + @pytest.mark.parametrize( + 'which', ['series', 'frame']) + def test_constructor_with_win_type(self, which): # GH 13383 - for o in [self.series, self.frame]: - c = o.rolling - c(0, win_type='boxcar') - with pytest.raises(ValueError): - c(-1, win_type='boxcar') + o = getattr(self, which) + c = o.rolling + c(0, win_type='boxcar') + with pytest.raises(ValueError): + c(-1, win_type='boxcar') - def test_constructor_with_timedelta_window(self): + @pytest.mark.parametrize( + 'window', [timedelta(days=3), pd.Timedelta(days=3)]) + def test_constructor_with_timedelta_window(self, window): # GH 15440 n = 10 df = DataFrame({'value': np.arange(n)}, index=pd.date_range('2015-12-24', periods=n, freq="D")) expected_data = np.append([0., 1.], np.arange(3., 27., 3)) - for window in [timedelta(days=3), pd.Timedelta(days=3)]: - result = df.rolling(window=window).sum() - expected = DataFrame({'value': expected_data}, - index=pd.date_range('2015-12-24', periods=n, - freq="D")) - tm.assert_frame_equal(result, expected) - expected = df.rolling('3D').sum() - tm.assert_frame_equal(result, expected) + + result = df.rolling(window=window).sum() + expected = DataFrame({'value': expected_data}, + index=pd.date_range('2015-12-24', periods=n, + freq="D")) + tm.assert_frame_equal(result, expected) + expected = df.rolling('3D').sum() + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( 'window', [timedelta(days=3), pd.Timedelta(days=3), '3D']) - def test_constructor_with_timedelta_window_and_minperiods(self, window): + def test_constructor_timedelta_window_and_minperiods(self, window, raw): # GH 15305 n = 10 df = DataFrame({'value': np.arange(n)}, @@ -402,21 +439,22 @@ def test_constructor_with_timedelta_window_and_minperiods(self, window): index=pd.date_range('2017-08-08', periods=n, freq="D")) result_roll_sum = df.rolling(window=window, min_periods=2).sum() result_roll_generic = df.rolling(window=window, - min_periods=2).apply(sum) + min_periods=2).apply(sum, raw=raw) tm.assert_frame_equal(result_roll_sum, expected) tm.assert_frame_equal(result_roll_generic, expected) - def test_numpy_compat(self): + @pytest.mark.parametrize( + 'method', ['std', 'mean', 'sum', 'max', 'min', 'var']) + def test_numpy_compat(self, method): # see gh-12811 r = rwindow.Rolling(Series([2, 4, 6]), window=2) msg = "numpy operations are not valid with window objects" - for func in ('std', 'mean', 'sum', 'max', 'min', 'var'): - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(r, func), 1, 2, 3) - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(r, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(r, method), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(r, method), dtype=np.float64) def test_closed(self): df = DataFrame({'A': [0, 1, 2, 3, 4]}) @@ -483,35 +521,38 @@ def test_doc_string(self): df df.expanding(2).sum() - def test_constructor(self): + @pytest.mark.parametrize( + 'which', ['series', 'frame']) + def test_constructor(self, which): # GH 12669 - for o in [self.series, self.frame]: - c = o.expanding + o = getattr(self, which) + c = o.expanding - # valid - c(min_periods=1) - c(min_periods=1, center=True) - c(min_periods=1, center=False) + # valid + c(min_periods=1) + c(min_periods=1, center=True) + c(min_periods=1, center=False) - # not valid - for w in [2., 'foo', np.array([2])]: - with pytest.raises(ValueError): - c(min_periods=w) - with pytest.raises(ValueError): - c(min_periods=1, center=w) + # not valid + for w in [2., 'foo', np.array([2])]: + with pytest.raises(ValueError): + c(min_periods=w) + with pytest.raises(ValueError): + c(min_periods=1, center=w) - def test_numpy_compat(self): + @pytest.mark.parametrize( + 'method', ['std', 'mean', 'sum', 'max', 'min', 'var']) + def test_numpy_compat(self, method): # see gh-12811 e = rwindow.Expanding(Series([2, 4, 6]), window=2) msg = "numpy operations are not valid with window objects" - for func in ('std', 'mean', 'sum', 'max', 'min', 'var'): - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(e, func), 1, 2, 3) - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(e, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, method), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, method), dtype=np.float64) @pytest.mark.parametrize( 'expander', @@ -558,55 +599,58 @@ def test_doc_string(self): df df.ewm(com=0.5).mean() - def test_constructor(self): - for o in [self.series, self.frame]: - c = o.ewm - - # valid - c(com=0.5) - c(span=1.5) - c(alpha=0.5) - c(halflife=0.75) - c(com=0.5, span=None) - c(alpha=0.5, com=None) - c(halflife=0.75, alpha=None) + @pytest.mark.parametrize( + 'which', ['series', 'frame']) + def test_constructor(self, which): + o = getattr(self, which) + c = o.ewm + + # valid + c(com=0.5) + c(span=1.5) + c(alpha=0.5) + c(halflife=0.75) + c(com=0.5, span=None) + c(alpha=0.5, com=None) + c(halflife=0.75, alpha=None) + + # not valid: mutually exclusive + with pytest.raises(ValueError): + c(com=0.5, alpha=0.5) + with pytest.raises(ValueError): + c(span=1.5, halflife=0.75) + with pytest.raises(ValueError): + c(alpha=0.5, span=1.5) - # not valid: mutually exclusive - with pytest.raises(ValueError): - c(com=0.5, alpha=0.5) - with pytest.raises(ValueError): - c(span=1.5, halflife=0.75) - with pytest.raises(ValueError): - c(alpha=0.5, span=1.5) + # not valid: com < 0 + with pytest.raises(ValueError): + c(com=-0.5) - # not valid: com < 0 - with pytest.raises(ValueError): - c(com=-0.5) + # not valid: span < 1 + with pytest.raises(ValueError): + c(span=0.5) - # not valid: span < 1 - with pytest.raises(ValueError): - c(span=0.5) + # not valid: halflife <= 0 + with pytest.raises(ValueError): + c(halflife=0) - # not valid: halflife <= 0 + # not valid: alpha <= 0 or alpha > 1 + for alpha in (-0.5, 1.5): with pytest.raises(ValueError): - c(halflife=0) + c(alpha=alpha) - # not valid: alpha <= 0 or alpha > 1 - for alpha in (-0.5, 1.5): - with pytest.raises(ValueError): - c(alpha=alpha) - - def test_numpy_compat(self): + @pytest.mark.parametrize( + 'method', ['std', 'mean', 'var']) + def test_numpy_compat(self, method): # see gh-12811 e = rwindow.EWM(Series([2, 4, 6]), alpha=0.5) msg = "numpy operations are not valid with window objects" - for func in ('std', 'mean', 'var'): - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(e, func), 1, 2, 3) - tm.assert_raises_regex(UnsupportedFunctionCall, msg, - getattr(e, func), dtype=np.float64) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, method), 1, 2, 3) + tm.assert_raises_regex(UnsupportedFunctionCall, msg, + getattr(e, method), dtype=np.float64) # gh-12373 : rolling functions error on float32 data @@ -943,11 +987,8 @@ def test_cmov_window_na_min_periods(self): tm.assert_series_equal(xp, rs) @td.skip_if_no_scipy - def test_cmov_window_regular(self): + def test_cmov_window_regular(self, win_types): # GH 8238 - win_types = ['triang', 'blackman', 'hamming', 'bartlett', 'bohman', - 'blackmanharris', 'nuttall', 'barthann'] - vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48]) xps = { @@ -969,33 +1010,25 @@ def test_cmov_window_regular(self): 14.0825, 11.5675, np.nan, np.nan] } - for wt in win_types: - xp = Series(xps[wt]) - rs = Series(vals).rolling(5, win_type=wt, center=True).mean() - tm.assert_series_equal(xp, rs) + xp = Series(xps[win_types]) + rs = Series(vals).rolling(5, win_type=win_types, center=True).mean() + tm.assert_series_equal(xp, rs) @td.skip_if_no_scipy - def test_cmov_window_regular_linear_range(self): + def test_cmov_window_regular_linear_range(self, win_types): # GH 8238 - win_types = ['triang', 'blackman', 'hamming', 'bartlett', 'bohman', - 'blackmanharris', 'nuttall', 'barthann'] - vals = np.array(range(10), dtype=np.float) xp = vals.copy() xp[:2] = np.nan xp[-2:] = np.nan xp = Series(xp) - for wt in win_types: - rs = Series(vals).rolling(5, win_type=wt, center=True).mean() - tm.assert_series_equal(xp, rs) + rs = Series(vals).rolling(5, win_type=win_types, center=True).mean() + tm.assert_series_equal(xp, rs) @td.skip_if_no_scipy - def test_cmov_window_regular_missing_data(self): + def test_cmov_window_regular_missing_data(self, win_types): # GH 8238 - win_types = ['triang', 'blackman', 'hamming', 'bartlett', 'bohman', - 'blackmanharris', 'nuttall', 'barthann'] - vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, np.nan, 10.63, 14.48]) xps = { @@ -1017,17 +1050,18 @@ def test_cmov_window_regular_missing_data(self): 9.16438, 13.05052, 14.02175, 16.1098, 13.65509] } - for wt in win_types: - xp = Series(xps[wt]) - rs = Series(vals).rolling(5, win_type=wt, min_periods=3).mean() - tm.assert_series_equal(xp, rs) + xp = Series(xps[win_types]) + rs = Series(vals).rolling(5, win_type=win_types, min_periods=3).mean() + tm.assert_series_equal(xp, rs) @td.skip_if_no_scipy - def test_cmov_window_special(self): + def test_cmov_window_special(self, win_types_special): # GH 8238 - win_types = ['kaiser', 'gaussian', 'general_gaussian', 'slepian'] - kwds = [{'beta': 1.}, {'std': 1.}, {'power': 2., - 'width': 2.}, {'width': 0.5}] + kwds = { + 'kaiser': {'beta': 1.}, + 'gaussian': {'std': 1.}, + 'general_gaussian': {'power': 2., 'width': 2.}, + 'slepian': {'width': 0.5}} vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48]) @@ -1043,17 +1077,20 @@ def test_cmov_window_special(self): 12.90702, 12.83757, np.nan, np.nan] } - for wt, k in zip(win_types, kwds): - xp = Series(xps[wt]) - rs = Series(vals).rolling(5, win_type=wt, center=True).mean(**k) - tm.assert_series_equal(xp, rs) + xp = Series(xps[win_types_special]) + rs = Series(vals).rolling( + 5, win_type=win_types_special, center=True).mean( + **kwds[win_types_special]) + tm.assert_series_equal(xp, rs) @td.skip_if_no_scipy - def test_cmov_window_special_linear_range(self): + def test_cmov_window_special_linear_range(self, win_types_special): # GH 8238 - win_types = ['kaiser', 'gaussian', 'general_gaussian', 'slepian'] - kwds = [{'beta': 1.}, {'std': 1.}, {'power': 2., - 'width': 2.}, {'width': 0.5}] + kwds = { + 'kaiser': {'beta': 1.}, + 'gaussian': {'std': 1.}, + 'general_gaussian': {'power': 2., 'width': 2.}, + 'slepian': {'width': 0.5}} vals = np.array(range(10), dtype=np.float) xp = vals.copy() @@ -1061,9 +1098,10 @@ def test_cmov_window_special_linear_range(self): xp[-2:] = np.nan xp = Series(xp) - for wt, k in zip(win_types, kwds): - rs = Series(vals).rolling(5, win_type=wt, center=True).mean(**k) - tm.assert_series_equal(xp, rs) + rs = Series(vals).rolling( + 5, win_type=win_types_special, center=True).mean( + **kwds[win_types_special]) + tm.assert_series_equal(xp, rs) def test_rolling_median(self): self._check_moment_func(np.median, name='median') @@ -1150,43 +1188,76 @@ def test_rolling_quantile_param(self): with pytest.raises(TypeError): ser.rolling(3).quantile('foo') - def test_rolling_apply(self): + def test_rolling_apply(self, raw): # suppress warnings about empty slices, as we are deliberately testing # with a 0-length Series + with warnings.catch_warnings(): warnings.filterwarnings("ignore", message=".*(empty slice|0 for slice).*", category=RuntimeWarning) - ser = Series([]) - tm.assert_series_equal(ser, - ser.rolling(10).apply(lambda x: x.mean())) - def f(x): return x[np.isfinite(x)].mean() - self._check_moment_func(np.mean, name='apply', func=f) + self._check_moment_func(np.mean, name='apply', func=f, raw=raw) - # GH 8080 + expected = Series([]) + result = expected.rolling(10).apply(lambda x: x.mean(), raw=raw) + tm.assert_series_equal(result, expected) + + # gh-8080 s = Series([None, None, None]) - result = s.rolling(2, min_periods=0).apply(lambda x: len(x)) + result = s.rolling(2, min_periods=0).apply(lambda x: len(x), raw=raw) expected = Series([1., 2., 2.]) tm.assert_series_equal(result, expected) - result = s.rolling(2, min_periods=0).apply(len) + result = s.rolling(2, min_periods=0).apply(len, raw=raw) tm.assert_series_equal(result, expected) - def test_rolling_apply_out_of_bounds(self): - # #1850 + @pytest.mark.parametrize('klass', [Series, DataFrame]) + @pytest.mark.parametrize( + 'method', [lambda x: x.rolling(window=2), lambda x: x.expanding()]) + def test_apply_future_warning(self, klass, method): + + # gh-5071 + s = klass(np.arange(3)) + + with tm.assert_produces_warning(FutureWarning): + method(s).apply(lambda x: len(x)) + + def test_rolling_apply_out_of_bounds(self, raw): + # gh-1850 vals = pd.Series([1, 2, 3, 4]) - result = vals.rolling(10).apply(np.sum) + result = vals.rolling(10).apply(np.sum, raw=raw) assert result.isna().all() - result = vals.rolling(10, min_periods=1).apply(np.sum) + result = vals.rolling(10, min_periods=1).apply(np.sum, raw=raw) expected = pd.Series([1, 3, 6, 10], dtype=float) tm.assert_almost_equal(result, expected) + @pytest.mark.parametrize('window', [2, '2s']) + def test_rolling_apply_with_pandas_objects(self, window): + # 5071 + df = pd.DataFrame({'A': np.random.randn(5), + 'B': np.random.randint(0, 10, size=5)}, + index=pd.date_range('20130101', periods=5, freq='s')) + + # we have an equal spaced timeseries index + # so simulate removing the first period + def f(x): + if x.index[0] == df.index[0]: + return np.nan + return x.iloc[-1] + + result = df.rolling(window).apply(f, raw=False) + expected = df.iloc[2:].reindex_like(df) + tm.assert_frame_equal(result, expected) + + with pytest.raises(AttributeError): + df.rolling(window).apply(f, raw=True) + def test_rolling_std(self): self._check_moment_func(lambda x: np.std(x, ddof=1), name='std') @@ -1256,10 +1327,10 @@ def get_result(obj, window, min_periods=None, center=False): frame_result = get_result(self.frame, window=50) assert isinstance(frame_result, DataFrame) - tm.assert_series_equal(frame_result.iloc[-1, :], - self.frame.iloc[-50:, :].apply(static_comp, - axis=0), - check_names=False) + tm.assert_series_equal( + frame_result.iloc[-1, :], + self.frame.iloc[-50:, :].apply(static_comp, axis=0, raw=raw), + check_names=False) # check time_rule works if has_time_rule: @@ -1287,7 +1358,7 @@ def get_result(obj, window, min_periods=None, center=False): static_comp(trunc_series)) tm.assert_series_equal(frame_result.xs(last_date), - trunc_frame.apply(static_comp), + trunc_frame.apply(static_comp, raw=raw), check_names=False) # excluding NaNs correctly @@ -1402,26 +1473,20 @@ def test_ewma(self): result = vals.ewm(span=100, adjust=False).mean().sum() assert np.abs(result - 1) < 1e-2 + @pytest.mark.parametrize('adjust', [True, False]) + @pytest.mark.parametrize('ignore_na', [True, False]) + def test_ewma_cases(self, adjust, ignore_na): + # try adjust/ignore_na args matrix + s = Series([1.0, 2.0, 4.0, 8.0]) - expected = Series([1.0, 1.6, 2.736842, 4.923077]) - for f in [lambda s: s.ewm(com=2.0, adjust=True).mean(), - lambda s: s.ewm(com=2.0, adjust=True, - ignore_na=False).mean(), - lambda s: s.ewm(com=2.0, adjust=True, ignore_na=True).mean(), - ]: - result = f(s) - tm.assert_series_equal(result, expected) + if adjust: + expected = Series([1.0, 1.6, 2.736842, 4.923077]) + else: + expected = Series([1.0, 1.333333, 2.222222, 4.148148]) - expected = Series([1.0, 1.333333, 2.222222, 4.148148]) - for f in [lambda s: s.ewm(com=2.0, adjust=False).mean(), - lambda s: s.ewm(com=2.0, adjust=False, - ignore_na=False).mean(), - lambda s: s.ewm(com=2.0, adjust=False, - ignore_na=True).mean(), - ]: - result = f(s) - tm.assert_series_equal(result, expected) + result = s.ewm(com=2.0, adjust=adjust, ignore_na=ignore_na).mean() + tm.assert_series_equal(result, expected) def test_ewma_nan_handling(self): s = Series([1.] + [np.nan] * 5 + [1.]) @@ -1555,14 +1620,13 @@ def test_ewm_domain_checks(self): s.ewm(alpha=1.0) pytest.raises(ValueError, s.ewm, alpha=1.1) - def test_ew_empty_series(self): + @pytest.mark.parametrize('method', ['mean', 'vol', 'var']) + def test_ew_empty_series(self, method): vals = pd.Series([], dtype=np.float64) ewm = vals.ewm(3) - funcs = ['mean', 'vol', 'var'] - for f in funcs: - result = getattr(ewm, f)() - tm.assert_almost_equal(result, vals) + result = getattr(ewm, method)() + tm.assert_almost_equal(result, vals) def _check_ew(self, name=None, preserve_nan=False): series_result = getattr(self.series.ewm(com=10), name)() @@ -2160,7 +2224,7 @@ def test_expanding_consistency(self, min_periods): if name == 'count': expanding_f_result = expanding_f() expanding_apply_f_result = x.expanding( - min_periods=0).apply(func=f) + min_periods=0).apply(func=f, raw=True) else: if name in ['cov', 'corr']: expanding_f_result = expanding_f( @@ -2168,7 +2232,7 @@ def test_expanding_consistency(self, min_periods): else: expanding_f_result = expanding_f() expanding_apply_f_result = x.expanding( - min_periods=min_periods).apply(func=f) + min_periods=min_periods).apply(func=f, raw=True) # GH 9422 if name in ['sum', 'prod']: @@ -2259,7 +2323,7 @@ def test_rolling_consistency(self, window, min_periods, center): rolling_f_result = rolling_f() rolling_apply_f_result = x.rolling( window=window, min_periods=0, - center=center).apply(func=f) + center=center).apply(func=f, raw=True) else: if name in ['cov', 'corr']: rolling_f_result = rolling_f( @@ -2268,7 +2332,7 @@ def test_rolling_consistency(self, window, min_periods, center): rolling_f_result = rolling_f() rolling_apply_f_result = x.rolling( window=window, min_periods=min_periods, - center=center).apply(func=f) + center=center).apply(func=f, raw=True) # GH 9422 if name in ['sum', 'prod']: @@ -2348,29 +2412,25 @@ def test_corr_sanity(self): except AssertionError: print(res) - def test_flex_binary_frame(self): - def _check(method): - series = self.frame[1] + @pytest.mark.parametrize('method', ['corr', 'cov']) + def test_flex_binary_frame(self, method): + series = self.frame[1] - res = getattr(series.rolling(window=10), method)(self.frame) - res2 = getattr(self.frame.rolling(window=10), method)(series) - exp = self.frame.apply(lambda x: getattr( - series.rolling(window=10), method)(x)) + res = getattr(series.rolling(window=10), method)(self.frame) + res2 = getattr(self.frame.rolling(window=10), method)(series) + exp = self.frame.apply(lambda x: getattr( + series.rolling(window=10), method)(x)) - tm.assert_frame_equal(res, exp) - tm.assert_frame_equal(res2, exp) + tm.assert_frame_equal(res, exp) + tm.assert_frame_equal(res2, exp) - frame2 = self.frame.copy() - frame2.values[:] = np.random.randn(*frame2.shape) + frame2 = self.frame.copy() + frame2.values[:] = np.random.randn(*frame2.shape) - res3 = getattr(self.frame.rolling(window=10), method)(frame2) - exp = DataFrame(dict((k, getattr(self.frame[k].rolling( - window=10), method)(frame2[k])) for k in self.frame)) - tm.assert_frame_equal(res3, exp) - - methods = ['corr', 'cov'] - for meth in methods: - _check(meth) + res3 = getattr(self.frame.rolling(window=10), method)(frame2) + exp = DataFrame(dict((k, getattr(self.frame[k].rolling( + window=10), method)(frame2[k])) for k in self.frame)) + tm.assert_frame_equal(res3, exp) def test_ewmcov(self): self._check_binary_ew('cov') @@ -2417,19 +2477,24 @@ def func(A, B, com, **kwargs): pytest.raises(Exception, func, A, randn(50), 20, min_periods=5) - def test_expanding_apply_args_kwargs(self): + def test_expanding_apply_args_kwargs(self, raw): + def mean_w_arg(x, const): return np.mean(x) + const df = DataFrame(np.random.rand(20, 3)) - expected = df.expanding().apply(np.mean) + 20. + expected = df.expanding().apply(np.mean, raw=raw) + 20. - tm.assert_frame_equal(df.expanding().apply(mean_w_arg, args=(20, )), - expected) - tm.assert_frame_equal(df.expanding().apply(mean_w_arg, - kwargs={'const': 20}), - expected) + result = df.expanding().apply(mean_w_arg, + raw=raw, + args=(20, )) + tm.assert_frame_equal(result, expected) + + result = df.expanding().apply(mean_w_arg, + raw=raw, + kwargs={'const': 20}) + tm.assert_frame_equal(result, expected) def test_expanding_corr(self): A = self.series.dropna() @@ -2539,42 +2604,47 @@ def test_rolling_corr_diff_length(self): result = s1.rolling(window=3, min_periods=2).corr(s2a) tm.assert_series_equal(result, expected) - def test_rolling_functions_window_non_shrinkage(self): + @pytest.mark.parametrize( + 'f', + [ + lambda x: (x.rolling(window=10, min_periods=5) + .cov(x, pairwise=False)), + lambda x: (x.rolling(window=10, min_periods=5) + .corr(x, pairwise=False)), + lambda x: x.rolling(window=10, min_periods=5).max(), + lambda x: x.rolling(window=10, min_periods=5).min(), + lambda x: x.rolling(window=10, min_periods=5).sum(), + lambda x: x.rolling(window=10, min_periods=5).mean(), + lambda x: x.rolling(window=10, min_periods=5).std(), + lambda x: x.rolling(window=10, min_periods=5).var(), + lambda x: x.rolling(window=10, min_periods=5).skew(), + lambda x: x.rolling(window=10, min_periods=5).kurt(), + lambda x: x.rolling( + window=10, min_periods=5).quantile(quantile=0.5), + lambda x: x.rolling(window=10, min_periods=5).median(), + lambda x: x.rolling(window=10, min_periods=5).apply( + sum, raw=False), + lambda x: x.rolling(window=10, min_periods=5).apply( + sum, raw=True), + lambda x: x.rolling(win_type='boxcar', + window=10, min_periods=5).mean()]) + def test_rolling_functions_window_non_shrinkage(self, f): # GH 7764 s = Series(range(4)) s_expected = Series(np.nan, index=s.index) df = DataFrame([[1, 5], [3, 2], [3, 9], [-1, 0]], columns=['A', 'B']) df_expected = DataFrame(np.nan, index=df.index, columns=df.columns) - functions = [lambda x: (x.rolling(window=10, min_periods=5) - .cov(x, pairwise=False)), - lambda x: (x.rolling(window=10, min_periods=5) - .corr(x, pairwise=False)), - lambda x: x.rolling(window=10, min_periods=5).max(), - lambda x: x.rolling(window=10, min_periods=5).min(), - lambda x: x.rolling(window=10, min_periods=5).sum(), - lambda x: x.rolling(window=10, min_periods=5).mean(), - lambda x: x.rolling(window=10, min_periods=5).std(), - lambda x: x.rolling(window=10, min_periods=5).var(), - lambda x: x.rolling(window=10, min_periods=5).skew(), - lambda x: x.rolling(window=10, min_periods=5).kurt(), - lambda x: x.rolling( - window=10, min_periods=5).quantile(quantile=0.5), - lambda x: x.rolling(window=10, min_periods=5).median(), - lambda x: x.rolling(window=10, min_periods=5).apply(sum), - lambda x: x.rolling(win_type='boxcar', - window=10, min_periods=5).mean()] - for f in functions: - try: - s_result = f(s) - tm.assert_series_equal(s_result, s_expected) + try: + s_result = f(s) + tm.assert_series_equal(s_result, s_expected) - df_result = f(df) - tm.assert_frame_equal(df_result, df_expected) - except (ImportError): + df_result = f(df) + tm.assert_frame_equal(df_result, df_expected) + except (ImportError): - # scipy needed for rolling_window - continue + # scipy needed for rolling_window + pytest.skip("scipy not available") def test_rolling_functions_window_non_shrinkage_binary(self): @@ -2620,7 +2690,10 @@ def test_moment_functions_zero_length(self): lambda x: x.expanding(min_periods=5).kurt(), lambda x: x.expanding(min_periods=5).quantile(0.5), lambda x: x.expanding(min_periods=5).median(), - lambda x: x.expanding(min_periods=5).apply(sum), + lambda x: x.expanding(min_periods=5).apply( + sum, raw=False), + lambda x: x.expanding(min_periods=5).apply( + sum, raw=True), lambda x: x.rolling(window=10).count(), lambda x: x.rolling(window=10, min_periods=5).cov( x, pairwise=False), @@ -2637,7 +2710,10 @@ def test_moment_functions_zero_length(self): lambda x: x.rolling( window=10, min_periods=5).quantile(0.5), lambda x: x.rolling(window=10, min_periods=5).median(), - lambda x: x.rolling(window=10, min_periods=5).apply(sum), + lambda x: x.rolling(window=10, min_periods=5).apply( + sum, raw=False), + lambda x: x.rolling(window=10, min_periods=5).apply( + sum, raw=True), lambda x: x.rolling(win_type='boxcar', window=10, min_periods=5).mean(), ] @@ -2805,20 +2881,25 @@ def expanding_func(x, min_periods=1, center=False, axis=0): return getattr(exp, func)() self._check_expanding(expanding_func, static_comp, preserve_nan=False) - def test_expanding_apply(self): + def test_expanding_apply(self, raw): def expanding_mean(x, min_periods=1): + exp = x.expanding(min_periods=min_periods) - return exp.apply(lambda x: x.mean()) + result = exp.apply(lambda x: x.mean(), raw=raw) + return result - self._check_expanding(expanding_mean, np.mean) + # TODO(jreback), needed to add preserve_nan=False + # here to make this pass + self._check_expanding(expanding_mean, np.mean, preserve_nan=False) ser = Series([]) - tm.assert_series_equal(ser, ser.expanding().apply(lambda x: x.mean())) + tm.assert_series_equal(ser, ser.expanding().apply( + lambda x: x.mean(), raw=raw)) # GH 8080 s = Series([None, None, None]) - result = s.expanding(min_periods=0).apply(lambda x: len(x)) + result = s.expanding(min_periods=0).apply(lambda x: len(x), raw=raw) expected = Series([1., 2., 3.]) tm.assert_series_equal(result, expected) @@ -3057,13 +3138,14 @@ def func(x): expected = g.apply(func) tm.assert_series_equal(result, expected) - def test_rolling_apply(self): + def test_rolling_apply(self, raw): g = self.frame.groupby('A') r = g.rolling(window=4) # reduction - result = r.apply(lambda x: x.sum()) - expected = g.apply(lambda x: x.rolling(4).apply(lambda y: y.sum())) + result = r.apply(lambda x: x.sum(), raw=raw) + expected = g.apply( + lambda x: x.rolling(4).apply(lambda y: y.sum(), raw=raw)) tm.assert_frame_equal(result, expected) def test_expanding(self): @@ -3104,13 +3186,14 @@ def func(x): expected = g.apply(func) tm.assert_series_equal(result, expected) - def test_expanding_apply(self): + def test_expanding_apply(self, raw): g = self.frame.groupby('A') r = g.expanding() # reduction - result = r.apply(lambda x: x.sum()) - expected = g.apply(lambda x: x.expanding().apply(lambda y: y.sum())) + result = r.apply(lambda x: x.sum(), raw=raw) + expected = g.apply( + lambda x: x.expanding().apply(lambda y: y.sum(), raw=raw)) tm.assert_frame_equal(result, expected) @@ -3624,22 +3707,22 @@ def test_ragged_max(self): expected['B'] = [0.0, 1, 2, 3, 4] tm.assert_frame_equal(result, expected) - def test_ragged_apply(self): + def test_ragged_apply(self, raw): df = self.ragged f = lambda x: 1 - result = df.rolling(window='1s', min_periods=1).apply(f) + result = df.rolling(window='1s', min_periods=1).apply(f, raw=raw) expected = df.copy() expected['B'] = 1. tm.assert_frame_equal(result, expected) - result = df.rolling(window='2s', min_periods=1).apply(f) + result = df.rolling(window='2s', min_periods=1).apply(f, raw=raw) expected = df.copy() expected['B'] = 1. tm.assert_frame_equal(result, expected) - result = df.rolling(window='5s', min_periods=1).apply(f) + result = df.rolling(window='5s', min_periods=1).apply(f, raw=raw) expected = df.copy() expected['B'] = 1. tm.assert_frame_equal(result, expected) @@ -3662,8 +3745,14 @@ def test_all(self): expected = er.quantile(0.5) tm.assert_frame_equal(result, expected) - result = r.apply(lambda x: 1) - expected = er.apply(lambda x: 1) + def test_all_apply(self, raw): + + df = self.regular * 2 + er = df.rolling(window=1) + r = df.rolling(window='1s') + + result = r.apply(lambda x: 1, raw=raw) + expected = er.apply(lambda x: 1, raw=raw) tm.assert_frame_equal(result, expected) def test_all2(self):
closes #5071
https://api.github.com/repos/pandas-dev/pandas/pulls/20584
2018-04-02T14:09:07Z
2018-04-16T14:54:04Z
2018-04-16T14:54:04Z
2018-08-02T14:16:32Z
API: categorical grouping will no longer return the cartesian product
diff --git a/doc/source/groupby.rst b/doc/source/groupby.rst index 407fad39ba232..3616a7e1b41d2 100644 --- a/doc/source/groupby.rst +++ b/doc/source/groupby.rst @@ -91,10 +91,10 @@ The mapping can be specified many different ways: - A Python function, to be called on each of the axis labels. - A list or NumPy array of the same length as the selected axis. - A dict or ``Series``, providing a ``label -> group name`` mapping. - - For ``DataFrame`` objects, a string indicating a column to be used to group. + - For ``DataFrame`` objects, a string indicating a column to be used to group. Of course ``df.groupby('A')`` is just syntactic sugar for ``df.groupby(df['A'])``, but it makes life simpler. - - For ``DataFrame`` objects, a string indicating an index level to be used to + - For ``DataFrame`` objects, a string indicating an index level to be used to group. - A list of any of the above things. @@ -120,7 +120,7 @@ consider the following ``DataFrame``: 'D' : np.random.randn(8)}) df -On a DataFrame, we obtain a GroupBy object by calling :meth:`~DataFrame.groupby`. +On a DataFrame, we obtain a GroupBy object by calling :meth:`~DataFrame.groupby`. We could naturally group by either the ``A`` or ``B`` columns, or both: .. ipython:: python @@ -360,8 +360,8 @@ Index level names may be specified as keys directly to ``groupby``. DataFrame column selection in GroupBy ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Once you have created the GroupBy object from a DataFrame, you might want to do -something different for each of the columns. Thus, using ``[]`` similar to +Once you have created the GroupBy object from a DataFrame, you might want to do +something different for each of the columns. Thus, using ``[]`` similar to getting a column from a DataFrame, you can do: .. ipython:: python @@ -421,7 +421,7 @@ statement if you wish: ``for (k1, k2), group in grouped:``. Selecting a group ----------------- -A single group can be selected using +A single group can be selected using :meth:`~pandas.core.groupby.DataFrameGroupBy.get_group`: .. ipython:: python @@ -444,8 +444,8 @@ perform a computation on the grouped data. These operations are similar to the :ref:`aggregating API <basics.aggregate>`, :ref:`window functions API <stats.aggregate>`, and :ref:`resample API <timeseries.aggregate>`. -An obvious one is aggregation via the -:meth:`~pandas.core.groupby.DataFrameGroupBy.aggregate` or equivalently +An obvious one is aggregation via the +:meth:`~pandas.core.groupby.DataFrameGroupBy.aggregate` or equivalently :meth:`~pandas.core.groupby.DataFrameGroupBy.agg` method: .. ipython:: python @@ -517,12 +517,12 @@ Some common aggregating functions are tabulated below: :meth:`~pd.core.groupby.DataFrameGroupBy.nth`;Take nth value, or a subset if n is a list :meth:`~pd.core.groupby.DataFrameGroupBy.min`;Compute min of group values :meth:`~pd.core.groupby.DataFrameGroupBy.max`;Compute max of group values - -The aggregating functions above will exclude NA values. Any function which + +The aggregating functions above will exclude NA values. Any function which reduces a :class:`Series` to a scalar value is an aggregation function and will work, a trivial example is ``df.groupby('A').agg(lambda ser: 1)``. Note that -:meth:`~pd.core.groupby.DataFrameGroupBy.nth` can act as a reducer *or* a +:meth:`~pd.core.groupby.DataFrameGroupBy.nth` can act as a reducer *or* a filter, see :ref:`here <groupby.nth>`. .. _groupby.aggregate.multifunc: @@ -732,7 +732,7 @@ and that the transformed data contains no NAs. .. note:: Some functions will automatically transform the input when applied to a - GroupBy object, but returning an object of the same shape as the original. + GroupBy object, but returning an object of the same shape as the original. Passing ``as_index=False`` will not affect these transformation methods. For example: ``fillna, ffill, bfill, shift.``. @@ -926,7 +926,7 @@ The dimension of the returned result can also change: In [11]: grouped.apply(f) -``apply`` on a Series can operate on a returned value from the applied function, +``apply`` on a Series can operate on a returned value from the applied function, that is itself a series, and possibly upcast the result to a DataFrame: .. ipython:: python @@ -984,20 +984,48 @@ will be (silently) dropped. Thus, this does not pose any problems: df.groupby('A').std() -Note that ``df.groupby('A').colname.std().`` is more efficient than +Note that ``df.groupby('A').colname.std().`` is more efficient than ``df.groupby('A').std().colname``, so if the result of an aggregation function -is only interesting over one column (here ``colname``), it may be filtered +is only interesting over one column (here ``colname``), it may be filtered *before* applying the aggregation function. +.. _groupby.observed: + +Handling of (un)observed Categorical values +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When using a ``Categorical`` grouper (as a single or as part of multipler groupers), the ``observed`` keyword +controls whether to return a cartesian product of all possible groupers values (``observed=False``) or only those +that are observed groupers (``observed=True``). + +Show all values: + +.. ipython:: python + + pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'], categories=['a', 'b']), observed=False).count() + +Show only the observed values: + +.. ipython:: python + + pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'], categories=['a', 'b']), observed=True).count() + +The returned dtype of the grouped will *always* include *all* of the catergories that were grouped. + +.. ipython:: python + + s = pd.Series([1, 1, 1]).groupby(pd.Categorical(['a', 'a', 'a'], categories=['a', 'b']), observed=False).count() + s.index.dtype + .. _groupby.missing: NA and NaT group handling ~~~~~~~~~~~~~~~~~~~~~~~~~ -If there are any NaN or NaT values in the grouping key, these will be -automatically excluded. In other words, there will never be an "NA group" or -"NaT group". This was not the case in older versions of pandas, but users were -generally discarding the NA group anyway (and supporting it was an +If there are any NaN or NaT values in the grouping key, these will be +automatically excluded. In other words, there will never be an "NA group" or +"NaT group". This was not the case in older versions of pandas, but users were +generally discarding the NA group anyway (and supporting it was an implementation headache). Grouping with ordered factors @@ -1084,8 +1112,8 @@ This shows the first or last n rows from each group. Taking the nth row of each group ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -To select from a DataFrame or Series the nth item, use -:meth:`~pd.core.groupby.DataFrameGroupBy.nth`. This is a reduction method, and +To select from a DataFrame or Series the nth item, use +:meth:`~pd.core.groupby.DataFrameGroupBy.nth`. This is a reduction method, and will return a single row (or no row) per group if you pass an int for n: .. ipython:: python @@ -1153,7 +1181,7 @@ Enumerate groups .. versionadded:: 0.20.2 To see the ordering of the groups (as opposed to the order of rows -within a group given by ``cumcount``) you can use +within a group given by ``cumcount``) you can use :meth:`~pandas.core.groupby.DataFrameGroupBy.ngroup`. @@ -1273,7 +1301,7 @@ Regroup columns of a DataFrame according to their sum, and sum the aggregated on Multi-column factorization ~~~~~~~~~~~~~~~~~~~~~~~~~~ -By using :meth:`~pandas.core.groupby.DataFrameGroupBy.ngroup`, we can extract +By using :meth:`~pandas.core.groupby.DataFrameGroupBy.ngroup`, we can extract information about the groups in a way similar to :func:`factorize` (as described further in the :ref:`reshaping API <reshaping.factorize>`) but which applies naturally to multiple columns of mixed type and different diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 604b68b650201..5af703822829b 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -396,6 +396,58 @@ documentation. If you build an extension array, publicize it on our .. _cyberpandas: https://cyberpandas.readthedocs.io/en/latest/ +.. _whatsnew_0230.enhancements.categorical_grouping: + +Categorical Groupers has gained an observed keyword +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +In previous versions, grouping by 1 or more categorical columns would result in an index that was the cartesian product of all of the categories for +each grouper, not just the observed values.``.groupby()`` has gained the ``observed`` keyword to toggle this behavior. The default remains backward +compatible (generate a cartesian product). (:issue:`14942`, :issue:`8138`, :issue:`15217`, :issue:`17594`, :issue:`8669`, :issue:`20583`) + + +.. ipython:: python + + cat1 = pd.Categorical(["a", "a", "b", "b"], + categories=["a", "b", "z"], ordered=True) + cat2 = pd.Categorical(["c", "d", "c", "d"], + categories=["c", "d", "y"], ordered=True) + df = pd.DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + df['C'] = ['foo', 'bar'] * 2 + df + +To show all values, the previous behavior: + +.. ipython:: python + + df.groupby(['A', 'B', 'C'], observed=False).count() + + +To show only observed values: + +.. ipython:: python + + df.groupby(['A', 'B', 'C'], observed=True).count() + +For pivotting operations, this behavior is *already* controlled by the ``dropna`` keyword: + +.. ipython:: python + + cat1 = pd.Categorical(["a", "a", "b", "b"], + categories=["a", "b", "z"], ordered=True) + cat2 = pd.Categorical(["c", "d", "c", "d"], + categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + df + +.. ipython:: python + + pd.pivot_table(df, values='values', index=['A', 'B'], + dropna=True) + pd.pivot_table(df, values='values', index=['A', 'B'], + dropna=False) + + .. _whatsnew_0230.enhancements.other: Other Enhancements diff --git a/pandas/conftest.py b/pandas/conftest.py index 559b5e44631b6..c4aab1b632b00 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -66,6 +66,17 @@ def ip(): return InteractiveShell() +@pytest.fixture(params=[True, False, None]) +def observed(request): + """ pass in the observed keyword to groupby for [True, False] + This indicates whether categoricals should return values for + values which are not in the grouper [False / None], or only values which + appear in the grouper [True]. [None] is supported for future compatiblity + if we decide to change the default (and would need to warn if this + parameter is not passed)""" + return request.param + + @pytest.fixture(params=[None, 'gzip', 'bz2', 'zip', pytest.param('xz', marks=td.skip_if_no_lzma)]) def compression(request): diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 517c21cc1bc3a..f91782459df67 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -647,8 +647,13 @@ def _set_categories(self, categories, fastpath=False): self._dtype = new_dtype - def _codes_for_groupby(self, sort): + def _codes_for_groupby(self, sort, observed): """ + Code the categories to ensure we can groupby for categoricals. + + If observed=True, we return a new Categorical with the observed + categories only. + If sort=False, return a copy of self, coded with categories as returned by .unique(), followed by any categories not appearing in the data. If sort=True, return self. @@ -661,6 +666,8 @@ def _codes_for_groupby(self, sort): ---------- sort : boolean The value of the sort parameter groupby was called with. + observed : boolean + Account only for the observed values Returns ------- @@ -671,6 +678,26 @@ def _codes_for_groupby(self, sort): categories in the original order. """ + # we only care about observed values + if observed: + unique_codes = unique1d(self.codes) + cat = self.copy() + + take_codes = unique_codes[unique_codes != -1] + if self.ordered: + take_codes = np.sort(take_codes) + + # we recode according to the uniques + categories = self.categories.take(take_codes) + codes = _recode_for_categories(self.codes, + self.categories, + categories) + + # return a new categorical that maps our new codes + # and categories + dtype = CategoricalDtype(categories, ordered=self.ordered) + return type(self)(codes, dtype=dtype, fastpath=True) + # Already sorted according to self.categories; all is fine if sort: return self @@ -2161,7 +2188,7 @@ def unique(self): # exclude nan from indexer for categories take_codes = unique_codes[unique_codes != -1] if self.ordered: - take_codes = sorted(take_codes) + take_codes = np.sort(take_codes) return cat.set_categories(cat.categories.take(take_codes)) def _values_for_factorize(self): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index af19acbb416ee..e68662037b43d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6599,7 +6599,7 @@ def clip_lower(self, threshold, axis=None, inplace=False): axis=axis, inplace=inplace) def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, - group_keys=True, squeeze=False, **kwargs): + group_keys=True, squeeze=False, observed=None, **kwargs): """ Group series using mapper (dict or key function, apply given function to group, return result as series) or by a series of columns. @@ -6632,6 +6632,13 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, squeeze : boolean, default False reduce the dimensionality of the return type if possible, otherwise return a consistent type + observed : boolean, default None + if True: only show observed values for categorical groupers. + if False: show all values for categorical groupers. + if None: if any categorical groupers, show a FutureWarning, + default to False. + + .. versionadded:: 0.23.0 Returns ------- @@ -6665,7 +6672,7 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, axis = self._get_axis_number(axis) return groupby(self, by=by, axis=axis, level=level, as_index=as_index, sort=sort, group_keys=group_keys, squeeze=squeeze, - **kwargs) + observed=observed, **kwargs) def asfreq(self, freq, method=None, how=None, normalize=False, fill_value=None): diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 8c20d62117e25..8613ab4d8c59d 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -556,7 +556,8 @@ class _GroupBy(PandasObject, SelectionMixin): def __init__(self, obj, keys=None, axis=0, level=None, grouper=None, exclusions=None, selection=None, as_index=True, - sort=True, group_keys=True, squeeze=False, **kwargs): + sort=True, group_keys=True, squeeze=False, + observed=None, **kwargs): self._selection = selection @@ -576,6 +577,7 @@ def __init__(self, obj, keys=None, axis=0, level=None, self.sort = sort self.group_keys = group_keys self.squeeze = squeeze + self.observed = observed self.mutated = kwargs.pop('mutated', False) if grouper is None: @@ -583,6 +585,7 @@ def __init__(self, obj, keys=None, axis=0, level=None, axis=axis, level=level, sort=sort, + observed=observed, mutated=self.mutated) self.obj = obj @@ -1661,10 +1664,11 @@ def nth(self, n, dropna=None): if dropna not in ['any', 'all']: if isinstance(self._selected_obj, Series) and dropna is True: - warnings.warn("the dropna='%s' keyword is deprecated," + warnings.warn("the dropna={dropna} keyword is deprecated," "use dropna='all' instead. " "For a Series groupby, dropna must be " - "either None, 'any' or 'all'." % (dropna), + "either None, 'any' or 'all'.".format( + dropna=dropna), FutureWarning, stacklevel=2) dropna = 'all' @@ -2331,27 +2335,30 @@ def ngroups(self): def recons_labels(self): comp_ids, obs_ids, _ = self.group_info labels = (ping.labels for ping in self.groupings) - return decons_obs_group_ids(comp_ids, - obs_ids, self.shape, labels, xnull=True) + return decons_obs_group_ids( + comp_ids, obs_ids, self.shape, labels, xnull=True) @cache_readonly def result_index(self): if not self.compressed and len(self.groupings) == 1: - return self.groupings[0].group_index.rename(self.names[0]) - - return MultiIndex(levels=[ping.group_index for ping in self.groupings], - labels=self.recons_labels, - verify_integrity=False, - names=self.names) + return self.groupings[0].result_index.rename(self.names[0]) + + labels = self.recons_labels + levels = [ping.result_index for ping in self.groupings] + result = MultiIndex(levels=levels, + labels=labels, + verify_integrity=False, + names=self.names) + return result def get_group_levels(self): if not self.compressed and len(self.groupings) == 1: - return [self.groupings[0].group_index] + return [self.groupings[0].result_index] name_list = [] for ping, labels in zip(self.groupings, self.recons_labels): labels = _ensure_platform_int(labels) - levels = ping.group_index.take(labels) + levels = ping.result_index.take(labels) name_list.append(levels) @@ -2883,6 +2890,8 @@ class Grouping(object): obj : name : level : + observed : boolean, default False + If we are a Categorical, use the observed values in_axis : if the Grouping is a column in self.obj and hence among Groupby.exclusions list @@ -2898,14 +2907,16 @@ class Grouping(object): """ def __init__(self, index, grouper=None, obj=None, name=None, level=None, - sort=True, in_axis=False): + sort=True, observed=None, in_axis=False): self.name = name self.level = level self.grouper = _convert_grouper(index, grouper) + self.all_grouper = None self.index = index self.sort = sort self.obj = obj + self.observed = observed self.in_axis = in_axis # right place for this? @@ -2953,17 +2964,30 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None, # a passed Categorical elif is_categorical_dtype(self.grouper): - self.grouper = self.grouper._codes_for_groupby(self.sort) + # observed can be True/False/None + # we treat None as False. If in the future + # we need to warn if observed is not passed + # then we have this option + # gh-20583 + + self.all_grouper = self.grouper + self.grouper = self.grouper._codes_for_groupby( + self.sort, observed) + categories = self.grouper.categories # we make a CategoricalIndex out of the cat grouper # preserving the categories / ordered attributes self._labels = self.grouper.codes + if observed: + codes = algorithms.unique1d(self.grouper.codes) + else: + codes = np.arange(len(categories)) - c = self.grouper.categories self._group_index = CategoricalIndex( - Categorical.from_codes(np.arange(len(c)), - categories=c, - ordered=self.grouper.ordered)) + Categorical.from_codes( + codes=codes, + categories=categories, + ordered=self.grouper.ordered)) # we are done if isinstance(self.grouper, Grouping): @@ -3022,6 +3046,22 @@ def labels(self): self._make_labels() return self._labels + @cache_readonly + def result_index(self): + if self.all_grouper is not None: + all_categories = self.all_grouper.categories + + # we re-order to the original category orderings + if self.sort: + return self.group_index.set_categories(all_categories) + + # we are not sorting, so add unobserved to the end + categories = self.group_index.categories + return self.group_index.add_categories( + all_categories[~all_categories.isin(categories)]) + + return self.group_index + @property def group_index(self): if self._group_index is None: @@ -3048,7 +3088,7 @@ def groups(self): def _get_grouper(obj, key=None, axis=0, level=None, sort=True, - mutated=False, validate=True): + observed=None, mutated=False, validate=True): """ create and return a BaseGrouper, which is an internal mapping of how to create the grouper indexers. @@ -3065,6 +3105,9 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True, are and then creates a Grouping for each one, combined into a BaseGrouper. + If observed & we have a categorical grouper, only show the observed + values + If validate, then check for key/level overlaps """ @@ -3243,6 +3286,7 @@ def is_in_obj(gpr): name=name, level=level, sort=sort, + observed=observed, in_axis=in_axis) \ if not isinstance(gpr, Grouping) else gpr @@ -4154,7 +4198,7 @@ def first_not_none(values): not_indexed_same=not_indexed_same) elif self.grouper.groupings is not None: if len(self.grouper.groupings) > 1: - key_index = MultiIndex.from_tuples(keys, names=key_names) + key_index = self.grouper.result_index else: ping = self.grouper.groupings[0] @@ -4244,8 +4288,9 @@ def first_not_none(values): # normally use vstack as its faster than concat # and if we have mi-columns - if isinstance(v.index, - MultiIndex) or key_index is None: + if (isinstance(v.index, MultiIndex) or + key_index is None or + isinstance(key_index, MultiIndex)): stacked_values = np.vstack(map(np.asarray, values)) result = DataFrame(stacked_values, index=key_index, columns=index) @@ -4696,6 +4741,14 @@ def _reindex_output(self, result): This can re-expand the output space """ + + # TODO(jreback): remove completely + # when observed parameter is defaulted to True + # gh-20583 + + if self.observed: + return result + groupings = self.grouper.groupings if groupings is None: return result diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 71caa098c7a28..3ffef5804acf7 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -782,9 +782,9 @@ def _concat_same_dtype(self, to_concat, name): result.name = name return result - def _codes_for_groupby(self, sort): + def _codes_for_groupby(self, sort, observed): """ Return a Categorical adjusted for groupby """ - return self.values._codes_for_groupby(sort) + return self.values._codes_for_groupby(sort, observed) @classmethod def _add_comparison_methods(cls): diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 74a9b59d3194a..39fb57e68c9c0 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -79,7 +79,7 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', pass values = list(values) - grouped = data.groupby(keys) + grouped = data.groupby(keys, observed=dropna) agged = grouped.agg(aggfunc) table = agged @@ -120,6 +120,7 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', data = data[data.notna().all(axis=1)] table = _add_margins(table, data, values, rows=index, cols=columns, aggfunc=aggfunc, + observed=dropna, margins_name=margins_name, fill_value=fill_value) # discard the top level @@ -138,7 +139,7 @@ def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', def _add_margins(table, data, values, rows, cols, aggfunc, - margins_name='All', fill_value=None): + observed=None, margins_name='All', fill_value=None): if not isinstance(margins_name, compat.string_types): raise ValueError('margins_name argument must be a string') @@ -168,6 +169,7 @@ def _add_margins(table, data, values, rows, cols, aggfunc, if values: marginal_result_set = _generate_marginal_results(table, data, values, rows, cols, aggfunc, + observed, grand_margin, margins_name) if not isinstance(marginal_result_set, tuple): @@ -175,7 +177,7 @@ def _add_margins(table, data, values, rows, cols, aggfunc, result, margin_keys, row_margin = marginal_result_set else: marginal_result_set = _generate_marginal_results_without_values( - table, data, rows, cols, aggfunc, margins_name) + table, data, rows, cols, aggfunc, observed, margins_name) if not isinstance(marginal_result_set, tuple): return marginal_result_set result, margin_keys, row_margin = marginal_result_set @@ -230,6 +232,7 @@ def _compute_grand_margin(data, values, aggfunc, def _generate_marginal_results(table, data, values, rows, cols, aggfunc, + observed, grand_margin, margins_name='All'): if len(cols) > 0: @@ -241,10 +244,13 @@ def _all_key(key): return (key, margins_name) + ('',) * (len(cols) - 1) if len(rows) > 0: - margin = data[rows + values].groupby(rows).agg(aggfunc) + margin = data[rows + values].groupby( + rows, observed=observed).agg(aggfunc) cat_axis = 1 - for key, piece in table.groupby(level=0, axis=cat_axis): + for key, piece in table.groupby(level=0, + axis=cat_axis, + observed=observed): all_key = _all_key(key) # we are going to mutate this, so need to copy! @@ -264,7 +270,9 @@ def _all_key(key): else: margin = grand_margin cat_axis = 0 - for key, piece in table.groupby(level=0, axis=cat_axis): + for key, piece in table.groupby(level=0, + axis=cat_axis, + observed=observed): all_key = _all_key(key) table_pieces.append(piece) table_pieces.append(Series(margin[key], index=[all_key])) @@ -279,7 +287,8 @@ def _all_key(key): margin_keys = table.columns if len(cols) > 0: - row_margin = data[cols + values].groupby(cols).agg(aggfunc) + row_margin = data[cols + values].groupby( + cols, observed=observed).agg(aggfunc) row_margin = row_margin.stack() # slight hack @@ -293,7 +302,7 @@ def _all_key(key): def _generate_marginal_results_without_values( table, data, rows, cols, aggfunc, - margins_name='All'): + observed, margins_name='All'): if len(cols) > 0: # need to "interleave" the margins margin_keys = [] @@ -304,14 +313,17 @@ def _all_key(): return (margins_name, ) + ('', ) * (len(cols) - 1) if len(rows) > 0: - margin = data[rows].groupby(rows).apply(aggfunc) + margin = data[rows].groupby(rows, + observed=observed).apply(aggfunc) all_key = _all_key() table[all_key] = margin result = table margin_keys.append(all_key) else: - margin = data.groupby(level=0, axis=0).apply(aggfunc) + margin = data.groupby(level=0, + axis=0, + observed=observed).apply(aggfunc) all_key = _all_key() table[all_key] = margin result = table @@ -322,7 +334,7 @@ def _all_key(): margin_keys = table.columns if len(cols): - row_margin = data[cols].groupby(cols).apply(aggfunc) + row_margin = data[cols].groupby(cols, observed=observed).apply(aggfunc) else: row_margin = Series(np.nan, index=result.columns) diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index 5bd239f8a3034..b60eb89e87da5 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -573,7 +573,7 @@ def test_sort_index_intervalindex(self): bins=[-3, -0.5, 0, 0.5, 3]) model = pd.concat([y, x1, x2], axis=1, keys=['Y', 'X1', 'X2']) - result = model.groupby(['X1', 'X2']).mean().unstack() + result = model.groupby(['X1', 'X2'], observed=True).mean().unstack() expected = IntervalIndex.from_tuples( [(-3.0, -0.5), (-0.5, 0.0), (0.0, 0.5), (0.5, 3.0)], diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index 80383c895a5e5..48a45e93e1e8e 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -158,35 +158,46 @@ def test__cython_agg_general(op, targop): ('min', np.min), ('max', np.max), ] ) -def test_cython_agg_empty_buckets(op, targop): +def test_cython_agg_empty_buckets(op, targop, observed): df = pd.DataFrame([11, 12, 13]) grps = range(0, 55, 5) # calling _cython_agg_general directly, instead of via the user API # which sets different values for min_count, so do that here. - result = df.groupby(pd.cut(df[0], grps))._cython_agg_general(op) - expected = df.groupby(pd.cut(df[0], grps)).agg(lambda x: targop(x)) + g = df.groupby(pd.cut(df[0], grps), observed=observed) + result = g._cython_agg_general(op) + + g = df.groupby(pd.cut(df[0], grps), observed=observed) + expected = g.agg(lambda x: targop(x)) tm.assert_frame_equal(result, expected) -def test_cython_agg_empty_buckets_nanops(): +def test_cython_agg_empty_buckets_nanops(observed): # GH-18869 can't call nanops on empty groups, so hardcode expected # for these df = pd.DataFrame([11, 12, 13], columns=['a']) grps = range(0, 25, 5) # add / sum - result = df.groupby(pd.cut(df['a'], grps))._cython_agg_general('add') + result = df.groupby(pd.cut(df['a'], grps), + observed=observed)._cython_agg_general('add') intervals = pd.interval_range(0, 20, freq=5) expected = pd.DataFrame( {"a": [0, 0, 36, 0]}, index=pd.CategoricalIndex(intervals, name='a', ordered=True)) + if observed: + expected = expected[expected.a != 0] + tm.assert_frame_equal(result, expected) # prod - result = df.groupby(pd.cut(df['a'], grps))._cython_agg_general('prod') + result = df.groupby(pd.cut(df['a'], grps), + observed=observed)._cython_agg_general('prod') expected = pd.DataFrame( {"a": [1, 1, 1716, 1]}, index=pd.CategoricalIndex(intervals, name='a', ordered=True)) + if observed: + expected = expected[expected.a != 1] + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index a10f7f6e46210..34489051efc18 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -488,15 +488,17 @@ def test_agg_structs_series(structure, expected): @pytest.mark.xfail(reason="GH-18869: agg func not called on empty groups.") -def test_agg_category_nansum(): +def test_agg_category_nansum(observed): categories = ['a', 'b', 'c'] df = pd.DataFrame({"A": pd.Categorical(['a', 'a', 'b'], categories=categories), 'B': [1, 2, 3]}) - result = df.groupby("A").B.agg(np.nansum) + result = df.groupby("A", observed=observed).B.agg(np.nansum) expected = pd.Series([3, 3, 0], index=pd.CategoricalIndex(['a', 'b', 'c'], categories=categories, name='A'), name='B') + if observed: + expected = expected[expected != 0] tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 160b60e69f39d..e0793b8e1bd64 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -5,16 +5,43 @@ import pytest import numpy as np -from numpy import nan - import pandas as pd from pandas import (Index, MultiIndex, CategoricalIndex, - DataFrame, Categorical, Series, Interval, qcut) + DataFrame, Categorical, Series, qcut) from pandas.util.testing import assert_frame_equal, assert_series_equal import pandas.util.testing as tm -def test_groupby(): +def cartesian_product_for_groupers(result, args, names): + """ Reindex to a cartesian production for the groupers, + preserving the nature (Categorical) of each grouper """ + + def f(a): + if isinstance(a, (CategoricalIndex, Categorical)): + categories = a.categories + a = Categorical.from_codes(np.arange(len(categories)), + categories=categories, + ordered=a.ordered) + return a + + index = pd.MultiIndex.from_product(map(f, args), names=names) + return result.reindex(index).sort_index() + + +def test_apply_use_categorical_name(df): + cats = qcut(df.C, 4) + + def get_stats(group): + return {'min': group.min(), + 'max': group.max(), + 'count': group.count(), + 'mean': group.mean()} + + result = df.groupby(cats, observed=False).D.apply(get_stats) + assert result.index.names[0] == 'C' + + +def test_basic(): cats = Categorical(["a", "a", "a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c", "d"], ordered=True) @@ -22,56 +49,29 @@ def test_groupby(): exp_index = CategoricalIndex(list('abcd'), name='b', ordered=True) expected = DataFrame({'a': [1, 2, 4, np.nan]}, index=exp_index) - result = data.groupby("b").mean() + result = data.groupby("b", observed=False).mean() tm.assert_frame_equal(result, expected) - raw_cat1 = Categorical(["a", "a", "b", "b"], - categories=["a", "b", "z"], ordered=True) - raw_cat2 = Categorical(["c", "d", "c", "d"], - categories=["c", "d", "y"], ordered=True) - df = DataFrame({"A": raw_cat1, "B": raw_cat2, "values": [1, 2, 3, 4]}) + cat1 = Categorical(["a", "a", "b", "b"], + categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], + categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) # single grouper - gb = df.groupby("A") + gb = df.groupby("A", observed=False) exp_idx = CategoricalIndex(['a', 'b', 'z'], name='A', ordered=True) expected = DataFrame({'values': Series([3, 7, 0], index=exp_idx)}) result = gb.sum() tm.assert_frame_equal(result, expected) - # multiple groupers - gb = df.groupby(['A', 'B']) - exp_index = pd.MultiIndex.from_product( - [Categorical(["a", "b", "z"], ordered=True), - Categorical(["c", "d", "y"], ordered=True)], - names=['A', 'B']) - expected = DataFrame({'values': [1, 2, np.nan, 3, 4, np.nan, - np.nan, np.nan, np.nan]}, - index=exp_index) - result = gb.sum() - tm.assert_frame_equal(result, expected) - - # multiple groupers with a non-cat - df = df.copy() - df['C'] = ['foo', 'bar'] * 2 - gb = df.groupby(['A', 'B', 'C']) - exp_index = pd.MultiIndex.from_product( - [Categorical(["a", "b", "z"], ordered=True), - Categorical(["c", "d", "y"], ordered=True), - ['foo', 'bar']], - names=['A', 'B', 'C']) - expected = DataFrame({'values': Series( - np.nan, index=exp_index)}).sort_index() - expected.iloc[[1, 2, 7, 8], 0] = [1, 2, 3, 4] - result = gb.sum() - tm.assert_frame_equal(result, expected) - # GH 8623 x = DataFrame([[1, 'John P. Doe'], [2, 'Jane Dove'], [1, 'John P. Doe']], columns=['person_id', 'person_name']) x['person_name'] = Categorical(x.person_name) - g = x.groupby(['person_id']) + g = x.groupby(['person_id'], observed=False) result = g.transform(lambda x: x) tm.assert_frame_equal(result, x[['person_name']]) @@ -93,36 +93,48 @@ def f(x): df = DataFrame({"a": [5, 15, 25]}) c = pd.cut(df.a, bins=[0, 10, 20, 30, 40]) - result = df.a.groupby(c).transform(sum) + result = df.a.groupby(c, observed=False).transform(sum) tm.assert_series_equal(result, df['a']) tm.assert_series_equal( - df.a.groupby(c).transform(lambda xs: np.sum(xs)), df['a']) - tm.assert_frame_equal(df.groupby(c).transform(sum), df[['a']]) + df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), + df['a']) + tm.assert_frame_equal( + df.groupby(c, observed=False).transform(sum), + df[['a']]) tm.assert_frame_equal( - df.groupby(c).transform(lambda xs: np.max(xs)), df[['a']]) + df.groupby(c, observed=False).transform(lambda xs: np.max(xs)), + df[['a']]) # Filter - tm.assert_series_equal(df.a.groupby(c).filter(np.all), df['a']) - tm.assert_frame_equal(df.groupby(c).filter(np.all), df) + tm.assert_series_equal( + df.a.groupby(c, observed=False).filter(np.all), + df['a']) + tm.assert_frame_equal( + df.groupby(c, observed=False).filter(np.all), + df) # Non-monotonic df = DataFrame({"a": [5, 15, 25, -5]}) c = pd.cut(df.a, bins=[-10, 0, 10, 20, 30, 40]) - result = df.a.groupby(c).transform(sum) + result = df.a.groupby(c, observed=False).transform(sum) tm.assert_series_equal(result, df['a']) tm.assert_series_equal( - df.a.groupby(c).transform(lambda xs: np.sum(xs)), df['a']) - tm.assert_frame_equal(df.groupby(c).transform(sum), df[['a']]) + df.a.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), + df['a']) tm.assert_frame_equal( - df.groupby(c).transform(lambda xs: np.sum(xs)), df[['a']]) + df.groupby(c, observed=False).transform(sum), + df[['a']]) + tm.assert_frame_equal( + df.groupby(c, observed=False).transform(lambda xs: np.sum(xs)), + df[['a']]) # GH 9603 df = DataFrame({'a': [1, 0, 0, 0]}) c = pd.cut(df.a, [0, 1, 2, 3, 4], labels=Categorical(list('abcd'))) - result = df.groupby(c).apply(len) + result = df.groupby(c, observed=False).apply(len) exp_index = CategoricalIndex( c.values.categories, ordered=c.values.ordered) @@ -130,36 +142,56 @@ def f(x): expected.index.name = 'a' tm.assert_series_equal(result, expected) + # more basic + levels = ['foo', 'bar', 'baz', 'qux'] + codes = np.random.randint(0, 4, size=100) -def test_groupby_sort(): + cats = Categorical.from_codes(codes, levels, ordered=True) - # http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby - # This should result in a properly sorted Series so that the plot - # has a sorted x axis - # self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar') + data = DataFrame(np.random.randn(100, 4)) - df = DataFrame({'value': np.random.randint(0, 10000, 100)}) - labels = ["{0} - {1}".format(i, i + 499) for i in range(0, 10000, 500)] - cat_labels = Categorical(labels, labels) + result = data.groupby(cats, observed=False).mean() - df = df.sort_values(by=['value'], ascending=True) - df['value_group'] = pd.cut(df.value, range(0, 10500, 500), - right=False, labels=cat_labels) + expected = data.groupby(np.asarray(cats), observed=False).mean() + exp_idx = CategoricalIndex(levels, categories=cats.categories, + ordered=True) + expected = expected.reindex(exp_idx) - res = df.groupby(['value_group'])['value_group'].count() - exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))] - exp.index = CategoricalIndex(exp.index, name=exp.index.name) - tm.assert_series_equal(res, exp) + assert_frame_equal(result, expected) + grouped = data.groupby(cats, observed=False) + desc_result = grouped.describe() -def test_level_groupby_get_group(): + idx = cats.codes.argsort() + ord_labels = np.asarray(cats).take(idx) + ord_data = data.take(idx) + + exp_cats = Categorical(ord_labels, ordered=True, + categories=['foo', 'bar', 'baz', 'qux']) + expected = ord_data.groupby( + exp_cats, sort=False, observed=False).describe() + assert_frame_equal(desc_result, expected) + + # GH 10460 + expc = Categorical.from_codes(np.arange(4).repeat(8), + levels, ordered=True) + exp = CategoricalIndex(expc) + tm.assert_index_equal((desc_result.stack().index + .get_level_values(0)), exp) + exp = Index(['count', 'mean', 'std', 'min', '25%', '50%', + '75%', 'max'] * 4) + tm.assert_index_equal((desc_result.stack().index + .get_level_values(1)), exp) + + +def test_level_get_group(observed): # GH15155 df = DataFrame(data=np.arange(2, 22, 2), index=MultiIndex( levels=[pd.CategoricalIndex(["a", "b"]), range(10)], labels=[[0] * 5 + [1] * 5, range(10)], names=["Index1", "Index2"])) - g = df.groupby(level=["Index1"]) + g = df.groupby(level=["Index1"], observed=observed) # expected should equal test.loc[["a"]] # GH15166 @@ -173,94 +205,217 @@ def test_level_groupby_get_group(): assert_frame_equal(result, expected) -def test_apply_use_categorical_name(df): - cats = qcut(df.C, 4) +@pytest.mark.parametrize('ordered', [True, False]) +def test_apply(ordered): + # GH 10138 - def get_stats(group): - return {'min': group.min(), - 'max': group.max(), - 'count': group.count(), - 'mean': group.mean()} + dense = Categorical(list('abc'), ordered=ordered) + + # 'b' is in the categories but not in the list + missing = Categorical( + list('aaa'), categories=['a', 'b'], ordered=ordered) + values = np.arange(len(dense)) + df = DataFrame({'missing': missing, + 'dense': dense, + 'values': values}) + grouped = df.groupby(['missing', 'dense'], observed=True) + + # missing category 'b' should still exist in the output index + idx = MultiIndex.from_arrays( + [missing, dense], names=['missing', 'dense']) + expected = DataFrame([0, 1, 2.], + index=idx, + columns=['values']) + + result = grouped.apply(lambda x: np.mean(x)) + assert_frame_equal(result, expected) - result = df.groupby(cats).D.apply(get_stats) - assert result.index.names[0] == 'C' + # we coerce back to ints + expected = expected.astype('int') + result = grouped.mean() + assert_frame_equal(result, expected) + result = grouped.agg(np.mean) + assert_frame_equal(result, expected) -def test_apply_categorical_data(): - # GH 10138 - for ordered in [True, False]: - dense = Categorical(list('abc'), ordered=ordered) - # 'b' is in the categories but not in the list - missing = Categorical( - list('aaa'), categories=['a', 'b'], ordered=ordered) - values = np.arange(len(dense)) - df = DataFrame({'missing': missing, - 'dense': dense, - 'values': values}) - grouped = df.groupby(['missing', 'dense']) - - # missing category 'b' should still exist in the output index - idx = MultiIndex.from_product( - [Categorical(['a', 'b'], ordered=ordered), - Categorical(['a', 'b', 'c'], ordered=ordered)], - names=['missing', 'dense']) - expected = DataFrame([0, 1, 2, np.nan, np.nan, np.nan], - index=idx, - columns=['values']) - - assert_frame_equal(grouped.apply(lambda x: np.mean(x)), expected) - assert_frame_equal(grouped.mean(), expected) - assert_frame_equal(grouped.agg(np.mean), expected) - - # but for transform we should still get back the original index - idx = MultiIndex.from_product([['a'], ['a', 'b', 'c']], - names=['missing', 'dense']) - expected = Series(1, index=idx) - assert_series_equal(grouped.apply(lambda x: 1), expected) - - -def test_groupby_categorical(): - levels = ['foo', 'bar', 'baz', 'qux'] - codes = np.random.randint(0, 4, size=100) + # but for transform we should still get back the original index + idx = MultiIndex.from_arrays([missing, dense], + names=['missing', 'dense']) + expected = Series(1, index=idx) + result = grouped.apply(lambda x: 1) + assert_series_equal(result, expected) + + +def test_observed(observed): + # multiple groupers, don't re-expand the output space + # of the grouper + # gh-14942 (implement) + # gh-10132 (back-compat) + # gh-8138 (back-compat) + # gh-8869 + + cat1 = Categorical(["a", "a", "b", "b"], + categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], + categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + df['C'] = ['foo', 'bar'] * 2 - cats = Categorical.from_codes(codes, levels, ordered=True) + # multiple groupers with a non-cat + gb = df.groupby(['A', 'B', 'C'], observed=observed) + exp_index = pd.MultiIndex.from_arrays( + [cat1, cat2, ['foo', 'bar'] * 2], + names=['A', 'B', 'C']) + expected = DataFrame({'values': Series( + [1, 2, 3, 4], index=exp_index)}).sort_index() + result = gb.sum() + if not observed: + expected = cartesian_product_for_groupers( + expected, + [cat1, cat2, ['foo', 'bar']], + list('ABC')) - data = DataFrame(np.random.randn(100, 4)) + tm.assert_frame_equal(result, expected) - result = data.groupby(cats).mean() + gb = df.groupby(['A', 'B'], observed=observed) + exp_index = pd.MultiIndex.from_arrays( + [cat1, cat2], + names=['A', 'B']) + expected = DataFrame({'values': [1, 2, 3, 4]}, + index=exp_index) + result = gb.sum() + if not observed: + expected = cartesian_product_for_groupers( + expected, + [cat1, cat2], + list('AB')) - expected = data.groupby(np.asarray(cats)).mean() - exp_idx = CategoricalIndex(levels, categories=cats.categories, - ordered=True) - expected = expected.reindex(exp_idx) + tm.assert_frame_equal(result, expected) - assert_frame_equal(result, expected) + # https://github.com/pandas-dev/pandas/issues/8138 + d = {'cat': + pd.Categorical(["a", "b", "a", "b"], categories=["a", "b", "c"], + ordered=True), + 'ints': [1, 1, 2, 2], + 'val': [10, 20, 30, 40]} + df = pd.DataFrame(d) - grouped = data.groupby(cats) - desc_result = grouped.describe() + # Grouping on a single column + groups_single_key = df.groupby("cat", observed=observed) + result = groups_single_key.mean() - idx = cats.codes.argsort() - ord_labels = np.asarray(cats).take(idx) - ord_data = data.take(idx) + exp_index = pd.CategoricalIndex(list('ab'), name="cat", + categories=list('abc'), + ordered=True) + expected = DataFrame({"ints": [1.5, 1.5], "val": [20., 30]}, + index=exp_index) + if not observed: + index = pd.CategoricalIndex(list('abc'), name="cat", + categories=list('abc'), + ordered=True) + expected = expected.reindex(index) - exp_cats = Categorical(ord_labels, ordered=True, - categories=['foo', 'bar', 'baz', 'qux']) - expected = ord_data.groupby(exp_cats, sort=False).describe() - assert_frame_equal(desc_result, expected) + tm.assert_frame_equal(result, expected) - # GH 10460 - expc = Categorical.from_codes(np.arange(4).repeat(8), - levels, ordered=True) - exp = CategoricalIndex(expc) - tm.assert_index_equal((desc_result.stack().index - .get_level_values(0)), exp) - exp = Index(['count', 'mean', 'std', 'min', '25%', '50%', - '75%', 'max'] * 4) - tm.assert_index_equal((desc_result.stack().index - .get_level_values(1)), exp) + # Grouping on two columns + groups_double_key = df.groupby(["cat", "ints"], observed=observed) + result = groups_double_key.agg('mean') + expected = DataFrame( + {"val": [10, 30, 20, 40], + "cat": pd.Categorical(['a', 'a', 'b', 'b'], + categories=['a', 'b', 'c'], + ordered=True), + "ints": [1, 2, 1, 2]}).set_index(["cat", "ints"]) + if not observed: + expected = cartesian_product_for_groupers( + expected, + [df.cat.values, [1, 2]], + ['cat', 'ints']) + + tm.assert_frame_equal(result, expected) + # GH 10132 + for key in [('a', 1), ('b', 2), ('b', 1), ('a', 2)]: + c, i = key + result = groups_double_key.get_group(key) + expected = df[(df.cat == c) & (df.ints == i)] + assert_frame_equal(result, expected) + + # gh-8869 + # with as_index + d = {'foo': [10, 8, 4, 8, 4, 1, 1], 'bar': [10, 20, 30, 40, 50, 60, 70], + 'baz': ['d', 'c', 'e', 'a', 'a', 'd', 'c']} + df = pd.DataFrame(d) + cat = pd.cut(df['foo'], np.linspace(0, 10, 3)) + df['range'] = cat + groups = df.groupby(['range', 'baz'], as_index=False, observed=observed) + result = groups.agg('mean') + + groups2 = df.groupby(['range', 'baz'], as_index=True, observed=observed) + expected = groups2.agg('mean').reset_index() + tm.assert_frame_equal(result, expected) + + +def test_observed_codes_remap(observed): + d = {'C1': [3, 3, 4, 5], 'C2': [1, 2, 3, 4], 'C3': [10, 100, 200, 34]} + df = pd.DataFrame(d) + values = pd.cut(df['C1'], [1, 2, 3, 6]) + values.name = "cat" + groups_double_key = df.groupby([values, 'C2'], observed=observed) + + idx = MultiIndex.from_arrays([values, [1, 2, 3, 4]], + names=["cat", "C2"]) + expected = DataFrame({"C1": [3, 3, 4, 5], + "C3": [10, 100, 200, 34]}, index=idx) + if not observed: + expected = cartesian_product_for_groupers( + expected, + [values.values, [1, 2, 3, 4]], + ['cat', 'C2']) + + result = groups_double_key.agg('mean') + tm.assert_frame_equal(result, expected) + + +def test_observed_perf(): + # we create a cartesian product, so this is + # non-performant if we don't use observed values + # gh-14942 + df = DataFrame({ + 'cat': np.random.randint(0, 255, size=30000), + 'int_id': np.random.randint(0, 255, size=30000), + 'other_id': np.random.randint(0, 10000, size=30000), + 'foo': 0}) + df['cat'] = df.cat.astype(str).astype('category') -def test_groupby_datetime_categorical(): + grouped = df.groupby(['cat', 'int_id', 'other_id'], observed=True) + result = grouped.count() + assert result.index.levels[0].nunique() == df.cat.nunique() + assert result.index.levels[1].nunique() == df.int_id.nunique() + assert result.index.levels[2].nunique() == df.other_id.nunique() + + +def test_observed_groups(observed): + # gh-20583 + # test that we have the appropriate groups + + cat = pd.Categorical(['a', 'c', 'a'], categories=['a', 'b', 'c']) + df = pd.DataFrame({'cat': cat, 'vals': [1, 2, 3]}) + g = df.groupby('cat', observed=observed) + + result = g.groups + if observed: + expected = {'a': Index([0, 2], dtype='int64'), + 'c': Index([1], dtype='int64')} + else: + expected = {'a': Index([0, 2], dtype='int64'), + 'b': Index([], dtype='int64'), + 'c': Index([1], dtype='int64')} + + tm.assert_dict_equal(result, expected) + + +def test_datetime(): # GH9049: ensure backward compatibility levels = pd.date_range('2014-01-01', periods=4) codes = np.random.randint(0, 4, size=100) @@ -268,9 +423,9 @@ def test_groupby_datetime_categorical(): cats = Categorical.from_codes(codes, levels, ordered=True) data = DataFrame(np.random.randn(100, 4)) - result = data.groupby(cats).mean() + result = data.groupby(cats, observed=False).mean() - expected = data.groupby(np.asarray(cats)).mean() + expected = data.groupby(np.asarray(cats), observed=False).mean() expected = expected.reindex(levels) expected.index = CategoricalIndex(expected.index, categories=expected.index, @@ -278,13 +433,13 @@ def test_groupby_datetime_categorical(): assert_frame_equal(result, expected) - grouped = data.groupby(cats) + grouped = data.groupby(cats, observed=False) desc_result = grouped.describe() idx = cats.codes.argsort() ord_labels = cats.take_nd(idx) ord_data = data.take(idx) - expected = ord_data.groupby(ord_labels).describe() + expected = ord_data.groupby(ord_labels, observed=False).describe() assert_frame_equal(desc_result, expected) tm.assert_index_equal(desc_result.index, expected.index) tm.assert_index_equal( @@ -303,7 +458,7 @@ def test_groupby_datetime_categorical(): .get_level_values(1)), exp) -def test_groupby_categorical_index(): +def test_categorical_index(): s = np.random.RandomState(12345) levels = ['foo', 'bar', 'baz', 'qux'] @@ -315,23 +470,23 @@ def test_groupby_categorical_index(): df['cats'] = cats # with a cat index - result = df.set_index('cats').groupby(level=0).sum() - expected = df[list('abcd')].groupby(cats.codes).sum() + result = df.set_index('cats').groupby(level=0, observed=False).sum() + expected = df[list('abcd')].groupby(cats.codes, observed=False).sum() expected.index = CategoricalIndex( Categorical.from_codes( [0, 1, 2, 3], levels, ordered=True), name='cats') assert_frame_equal(result, expected) # with a cat column, should produce a cat index - result = df.groupby('cats').sum() - expected = df[list('abcd')].groupby(cats.codes).sum() + result = df.groupby('cats', observed=False).sum() + expected = df[list('abcd')].groupby(cats.codes, observed=False).sum() expected.index = CategoricalIndex( Categorical.from_codes( [0, 1, 2, 3], levels, ordered=True), name='cats') assert_frame_equal(result, expected) -def test_groupby_describe_categorical_columns(): +def test_describe_categorical_columns(): # GH 11558 cats = pd.CategoricalIndex(['qux', 'foo', 'baz', 'bar'], categories=['foo', 'bar', 'baz', 'qux'], @@ -343,14 +498,15 @@ def test_groupby_describe_categorical_columns(): tm.assert_categorical_equal(result.stack().columns.values, cats.values) -def test_groupby_unstack_categorical(): +def test_unstack_categorical(): # GH11558 (example is taken from the original issue) df = pd.DataFrame({'a': range(10), 'medium': ['A', 'B'] * 5, 'artist': list('XYXXY') * 2}) df['medium'] = df['medium'].astype('category') - gcat = df.groupby(['artist', 'medium'])['a'].count().unstack() + gcat = df.groupby( + ['artist', 'medium'], observed=False)['a'].count().unstack() result = gcat.describe() exp_columns = pd.CategoricalIndex(['A', 'B'], ordered=False, @@ -363,7 +519,7 @@ def test_groupby_unstack_categorical(): tm.assert_series_equal(result, expected) -def test_groupby_bins_unequal_len(): +def test_bins_unequal_len(): # GH3011 series = Series([np.nan, np.nan, 1, 1, 2, 2, 3, 3, 4, 4]) bins = pd.cut(series.dropna().values, 4) @@ -374,47 +530,45 @@ def f(): pytest.raises(ValueError, f) -def test_groupby_multi_categorical_as_index(): +def test_as_index(): # GH13204 df = DataFrame({'cat': Categorical([1, 2, 2], [1, 2, 3]), 'A': [10, 11, 11], 'B': [101, 102, 103]}) - result = df.groupby(['cat', 'A'], as_index=False).sum() - expected = DataFrame({'cat': Categorical([1, 1, 2, 2, 3, 3]), - 'A': [10, 11, 10, 11, 10, 11], - 'B': [101.0, nan, nan, 205.0, nan, nan]}, - columns=['cat', 'A', 'B']) + result = df.groupby(['cat', 'A'], as_index=False, observed=True).sum() + expected = DataFrame( + {'cat': Categorical([1, 2], categories=df.cat.cat.categories), + 'A': [10, 11], + 'B': [101, 205]}, + columns=['cat', 'A', 'B']) tm.assert_frame_equal(result, expected) # function grouper f = lambda r: df.loc[r, 'A'] - result = df.groupby(['cat', f], as_index=False).sum() - expected = DataFrame({'cat': Categorical([1, 1, 2, 2, 3, 3]), - 'A': [10.0, nan, nan, 22.0, nan, nan], - 'B': [101.0, nan, nan, 205.0, nan, nan]}, - columns=['cat', 'A', 'B']) + result = df.groupby(['cat', f], as_index=False, observed=True).sum() + expected = DataFrame( + {'cat': Categorical([1, 2], categories=df.cat.cat.categories), + 'A': [10, 22], + 'B': [101, 205]}, + columns=['cat', 'A', 'B']) tm.assert_frame_equal(result, expected) # another not in-axis grouper s = Series(['a', 'b', 'b'], name='cat2') - result = df.groupby(['cat', s], as_index=False).sum() - expected = DataFrame({'cat': Categorical([1, 1, 2, 2, 3, 3]), - 'A': [10.0, nan, nan, 22.0, nan, nan], - 'B': [101.0, nan, nan, 205.0, nan, nan]}, - columns=['cat', 'A', 'B']) + result = df.groupby(['cat', s], as_index=False, observed=True).sum() tm.assert_frame_equal(result, expected) # GH18872: conflicting names in desired index - pytest.raises(ValueError, lambda: df.groupby(['cat', - s.rename('cat')]).sum()) + with pytest.raises(ValueError): + df.groupby(['cat', s.rename('cat')], observed=True).sum() # is original index dropped? - expected = DataFrame({'cat': Categorical([1, 1, 2, 2, 3, 3]), - 'A': [10, 11, 10, 11, 10, 11], - 'B': [101.0, nan, nan, 205.0, nan, nan]}, - columns=['cat', 'A', 'B']) - group_columns = ['cat', 'A'] + expected = DataFrame( + {'cat': Categorical([1, 2], categories=df.cat.cat.categories), + 'A': [10, 11], + 'B': [101, 205]}, + columns=['cat', 'A', 'B']) for name in [None, 'X', 'B', 'cat']: df.index = Index(list("abc"), name=name) @@ -422,15 +576,17 @@ def test_groupby_multi_categorical_as_index(): if name in group_columns and name in df.index.names: with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - result = df.groupby(group_columns, as_index=False).sum() + result = df.groupby( + group_columns, as_index=False, observed=True).sum() else: - result = df.groupby(group_columns, as_index=False).sum() + result = df.groupby( + group_columns, as_index=False, observed=True).sum() - tm.assert_frame_equal(result, expected, check_index_type=True) + tm.assert_frame_equal(result, expected) -def test_groupby_preserve_categories(): +def test_preserve_categories(): # GH-13179 categories = list('abc') @@ -439,8 +595,10 @@ def test_groupby_preserve_categories(): categories=categories, ordered=True)}) index = pd.CategoricalIndex(categories, categories, ordered=True) - tm.assert_index_equal(df.groupby('A', sort=True).first().index, index) - tm.assert_index_equal(df.groupby('A', sort=False).first().index, index) + tm.assert_index_equal( + df.groupby('A', sort=True, observed=False).first().index, index) + tm.assert_index_equal( + df.groupby('A', sort=False, observed=False).first().index, index) # ordered=False df = DataFrame({'A': pd.Categorical(list('ba'), @@ -449,13 +607,15 @@ def test_groupby_preserve_categories(): sort_index = pd.CategoricalIndex(categories, categories, ordered=False) nosort_index = pd.CategoricalIndex(list('bac'), list('bac'), ordered=False) - tm.assert_index_equal(df.groupby('A', sort=True).first().index, - sort_index) - tm.assert_index_equal(df.groupby('A', sort=False).first().index, - nosort_index) + tm.assert_index_equal( + df.groupby('A', sort=True, observed=False).first().index, + sort_index) + tm.assert_index_equal( + df.groupby('A', sort=False, observed=False).first().index, + nosort_index) -def test_groupby_preserve_categorical_dtype(): +def test_preserve_categorical_dtype(): # GH13743, GH13854 df = DataFrame({'A': [1, 2, 1, 1, 2], 'B': [10, 16, 22, 28, 34], @@ -475,38 +635,22 @@ def test_groupby_preserve_categorical_dtype(): categories=list("bac"), ordered=True)}) for col in ['C1', 'C2']: - result1 = df.groupby(by=col, as_index=False).mean() - result2 = df.groupby(by=col, as_index=True).mean().reset_index() - expected = exp_full.reindex(columns=result1.columns) - tm.assert_frame_equal(result1, expected) - tm.assert_frame_equal(result2, expected) - - # multiple grouper - exp_full = DataFrame({'A': [1, 1, 1, 2, 2, 2], - 'B': [np.nan, 20.0, np.nan, 25.0, np.nan, - np.nan], - 'C1': Categorical(list("bacbac"), - categories=list("bac"), - ordered=False), - 'C2': Categorical(list("bacbac"), - categories=list("bac"), - ordered=True)}) - for cols in [['A', 'C1'], ['A', 'C2']]: - result1 = df.groupby(by=cols, as_index=False).mean() - result2 = df.groupby(by=cols, as_index=True).mean().reset_index() + result1 = df.groupby(by=col, as_index=False, observed=False).mean() + result2 = df.groupby( + by=col, as_index=True, observed=False).mean().reset_index() expected = exp_full.reindex(columns=result1.columns) tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) -def test_groupby_categorical_no_compress(): +def test_categorical_no_compress(): data = Series(np.random.randn(9)) codes = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) cats = Categorical.from_codes(codes, [0, 1, 2], ordered=True) - result = data.groupby(cats).mean() - exp = data.groupby(codes).mean() + result = data.groupby(cats, observed=False).mean() + exp = data.groupby(codes, observed=False).mean() exp.index = CategoricalIndex(exp.index, categories=cats.categories, ordered=cats.ordered) @@ -515,8 +659,8 @@ def test_groupby_categorical_no_compress(): codes = np.array([0, 0, 0, 1, 1, 1, 3, 3, 3]) cats = Categorical.from_codes(codes, [0, 1, 2, 3], ordered=True) - result = data.groupby(cats).mean() - exp = data.groupby(codes).mean().reindex(cats.categories) + result = data.groupby(cats, observed=False).mean() + exp = data.groupby(codes, observed=False).mean().reindex(cats.categories) exp.index = CategoricalIndex(exp.index, categories=cats.categories, ordered=cats.ordered) assert_series_equal(result, exp) @@ -525,13 +669,34 @@ def test_groupby_categorical_no_compress(): categories=["a", "b", "c", "d"], ordered=True) data = DataFrame({"a": [1, 1, 1, 2, 2, 2, 3, 4, 5], "b": cats}) - result = data.groupby("b").mean() + result = data.groupby("b", observed=False).mean() result = result["a"].values exp = np.array([1, 2, 4, np.nan]) tm.assert_numpy_array_equal(result, exp) -def test_groupby_sort_categorical(): +def test_sort(): + + # http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby # noqa: flake8 + # This should result in a properly sorted Series so that the plot + # has a sorted x axis + # self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar') + + df = DataFrame({'value': np.random.randint(0, 10000, 100)}) + labels = ["{0} - {1}".format(i, i + 499) for i in range(0, 10000, 500)] + cat_labels = Categorical(labels, labels) + + df = df.sort_values(by=['value'], ascending=True) + df['value_group'] = pd.cut(df.value, range(0, 10500, 500), + right=False, labels=cat_labels) + + res = df.groupby(['value_group'], observed=False)['value_group'].count() + exp = res[sorted(res.index, key=lambda x: float(x.split()[0]))] + exp.index = CategoricalIndex(exp.index, name=exp.index.name) + tm.assert_series_equal(res, exp) + + +def test_sort2(): # dataframe groupby sort was being ignored # GH 8868 df = DataFrame([['(7.5, 10]', 10, 10], ['(7.5, 10]', 8, 20], @@ -543,35 +708,43 @@ def test_groupby_sort_categorical(): df['range'] = Categorical(df['range'], ordered=True) index = CategoricalIndex(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], name='range', ordered=True) - result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], - columns=['foo', 'bar'], index=index) + expected_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], + columns=['foo', 'bar'], index=index) col = 'range' - assert_frame_equal(result_sort, df.groupby(col, sort=True).first()) + result_sort = df.groupby(col, sort=True, observed=False).first() + assert_frame_equal(result_sort, expected_sort) + # when categories is ordered, group is ordered by category's order - assert_frame_equal(result_sort, df.groupby(col, sort=False).first()) + expected_sort = result_sort + result_sort = df.groupby(col, sort=False, observed=False).first() + assert_frame_equal(result_sort, expected_sort) df['range'] = Categorical(df['range'], ordered=False) index = CategoricalIndex(['(0, 2.5]', '(2.5, 5]', '(5, 7.5]', '(7.5, 10]'], name='range') - result_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], - columns=['foo', 'bar'], index=index) + expected_sort = DataFrame([[1, 60], [5, 30], [6, 40], [10, 10]], + columns=['foo', 'bar'], index=index) index = CategoricalIndex(['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], categories=['(7.5, 10]', '(2.5, 5]', '(5, 7.5]', '(0, 2.5]'], name='range') - result_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], - index=index, columns=['foo', 'bar']) + expected_nosort = DataFrame([[10, 10], [5, 30], [6, 40], [1, 60]], + index=index, columns=['foo', 'bar']) col = 'range' + # this is an unordered categorical, but we allow this #### - assert_frame_equal(result_sort, df.groupby(col, sort=True).first()) - assert_frame_equal(result_nosort, df.groupby(col, sort=False).first()) + result_sort = df.groupby(col, sort=True, observed=False).first() + assert_frame_equal(result_sort, expected_sort) + + result_nosort = df.groupby(col, sort=False, observed=False).first() + assert_frame_equal(result_nosort, expected_nosort) -def test_groupby_sort_categorical_datetimelike(): +def test_sort_datetimelike(): # GH10505 # use same data as test_groupby_sort_categorical, which category is @@ -600,9 +773,12 @@ def test_groupby_sort_categorical_datetimelike(): name='dt', ordered=True) col = 'dt' - assert_frame_equal(result_sort, df.groupby(col, sort=True).first()) + assert_frame_equal( + result_sort, df.groupby(col, sort=True, observed=False).first()) + # when categories is ordered, group is ordered by category's order - assert_frame_equal(result_sort, df.groupby(col, sort=False).first()) + assert_frame_equal( + result_sort, df.groupby(col, sort=False, observed=False).first()) # ordered = False df['dt'] = Categorical(df['dt'], ordered=False) @@ -620,65 +796,10 @@ def test_groupby_sort_categorical_datetimelike(): name='dt') col = 'dt' - assert_frame_equal(result_sort, df.groupby(col, sort=True).first()) - assert_frame_equal(result_nosort, df.groupby(col, sort=False).first()) - - -def test_groupby_categorical_two_columns(): - - # https://github.com/pandas-dev/pandas/issues/8138 - d = {'cat': - pd.Categorical(["a", "b", "a", "b"], categories=["a", "b", "c"], - ordered=True), - 'ints': [1, 1, 2, 2], - 'val': [10, 20, 30, 40]} - test = pd.DataFrame(d) - - # Grouping on a single column - groups_single_key = test.groupby("cat") - res = groups_single_key.agg('mean') - - exp_index = pd.CategoricalIndex(["a", "b", "c"], name="cat", - ordered=True) - exp = DataFrame({"ints": [1.5, 1.5, np.nan], "val": [20, 30, np.nan]}, - index=exp_index) - tm.assert_frame_equal(res, exp) - - # Grouping on two columns - groups_double_key = test.groupby(["cat", "ints"]) - res = groups_double_key.agg('mean') - exp = DataFrame({"val": [10, 30, 20, 40, np.nan, np.nan], - "cat": pd.Categorical(["a", "a", "b", "b", "c", "c"], - ordered=True), - "ints": [1, 2, 1, 2, 1, 2]}).set_index(["cat", "ints" - ]) - tm.assert_frame_equal(res, exp) - - # GH 10132 - for key in [('a', 1), ('b', 2), ('b', 1), ('a', 2)]: - c, i = key - result = groups_double_key.get_group(key) - expected = test[(test.cat == c) & (test.ints == i)] - assert_frame_equal(result, expected) - - d = {'C1': [3, 3, 4, 5], 'C2': [1, 2, 3, 4], 'C3': [10, 100, 200, 34]} - test = pd.DataFrame(d) - values = pd.cut(test['C1'], [1, 2, 3, 6]) - values.name = "cat" - groups_double_key = test.groupby([values, 'C2']) - - res = groups_double_key.agg('mean') - nan = np.nan - idx = MultiIndex.from_product( - [Categorical([Interval(1, 2), Interval(2, 3), - Interval(3, 6)], ordered=True), - [1, 2, 3, 4]], - names=["cat", "C2"]) - exp = DataFrame({"C1": [nan, nan, nan, nan, 3, 3, - nan, nan, nan, nan, 4, 5], - "C3": [nan, nan, nan, nan, 10, 100, - nan, nan, nan, nan, 200, 34]}, index=idx) - tm.assert_frame_equal(res, exp) + assert_frame_equal( + result_sort, df.groupby(col, sort=True, observed=False).first()) + assert_frame_equal( + result_nosort, df.groupby(col, sort=False, observed=False).first()) def test_empty_sum(): @@ -689,22 +810,22 @@ def test_empty_sum(): expected_idx = pd.CategoricalIndex(['a', 'b', 'c'], name='A') # 0 by default - result = df.groupby("A").B.sum() + result = df.groupby("A", observed=False).B.sum() expected = pd.Series([3, 1, 0], expected_idx, name='B') tm.assert_series_equal(result, expected) # min_count=0 - result = df.groupby("A").B.sum(min_count=0) + result = df.groupby("A", observed=False).B.sum(min_count=0) expected = pd.Series([3, 1, 0], expected_idx, name='B') tm.assert_series_equal(result, expected) # min_count=1 - result = df.groupby("A").B.sum(min_count=1) + result = df.groupby("A", observed=False).B.sum(min_count=1) expected = pd.Series([3, 1, np.nan], expected_idx, name='B') tm.assert_series_equal(result, expected) # min_count>1 - result = df.groupby("A").B.sum(min_count=2) + result = df.groupby("A", observed=False).B.sum(min_count=2) expected = pd.Series([3, np.nan, np.nan], expected_idx, name='B') tm.assert_series_equal(result, expected) @@ -718,16 +839,16 @@ def test_empty_prod(): expected_idx = pd.CategoricalIndex(['a', 'b', 'c'], name='A') # 1 by default - result = df.groupby("A").B.prod() + result = df.groupby("A", observed=False).B.prod() expected = pd.Series([2, 1, 1], expected_idx, name='B') tm.assert_series_equal(result, expected) # min_count=0 - result = df.groupby("A").B.prod(min_count=0) + result = df.groupby("A", observed=False).B.prod(min_count=0) expected = pd.Series([2, 1, 1], expected_idx, name='B') tm.assert_series_equal(result, expected) # min_count=1 - result = df.groupby("A").B.prod(min_count=1) + result = df.groupby("A", observed=False).B.prod(min_count=1) expected = pd.Series([2, 1, np.nan], expected_idx, name='B') tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index ba1371fe9f931..f1d678db4ff7f 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -313,14 +313,14 @@ def test_cython_median(): tm.assert_frame_equal(rs, xp) -def test_median_empty_bins(): +def test_median_empty_bins(observed): df = pd.DataFrame(np.random.randint(0, 44, 500)) grps = range(0, 55, 5) bins = pd.cut(df[0], grps) - result = df.groupby(bins).median() - expected = df.groupby(bins).agg(lambda x: x.median()) + result = df.groupby(bins, observed=observed).median() + expected = df.groupby(bins, observed=observed).agg(lambda x: x.median()) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 743237f5b386c..c0f5c43b2fd35 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -251,7 +251,7 @@ def test_groupby_levels_and_columns(self): by_columns.columns = pd.Index(by_columns.columns, dtype=np.int64) tm.assert_frame_equal(by_levels, by_columns) - def test_groupby_categorical_index_and_columns(self): + def test_groupby_categorical_index_and_columns(self, observed): # GH18432 columns = ['A', 'B', 'A', 'B'] categories = ['B', 'A'] @@ -260,17 +260,26 @@ def test_groupby_categorical_index_and_columns(self): categories=categories, ordered=True) df = DataFrame(data=data, columns=cat_columns) - result = df.groupby(axis=1, level=0).sum() + result = df.groupby(axis=1, level=0, observed=observed).sum() expected_data = 2 * np.ones((5, 2), int) - expected_columns = CategoricalIndex(categories, - categories=categories, - ordered=True) + + if observed: + # if we are not-observed we undergo a reindex + # so need to adjust the output as our expected sets us up + # to be non-observed + expected_columns = CategoricalIndex(['A', 'B'], + categories=categories, + ordered=True) + else: + expected_columns = CategoricalIndex(categories, + categories=categories, + ordered=True) expected = DataFrame(data=expected_data, columns=expected_columns) assert_frame_equal(result, expected) # test transposed version df = DataFrame(data.T, index=cat_columns) - result = df.groupby(axis=0, level=0).sum() + result = df.groupby(axis=0, level=0, observed=observed).sum() expected = DataFrame(data=expected_data.T, index=expected_columns) assert_frame_equal(result, expected) @@ -572,11 +581,11 @@ def test_get_group(self): pytest.raises(ValueError, lambda: g.get_group(('foo', 'bar', 'baz'))) - def test_get_group_empty_bins(self): + def test_get_group_empty_bins(self, observed): d = pd.DataFrame([3, 1, 7, 6]) bins = [0, 5, 10, 15] - g = d.groupby(pd.cut(d[0], bins)) + g = d.groupby(pd.cut(d[0], bins), observed=observed) # TODO: should prob allow a str of Interval work as well # IOW '(0, 5]' diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 1004b40bfb4c1..76cdc1d2a195d 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -93,23 +93,24 @@ def test_pivot_table_dropna(self): def test_pivot_table_categorical(self): - raw_cat1 = Categorical(["a", "a", "b", "b"], - categories=["a", "b", "z"], ordered=True) - raw_cat2 = Categorical(["c", "d", "c", "d"], - categories=["c", "d", "y"], ordered=True) - df = DataFrame({"A": raw_cat1, "B": raw_cat2, "values": [1, 2, 3, 4]}) - result = pd.pivot_table(df, values='values', index=['A', 'B']) - - exp_index = pd.MultiIndex.from_product( - [Categorical(["a", "b", "z"], ordered=True), - Categorical(["c", "d", "y"], ordered=True)], + cat1 = Categorical(["a", "a", "b", "b"], + categories=["a", "b", "z"], ordered=True) + cat2 = Categorical(["c", "d", "c", "d"], + categories=["c", "d", "y"], ordered=True) + df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) + result = pd.pivot_table(df, values='values', index=['A', 'B'], + dropna=True) + + exp_index = pd.MultiIndex.from_arrays( + [cat1, cat2], names=['A', 'B']) expected = DataFrame( - {'values': [1, 2, np.nan, 3, 4, np.nan, np.nan, np.nan, np.nan]}, + {'values': [1, 2, 3, 4]}, index=exp_index) tm.assert_frame_equal(result, expected) - def test_pivot_table_dropna_categoricals(self): + @pytest.mark.parametrize('dropna', [True, False]) + def test_pivot_table_dropna_categoricals(self, dropna): # GH 15193 categories = ['a', 'b', 'c', 'd'] @@ -118,30 +119,23 @@ def test_pivot_table_dropna_categoricals(self): 'C': range(0, 9)}) df['A'] = df['A'].astype(CDT(categories, ordered=False)) - result_true = df.pivot_table(index='B', columns='A', values='C', - dropna=True) + result = df.pivot_table(index='B', columns='A', values='C', + dropna=dropna) expected_columns = Series(['a', 'b', 'c'], name='A') expected_columns = expected_columns.astype( CDT(categories, ordered=False)) expected_index = Series([1, 2, 3], name='B') - expected_true = DataFrame([[0.0, 3.0, 6.0], - [1.0, 4.0, 7.0], - [2.0, 5.0, 8.0]], - index=expected_index, - columns=expected_columns,) - tm.assert_frame_equal(expected_true, result_true) - - result_false = df.pivot_table(index='B', columns='A', values='C', - dropna=False) - expected_columns = ( - Series(['a', 'b', 'c', 'd'], name='A').astype('category') - ) - expected_false = DataFrame([[0.0, 3.0, 6.0, np.NaN], - [1.0, 4.0, 7.0, np.NaN], - [2.0, 5.0, 8.0, np.NaN]], - index=expected_index, - columns=expected_columns,) - tm.assert_frame_equal(expected_false, result_false) + expected = DataFrame([[0, 3, 6], + [1, 4, 7], + [2, 5, 8]], + index=expected_index, + columns=expected_columns,) + if not dropna: + # add back the non observed to compare + expected = expected.reindex( + columns=Categorical(categories)).astype('float') + + tm.assert_frame_equal(result, expected) def test_pass_array(self): result = self.data.pivot_table( @@ -1068,7 +1062,7 @@ def test_pivot_table_margins_name_with_aggfunc_list(self): @pytest.mark.xfail(reason='GH 17035 (np.mean of ints is casted back to ' 'ints)') - def test_categorical_margins(self): + def test_categorical_margins(self, observed): # GH 10989 df = pd.DataFrame({'x': np.arange(8), 'y': np.arange(8) // 4, @@ -1078,12 +1072,12 @@ def test_categorical_margins(self): expected.index = Index([0, 1, 'All'], name='y') expected.columns = Index([0, 1, 'All'], name='z') - table = df.pivot_table('x', 'y', 'z', margins=True) + table = df.pivot_table('x', 'y', 'z', dropna=observed, margins=True) tm.assert_frame_equal(table, expected) @pytest.mark.xfail(reason='GH 17035 (np.mean of ints is casted back to ' 'ints)') - def test_categorical_margins_category(self): + def test_categorical_margins_category(self, observed): df = pd.DataFrame({'x': np.arange(8), 'y': np.arange(8) // 4, 'z': np.arange(8) % 2}) @@ -1094,16 +1088,17 @@ def test_categorical_margins_category(self): df.y = df.y.astype('category') df.z = df.z.astype('category') - table = df.pivot_table('x', 'y', 'z', margins=True) + table = df.pivot_table('x', 'y', 'z', dropna=observed, margins=True) tm.assert_frame_equal(table, expected) - def test_categorical_aggfunc(self): + def test_categorical_aggfunc(self, observed): # GH 9534 df = pd.DataFrame({"C1": ["A", "B", "C", "C"], "C2": ["a", "a", "b", "b"], "V": [1, 2, 3, 4]}) df["C1"] = df["C1"].astype("category") - result = df.pivot_table("V", index="C1", columns="C2", aggfunc="count") + result = df.pivot_table("V", index="C1", columns="C2", + dropna=observed, aggfunc="count") expected_index = pd.CategoricalIndex(['A', 'B', 'C'], categories=['A', 'B', 'C'], @@ -1118,7 +1113,7 @@ def test_categorical_aggfunc(self): columns=expected_columns) tm.assert_frame_equal(result, expected) - def test_categorical_pivot_index_ordering(self): + def test_categorical_pivot_index_ordering(self, observed): # GH 8731 df = pd.DataFrame({'Sales': [100, 120, 220], 'Month': ['January', 'January', 'January'], @@ -1130,18 +1125,19 @@ def test_categorical_pivot_index_ordering(self): result = df.pivot_table(values='Sales', index='Month', columns='Year', + dropna=observed, aggfunc='sum') expected_columns = pd.Int64Index([2013, 2014], name='Year') - expected_index = pd.CategoricalIndex(months, + expected_index = pd.CategoricalIndex(['January'], categories=months, ordered=False, name='Month') - expected_data = np.empty((12, 2)) - expected_data.fill(np.nan) - expected_data[0, :] = [320., 120.] - expected = pd.DataFrame(expected_data, + expected = pd.DataFrame([[320, 120]], index=expected_index, columns=expected_columns) + if not observed: + result = result.dropna().astype(np.int64) + tm.assert_frame_equal(result, expected) def test_pivot_table_not_series(self):
closes #14942 closes #15217 closes #17594 closes #8869 xref #8138
https://api.github.com/repos/pandas-dev/pandas/pulls/20583
2018-04-02T14:06:17Z
2018-05-01T15:09:11Z
2018-05-01T15:09:10Z
2019-01-30T17:44:14Z
TST: add tests for take() on empty arrays
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index c281bd80cb274..d49a0d799526a 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -458,11 +458,23 @@ def take(self, indexer, allow_fill=True, fill_value=None): Fill value to replace -1 values with. If applicable, this should use the sentinel missing value for this type. + Returns + ------- + ExtensionArray + + Raises + ------ + IndexError + When the indexer is out of bounds for the array. + Notes ----- This should follow pandas' semantics where -1 indicates missing values. Positions where indexer is ``-1`` should be filled with the missing value for this type. + This gives rise to the special case of a take on an empty + ExtensionArray that does not raises an IndexError straight away + when the `indexer` is all ``-1``. This is called by ``Series.__getitem__``, ``.loc``, ``iloc``, when the indexer is a sequence of values. @@ -477,6 +489,12 @@ def take(self, indexer, allow_fill=True, fill_value=None): def take(self, indexer, allow_fill=True, fill_value=None): indexer = np.asarray(indexer) mask = indexer == -1 + + # take on empty array not handled as desired by numpy + # in case of -1 (all missing take) + if not len(self) and mask.all(): + return type(self)([np.nan] * len(indexer)) + result = self.data.take(indexer) result[mask] = np.nan # NA for this type return type(self)(result) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 566ba1721d13c..4e2a65eba06dc 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -1,6 +1,8 @@ +import pytest import numpy as np import pandas as pd +import pandas.util.testing as tm from .base import BaseExtensionTests @@ -120,3 +122,48 @@ def test_take_sequence(self, data): assert result.iloc[0] == data[0] assert result.iloc[1] == data[1] assert result.iloc[2] == data[3] + + def test_take(self, data, na_value, na_cmp): + result = data.take([0, -1]) + assert result.dtype == data.dtype + assert result[0] == data[0] + na_cmp(result[1], na_value) + + with tm.assert_raises_regex(IndexError, "out of bounds"): + data.take([len(data) + 1]) + + def test_take_empty(self, data, na_value, na_cmp): + empty = data[:0] + result = empty.take([-1]) + na_cmp(result[0], na_value) + + with tm.assert_raises_regex(IndexError, "cannot do a non-empty take"): + empty.take([0, 1]) + + @pytest.mark.xfail(reason="Series.take with extension array buggy for -1") + def test_take_series(self, data): + s = pd.Series(data) + result = s.take([0, -1]) + expected = pd.Series( + data._constructor_from_sequence([data[0], data[len(data) - 1]]), + index=[0, len(data) - 1]) + self.assert_series_equal(result, expected) + + def test_reindex(self, data, na_value): + s = pd.Series(data) + result = s.reindex([0, 1, 3]) + expected = pd.Series(data.take([0, 1, 3]), index=[0, 1, 3]) + self.assert_series_equal(result, expected) + + n = len(data) + result = s.reindex([-1, 0, n]) + expected = pd.Series( + data._constructor_from_sequence([na_value, data[0], na_value]), + index=[-1, 0, n]) + self.assert_series_equal(result, expected) + + result = s.reindex([n, n + 1]) + expected = pd.Series( + data._constructor_from_sequence([na_value, na_value]), + index=[n, n + 1]) + self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index 6abf1f7f9a65a..27c156c15203f 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -84,6 +84,19 @@ def test_getitem_scalar(self): # to break things by changing. pass + @pytest.mark.xfail(reason="Categorical.take buggy") + def test_take(self): + # TODO remove this once Categorical.take is fixed + pass + + @pytest.mark.xfail(reason="Categorical.take buggy") + def test_take_empty(self): + pass + + @pytest.mark.xfail(reason="test not written correctly for categorical") + def test_reindex(self): + pass + class TestSetitem(base.BaseSetitemTests): pass diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index f93d11f579f11..a8e88365b5648 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -81,6 +81,10 @@ def take(self, indexer, allow_fill=True, fill_value=None): indexer = np.asarray(indexer) mask = indexer == -1 + # take on empty array not handled as desired by numpy in case of -1 + if not len(self) and mask.all(): + return type(self)([self._na_value] * len(indexer)) + indexer = _ensure_platform_int(indexer) out = self.values.take(indexer) out[mask] = self._na_value diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index d9ae49d87804a..33843492cb706 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -89,8 +89,12 @@ def isna(self): return np.array([x == self._na_value for x in self.data]) def take(self, indexer, allow_fill=True, fill_value=None): - output = [self.data[loc] if loc != -1 else self._na_value - for loc in indexer] + try: + output = [self.data[loc] if loc != -1 else self._na_value + for loc in indexer] + except IndexError: + raise IndexError("Index is out of bounds or cannot do a " + "non-empty take from an empty array.") return self._constructor_from_sequence(output) def copy(self, deep=False):
Another noticed during geopandas testing: `ExtensionArray.take` needs to be able to handle the case where it is empty. Added a example implementation for Decimal/JSONArray. And apparently, this was also failing for Categorical, so fixed that as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/20582
2018-04-02T12:48:48Z
2018-04-17T07:53:32Z
2018-04-17T07:53:32Z
2018-04-17T07:53:36Z
BUG: Series[EA].astype(str) works
diff --git a/pandas/core/internals.py b/pandas/core/internals.py index b0a6086c450ef..e8fab3748bacf 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -655,7 +655,7 @@ def _astype(self, dtype, copy=False, errors='raise', values=None, # astype formatting else: - values = self.values + values = self.get_values() else: values = self.get_values(dtype=dtype) diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index 74fe8f196a089..7146443bf8de5 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -16,3 +16,8 @@ def test_tolist(self, data): result = pd.Series(data).tolist() expected = list(data) assert result == expected + + def test_astype_str(self, data): + result = pd.Series(data[:5]).astype(str) + expected = pd.Series(data[:5].astype(str)) + self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 5e9639c487c37..87668cc1196b6 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -127,7 +127,12 @@ def test_sort_values_missing(self, data_missing_for_sorting, ascending): class TestCasting(base.BaseCastingTests): - pass + @pytest.mark.xfail + def test_astype_str(self): + """This currently fails in NumPy on np.array(self, dtype=str) with + + *** ValueError: setting an array element with a sequence + """ class TestGroupby(base.BaseGroupbyTests):
Closes https://github.com/pandas-dev/pandas/issues/20578 cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/20581
2018-04-02T11:37:09Z
2018-04-03T06:32:08Z
2018-04-03T06:32:07Z
2018-04-03T06:32:14Z
BUG: Fixed Series.align(frame) with ExtensionArray
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index d19f19b7224a7..75434fcc2b40d 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -12,6 +12,7 @@ is_complex, is_datetimetz, is_categorical_dtype, is_datetimelike, is_extension_type, + is_extension_array_dtype, is_object_dtype, is_datetime64tz_dtype, is_datetime64_dtype, is_datetime64_ns_dtype, @@ -329,7 +330,7 @@ def maybe_promote(dtype, fill_value=np.nan): dtype = np.object_ # in case we have a string that looked like a number - if is_categorical_dtype(dtype): + if is_extension_array_dtype(dtype): pass elif is_datetimetz(dtype): pass diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index 6f4d5b40515be..efc22c19a3eef 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -1,4 +1,5 @@ import pytest +import numpy as np import pandas as pd from pandas.core.internals import ExtensionBlock @@ -64,6 +65,19 @@ def test_align_frame(self, data, na_value): self.assert_frame_equal(r1, e1) self.assert_frame_equal(r2, e2) + def test_align_series_frame(self, data, na_value): + # https://github.com/pandas-dev/pandas/issues/20576 + ser = pd.Series(data, name='a') + df = pd.DataFrame({"col": np.arange(len(ser) + 1)}) + r1, r2 = ser.align(df) + + e1 = pd.Series( + data._constructor_from_sequence(list(data) + [na_value]), + name=ser.name) + + self.assert_series_equal(r1, e1) + self.assert_frame_equal(r2, df) + def test_set_frame_expand_regular_with_extension(self, data): df = pd.DataFrame({"A": [1] * len(data)}) df['B'] = data
Closes https://github.com/pandas-dev/pandas/issues/20576 cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/20580
2018-04-02T11:11:59Z
2018-04-03T06:33:35Z
2018-04-03T06:33:35Z
2018-04-03T06:33:35Z
TST: remove skip for values/index length mismatch in ExtensionArray tests
diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py index 4ac04d71338fd..5ac3a84517fe9 100644 --- a/pandas/tests/extension/base/constructors.py +++ b/pandas/tests/extension/base/constructors.py @@ -41,10 +41,7 @@ def test_dataframe_from_series(self, data): assert result.shape == (len(data), 1) assert isinstance(result._data.blocks[0], ExtensionBlock) - @pytest.mark.xfail(reason="GH-19342") def test_series_given_mismatched_index_raises(self, data): - msg = 'Wrong number of items passed 3, placement implies 4' - with tm.assert_raises_regex(ValueError, None) as m: + msg = 'Length of passed values is 3, index implies 5' + with tm.assert_raises_regex(ValueError, msg): pd.Series(data[:3], index=[0, 1, 2, 3, 4]) - - assert m.match(msg)
https://github.com/pandas-dev/pandas/issues/19342 is fixed in the meantime
https://api.github.com/repos/pandas-dev/pandas/pulls/20577
2018-04-02T09:54:01Z
2018-04-02T13:35:29Z
2018-04-02T13:35:29Z
2018-04-03T21:02:15Z
Adding test_map_missing_mixed to test_apply.py in pandas test suite series
diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index 0780c846a6c19..b28b9f342695f 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -576,3 +576,14 @@ def f(x): result = s.map(f) exp = pd.Series(['Asia/Tokyo'] * 25, name='XX') tm.assert_series_equal(result, exp) + + @pytest.mark.parametrize("vals,mapping,exp", [ + (list('abc'), {np.nan: 'not NaN'}, [np.nan] * 3 + ['not NaN']), + (list('abc'), {'a': 'a letter'}, ['a letter'] + [np.nan] * 3), + (list(range(3)), {0: 42}, [42] + [np.nan] * 3)]) + def test_map_missing_mixed(self, vals, mapping, exp): + # GH20495 + s = pd.Series(vals + [np.nan]) + result = s.map(mapping) + + tm.assert_series_equal(result, pd.Series(exp))
Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [x] closes #20495 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry (n/a)
https://api.github.com/repos/pandas-dev/pandas/pulls/20574
2018-04-02T04:22:32Z
2018-04-03T19:22:12Z
2018-04-03T19:22:11Z
2018-04-03T19:22:17Z
BUG: .unique() on MultiIndex: preserve names
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index ce63cb2473bc4..1f477c4f18811 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1069,6 +1069,8 @@ MultiIndex - Bug in :func:`MultiIndex.__contains__` where non-tuple keys would return ``True`` even if they had been dropped (:issue:`19027`) - Bug in :func:`MultiIndex.set_labels` which would cause casting (and potentially clipping) of the new labels if the ``level`` argument is not 0 or a list like [0, 1, ... ] (:issue:`19057`) - Bug in :func:`MultiIndex.get_level_values` which would return an invalid index on level of ints with missing values (:issue:`17924`) +- Bug in :func:`MultiIndex.unique` when called on empty :class:`MultiIndex` (:issue:`20568`) +- Bug in :func:`MultiIndex.unique` which would not preserve level names (:issue:`20570`) - Bug in :func:`MultiIndex.remove_unused_levels` which would fill nan values (:issue:`18417`) - Bug in :func:`MultiIndex.from_tuples` which would fail to take zipped tuples in python3 (:issue:`18434`) - Bug in :func:`MultiIndex.get_loc` which would fail to automatically cast values between float and int (:issue:`18818`, :issue:`15994`) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 8226c4bcac494..d4b9545999bc7 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -553,11 +553,10 @@ def __contains__(self, key): @Appender(_index_shared_docs['_shallow_copy']) def _shallow_copy(self, values=None, **kwargs): if values is not None: - if 'name' in kwargs: - kwargs['names'] = kwargs.pop('name', None) + names = kwargs.pop('names', kwargs.pop('name', self.names)) # discards freq kwargs.pop('freq', None) - return MultiIndex.from_tuples(values, **kwargs) + return MultiIndex.from_tuples(values, names=names, **kwargs) return self.view() @cache_readonly diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 34abf7052da8c..984f37042d600 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -2452,23 +2452,33 @@ def test_get_unique_index(self): assert result.unique tm.assert_index_equal(result, expected) - def test_unique(self): - mi = pd.MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]]) + @pytest.mark.parametrize('names', [None, ['first', 'second']]) + def test_unique(self, names): + mi = pd.MultiIndex.from_arrays([[1, 2, 1, 2], [1, 1, 1, 2]], + names=names) res = mi.unique() - exp = pd.MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]]) + exp = pd.MultiIndex.from_arrays([[1, 2, 2], [1, 1, 2]], names=mi.names) tm.assert_index_equal(res, exp) - mi = pd.MultiIndex.from_arrays([list('aaaa'), list('abab')]) + mi = pd.MultiIndex.from_arrays([list('aaaa'), list('abab')], + names=names) res = mi.unique() - exp = pd.MultiIndex.from_arrays([list('aa'), list('ab')]) + exp = pd.MultiIndex.from_arrays([list('aa'), list('ab')], + names=mi.names) tm.assert_index_equal(res, exp) - mi = pd.MultiIndex.from_arrays([list('aaaa'), list('aaaa')]) + mi = pd.MultiIndex.from_arrays([list('aaaa'), list('aaaa')], + names=names) res = mi.unique() - exp = pd.MultiIndex.from_arrays([['a'], ['a']]) + exp = pd.MultiIndex.from_arrays([['a'], ['a']], names=mi.names) tm.assert_index_equal(res, exp) + # GH #20568 - empty MI + mi = pd.MultiIndex.from_arrays([[], []], names=names) + res = mi.unique() + tm.assert_index_equal(mi, res) + @pytest.mark.parametrize('level', [0, 'first', 1, 'second']) def test_unique_level(self, level): # GH #17896 - with level= argument @@ -2483,6 +2493,11 @@ def test_unique_level(self, level): expected = mi.get_level_values(level) tm.assert_index_equal(result, expected) + # With empty MI + mi = pd.MultiIndex.from_arrays([[], []], names=['first', 'second']) + result = mi.unique(level=level) + expected = mi.get_level_values(level) + def test_unique_datetimelike(self): idx1 = pd.DatetimeIndex(['2015-01-01', '2015-01-01', '2015-01-01', '2015-01-01', 'NaT', 'NaT'])
- [x] closes #20308 - [x] closes #20570 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20571
2018-03-31T22:25:04Z
2018-04-01T15:49:57Z
2018-04-01T15:49:56Z
2018-04-01T15:50:27Z
BUG: Fix first_last_valid_index, now preserves the frequency.
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index ce63cb2473bc4..1f5948649c5e2 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1061,7 +1061,7 @@ Indexing - Bug in :meth:`DataFrame.drop_duplicates` where no ``KeyError`` is raised when passing in columns that don't exist on the ``DataFrame`` (issue:`19726`) - Bug in ``Index`` subclasses constructors that ignore unexpected keyword arguments (:issue:`19348`) - Bug in :meth:`Index.difference` when taking difference of an ``Index`` with itself (:issue:`20040`) - +- Bug in :meth:`DataFrame.first_valid_index` and :meth:`DataFrame.last_valid_index` in presence of entire rows of NaNs in the middle of values (:issue:`20499`). MultiIndex ^^^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9626079660771..35f3a7c20e270 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5015,31 +5015,6 @@ def update(self, other, join='left', overwrite=True, filter_func=None, self[col] = expressions.where(mask, this, that) - # ---------------------------------------------------------------------- - # Misc methods - - def _get_valid_indices(self): - is_valid = self.count(1) > 0 - return self.index[is_valid] - - @Appender(_shared_docs['valid_index'] % { - 'position': 'first', 'klass': 'DataFrame'}) - def first_valid_index(self): - if len(self) == 0: - return None - - valid_indices = self._get_valid_indices() - return valid_indices[0] if len(valid_indices) else None - - @Appender(_shared_docs['valid_index'] % { - 'position': 'last', 'klass': 'DataFrame'}) - def last_valid_index(self): - if len(self) == 0: - return None - - valid_indices = self._get_valid_indices() - return valid_indices[-1] if len(valid_indices) else None - # ---------------------------------------------------------------------- # Data reshaping diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d5cd22732f0a9..1931875799c73 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8763,6 +8763,51 @@ def transform(self, func, *args, **kwargs): scalar : type of index """ + def _find_valid_index(self, how): + """Retrieves the index of the first valid value. + + Parameters + ---------- + how : {'first', 'last'} + Use this parameter to change between the first or last valid index. + + Returns + ------- + idx_first_valid : type of index + """ + assert how in ['first', 'last'] + + if len(self) == 0: # early stop + return None + is_valid = ~self.isna() + + if self.ndim == 2: + is_valid = is_valid.any(1) # reduce axis 1 + + if how == 'first': + # First valid value case + i = is_valid.idxmax() + if not is_valid[i]: + return None + return i + + elif how == 'last': + # Last valid value case + i = is_valid.values[::-1].argmax() + if not is_valid.iat[len(self) - i - 1]: + return None + return self.index[len(self) - i - 1] + + @Appender(_shared_docs['valid_index'] % {'position': 'first', + 'klass': 'NDFrame'}) + def first_valid_index(self): + return self._find_valid_index('first') + + @Appender(_shared_docs['valid_index'] % {'position': 'last', + 'klass': 'NDFrame'}) + def last_valid_index(self): + return self._find_valid_index('last') + def _doc_parms(cls): """Return a tuple of the doc parms.""" diff --git a/pandas/core/series.py b/pandas/core/series.py index f3630dc43fbd1..808ac5e721fc8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3887,32 +3887,6 @@ def valid(self, inplace=False, **kwargs): "Use .dropna instead.", FutureWarning, stacklevel=2) return self.dropna(inplace=inplace, **kwargs) - @Appender(generic._shared_docs['valid_index'] % { - 'position': 'first', 'klass': 'Series'}) - def first_valid_index(self): - if len(self) == 0: - return None - - mask = isna(self._values) - i = mask.argmin() - if mask[i]: - return None - else: - return self.index[i] - - @Appender(generic._shared_docs['valid_index'] % { - 'position': 'last', 'klass': 'Series'}) - def last_valid_index(self): - if len(self) == 0: - return None - - mask = isna(self._values[::-1]) - i = mask.argmin() - if mask[i]: - return None - else: - return self.index[len(self) - i - 1] - # ---------------------------------------------------------------------- # Time series-oriented methods diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index ceb6c942c81b1..277c3c9bc5c23 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -530,6 +530,15 @@ def test_first_last_valid(self): assert frame.last_valid_index() is None assert frame.first_valid_index() is None + # GH20499: its preserves freq with holes + frame.index = date_range("20110101", periods=N, freq="B") + frame.iloc[1] = 1 + frame.iloc[-2] = 1 + assert frame.first_valid_index() == frame.index[1] + assert frame.last_valid_index() == frame.index[-2] + assert frame.first_valid_index().freq == frame.index.freq + assert frame.last_valid_index().freq == frame.index.freq + def test_at_time_frame(self): rng = date_range('1/1/2000', '1/5/2000', freq='5min') ts = DataFrame(np.random.randn(len(rng), 2), index=rng) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index baf2619c7b022..8e537b137baaf 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -432,6 +432,15 @@ def test_first_last_valid(self): assert empty.last_valid_index() is None assert empty.first_valid_index() is None + # GH20499: its preserves freq with holes + ts.index = date_range("20110101", periods=len(ts), freq="B") + ts.iloc[1] = 1 + ts.iloc[-2] = 1 + assert ts.first_valid_index() == ts.index[1] + assert ts.last_valid_index() == ts.index[-2] + assert ts.first_valid_index().freq == ts.index.freq + assert ts.last_valid_index().freq == ts.index.freq + def test_mpl_compat_hack(self): result = self.ts[:, np.newaxis] expected = self.ts.values[:, np.newaxis]
Checklist - [X] closes #20499 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry I'm not sure if I should add a test somewhere else. Notice that I've added a new function [`_find_first_valid`](https://github.com/mmngreco/pandas/blob/ff8d3964cba04ed08f9f3b0dee3ee5c7514b5ed7/pandas/core/generic.py#L8766-L8785).
https://api.github.com/repos/pandas-dev/pandas/pulls/20569
2018-03-31T16:35:04Z
2018-04-01T13:40:21Z
2018-04-01T13:40:20Z
2018-04-18T07:20:58Z
TST: xfail matmul under numpy < 1.12
diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index f9f079cb21858..430c571aab0a4 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -90,7 +90,7 @@ def test_factorize(self, data_for_grouping, na_sentinel): na_sentinel=na_sentinel) expected_labels = np.array([0, 0, na_sentinel, na_sentinel, 1, 1, 0, 2], - dtype='int64') + dtype=np.intp) expected_uniques = data_for_grouping.take([0, 4, 7]) tm.assert_numpy_array_equal(labels, expected_labels) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 7949636fcafbb..2763fcc2183d2 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -17,7 +17,7 @@ from pandas.compat import lrange, product, PY35 from pandas import (compat, isna, notna, DataFrame, Series, MultiIndex, date_range, Timestamp, Categorical, - _np_version_under1p15) + _np_version_under1p12, _np_version_under1p15) import pandas as pd import pandas.core.nanops as nanops import pandas.core.algorithms as algorithms @@ -2146,6 +2146,9 @@ def test_dot(self): @pytest.mark.skipif(not PY35, reason='matmul supported for Python>=3.5') + @pytest.mark.xfail( + _np_version_under1p12, + reason="unpredictable return types under numpy < 1.12") def test_matmul(self): # matmul test is for GH #10259 a = DataFrame(np.random.randn(3, 4), index=['a', 'b', 'c'],
https://api.github.com/repos/pandas-dev/pandas/pulls/20567
2018-03-31T15:43:48Z
2018-03-31T16:37:32Z
2018-03-31T16:37:32Z
2018-03-31T16:37:32Z
ENH/DOC: update pandas-gbq signature and docstring
diff --git a/doc/source/conf.py b/doc/source/conf.py index 43c7c23c5e20d..965b537c15ce5 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -350,6 +350,7 @@ intersphinx_mapping = { 'statsmodels': ('http://www.statsmodels.org/devel/', None), 'matplotlib': ('http://matplotlib.org/', None), + 'pandas-gbq': ('https://pandas-gbq.readthedocs.io/en/latest/', None), 'python': ('https://docs.python.org/3/', None), 'numpy': ('https://docs.scipy.org/doc/numpy/', None), 'scipy': ('https://docs.scipy.org/doc/scipy/reference/', None), diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index ce63cb2473bc4..4f05a6f108add 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -404,7 +404,10 @@ Other Enhancements - :func:`read_html` now accepts a ``displayed_only`` keyword argument to controls whether or not hidden elements are parsed (``True`` by default) (:issue:`20027`) - zip compression is supported via ``compression=zip`` in :func:`DataFrame.to_pickle`, :func:`Series.to_pickle`, :func:`DataFrame.to_csv`, :func:`Series.to_csv`, :func:`DataFrame.to_json`, :func:`Series.to_json`. (:issue:`17778`) - :class:`DataFrame` and :class:`Series` now support matrix multiplication (```@```) operator (:issue:`10259`) for Python>=3.5 - +- Updated ``to_gbq`` and ``read_gbq`` signature and documentation to reflect changes from + the Pandas-GBQ library version 0.4.0. Adds intersphinx mapping to Pandas-GBQ + library. (:issue:`20564`) + .. _whatsnew_0230.api_breaking: Backwards incompatible API changes diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9626079660771..af6b64057e358 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1116,60 +1116,90 @@ def to_dict(self, orient='dict', into=dict): else: raise ValueError("orient '%s' not understood" % orient) - def to_gbq(self, destination_table, project_id, chunksize=10000, - verbose=True, reauth=False, if_exists='fail', private_key=None): - """Write a DataFrame to a Google BigQuery table. - - The main method a user calls to export pandas DataFrame contents to - Google BigQuery table. + def to_gbq(self, destination_table, project_id, chunksize=None, + verbose=None, reauth=False, if_exists='fail', private_key=None, + auth_local_webserver=False, table_schema=None): + """ + Write a DataFrame to a Google BigQuery table. - Google BigQuery API Client Library v2 for Python is used. - Documentation is available `here - <https://developers.google.com/api-client-library/python/apis/bigquery/v2>`__ + This function requires the `pandas-gbq package + <https://pandas-gbq.readthedocs.io>`__. Authentication to the Google BigQuery service is via OAuth 2.0. - - If "private_key" is not provided: + - If ``private_key`` is provided, the library loads the JSON service + account credentials and uses those to authenticate. - By default "application default credentials" are used. + - If no ``private_key`` is provided, the library tries `application + default credentials`_. - If default application credentials are not found or are restrictive, - user account credentials are used. In this case, you will be asked to - grant permissions for product name 'pandas GBQ'. + .. _application default credentials: + https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application - - If "private_key" is provided: - - Service account credentials will be used to authenticate. + - If application default credentials are not found or cannot be used + with BigQuery, the library authenticates with user account + credentials. In this case, you will be asked to grant permissions + for product name 'pandas GBQ'. Parameters ---------- - dataframe : DataFrame - DataFrame to be written - destination_table : string - Name of table to be written, in the form 'dataset.tablename' + destination_table : str + Name of table to be written, in the form 'dataset.tablename'. project_id : str Google BigQuery Account project ID. - chunksize : int (default 10000) + chunksize : int, optional Number of rows to be inserted in each chunk from the dataframe. - verbose : boolean (default True) - Show percentage complete - reauth : boolean (default False) + Set to ``None`` to load the whole dataframe at once. + reauth : bool, default False Force Google BigQuery to reauthenticate the user. This is useful if multiple accounts are used. - if_exists : {'fail', 'replace', 'append'}, default 'fail' - 'fail': If table exists, do nothing. - 'replace': If table exists, drop it, recreate it, and insert data. - 'append': If table exists, insert data. Create if does not exist. - private_key : str (optional) + if_exists : str, default 'fail' + Behavior when the destination table exists. Value can be one of: + + ``'fail'`` + If table exists, do nothing. + ``'replace'`` + If table exists, drop it, recreate it, and insert data. + ``'append'`` + If table exists, insert data. Create if does not exist. + private_key : str, optional Service account private key in JSON format. Can be file path or string contents. This is useful for remote server - authentication (eg. Jupyter/IPython notebook on remote host) - """ + authentication (eg. Jupyter/IPython notebook on remote host). + auth_local_webserver : bool, default False + Use the `local webserver flow`_ instead of the `console flow`_ + when getting user credentials. + + .. _local webserver flow: + http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_local_server + .. _console flow: + http://google-auth-oauthlib.readthedocs.io/en/latest/reference/google_auth_oauthlib.flow.html#google_auth_oauthlib.flow.InstalledAppFlow.run_console + + *New in version 0.2.0 of pandas-gbq*. + table_schema : list of dicts, optional + List of BigQuery table fields to which according DataFrame + columns conform to, e.g. ``[{'name': 'col1', 'type': + 'STRING'},...]``. If schema is not provided, it will be + generated according to dtypes of DataFrame columns. See + BigQuery API documentation on available names of a field. + + *New in version 0.3.1 of pandas-gbq*. + verbose : boolean, deprecated + *Deprecated in Pandas-GBQ 0.4.0.* Use the `logging module + to adjust verbosity instead + <https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__. + See Also + -------- + pandas_gbq.to_gbq : This function in the pandas-gbq library. + pandas.read_gbq : Read a DataFrame from Google BigQuery. + """ from pandas.io import gbq - return gbq.to_gbq(self, destination_table, project_id=project_id, - chunksize=chunksize, verbose=verbose, reauth=reauth, - if_exists=if_exists, private_key=private_key) + return gbq.to_gbq( + self, destination_table, project_id, chunksize=chunksize, + verbose=verbose, reauth=reauth, if_exists=if_exists, + private_key=private_key, auth_local_webserver=auth_local_webserver, + table_schema=table_schema) @classmethod def from_records(cls, data, index=None, exclude=None, columns=None, diff --git a/pandas/io/gbq.py b/pandas/io/gbq.py index f9bc6ae1a5451..236d70609e76c 100644 --- a/pandas/io/gbq.py +++ b/pandas/io/gbq.py @@ -22,12 +22,10 @@ def _try_import(): def read_gbq(query, project_id=None, index_col=None, col_order=None, - reauth=False, verbose=True, private_key=None, dialect='legacy', + reauth=False, verbose=None, private_key=None, dialect='legacy', **kwargs): - r"""Load data from Google BigQuery. - - The main method a user calls to execute a Query in Google BigQuery - and read results into a pandas DataFrame. + """ + Load data from Google BigQuery. This function requires the `pandas-gbq package <https://pandas-gbq.readthedocs.io>`__. @@ -49,32 +47,39 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, Parameters ---------- query : str - SQL-Like Query to return data values + SQL-Like Query to return data values. project_id : str Google BigQuery Account project ID. - index_col : str (optional) - Name of result column to use for index in results DataFrame - col_order : list(str) (optional) + index_col : str, optional + Name of result column to use for index in results DataFrame. + col_order : list(str), optional List of BigQuery column names in the desired order for results - DataFrame - reauth : boolean (default False) + DataFrame. + reauth : boolean, default False Force Google BigQuery to reauthenticate the user. This is useful if multiple accounts are used. - verbose : boolean (default True) - Verbose output - private_key : str (optional) + private_key : str, optional Service account private key in JSON format. Can be file path or string contents. This is useful for remote server - authentication (eg. Jupyter/IPython notebook on remote host) - - dialect : {'legacy', 'standard'}, default 'legacy' - 'legacy' : Use BigQuery's legacy SQL dialect. - 'standard' : Use BigQuery's standard SQL, which is - compliant with the SQL 2011 standard. For more information - see `BigQuery SQL Reference - <https://cloud.google.com/bigquery/sql-reference/>`__ - - `**kwargs` : Arbitrary keyword arguments + authentication (eg. Jupyter/IPython notebook on remote host). + dialect : str, default 'legacy' + SQL syntax dialect to use. Value can be one of: + + ``'legacy'`` + Use BigQuery's legacy SQL dialect. For more information see + `BigQuery Legacy SQL Reference + <https://cloud.google.com/bigquery/docs/reference/legacy-sql>`__. + ``'standard'`` + Use BigQuery's standard SQL, which is + compliant with the SQL 2011 standard. For more information + see `BigQuery Standard SQL Reference + <https://cloud.google.com/bigquery/docs/reference/standard-sql/>`__. + verbose : boolean, deprecated + *Deprecated in Pandas-GBQ 0.4.0.* Use the `logging module + to adjust verbosity instead + <https://pandas-gbq.readthedocs.io/en/latest/intro.html#logging>`__. + kwargs : dict + Arbitrary keyword arguments. configuration (dict): query config parameters for job processing. For example: @@ -86,8 +91,12 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, Returns ------- df: DataFrame - DataFrame representing results of query + DataFrame representing results of query. + See Also + -------- + pandas_gbq.read_gbq : This function in the pandas-gbq library. + pandas.DataFrame.to_gbq : Write a DataFrame to Google BigQuery. """ pandas_gbq = _try_import() return pandas_gbq.read_gbq( @@ -99,10 +108,12 @@ def read_gbq(query, project_id=None, index_col=None, col_order=None, **kwargs) -def to_gbq(dataframe, destination_table, project_id, chunksize=10000, - verbose=True, reauth=False, if_exists='fail', private_key=None): +def to_gbq(dataframe, destination_table, project_id, chunksize=None, + verbose=None, reauth=False, if_exists='fail', private_key=None, + auth_local_webserver=False, table_schema=None): pandas_gbq = _try_import() - pandas_gbq.to_gbq(dataframe, destination_table, project_id, - chunksize=chunksize, - verbose=verbose, reauth=reauth, - if_exists=if_exists, private_key=private_key) + return pandas_gbq.to_gbq( + dataframe, destination_table, project_id, chunksize=chunksize, + verbose=verbose, reauth=reauth, if_exists=if_exists, + private_key=private_key, auth_local_webserver=auth_local_webserver, + table_schema=table_schema)
Delegates more of the behavior and documentation for `to_gbq` and `read_gbq` methods to the `pandas-gbq` library. This duplicate documentation was getting out of sync. Please include the output of the validation script below between the "```" ticks: ``` $ scripts/validate_docstrings.py pandas.DataFrame.to_gbq ################################################################################ ##################### Docstring (pandas.DataFrame.to_gbq) ##################### ################################################################################ Write a DataFrame to a Google BigQuery table. This function requires the `pandas-gbq package <https://pandas-gbq.readthedocs.io>`__. See: :meth:`pandas_gbq.to_gbq` ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'kwargs', 'args'} not documented No returns section found See Also section not found No examples section found (3.6.2/envs/pandas-dev) # swast @ swast-macbookpro2 in ~/src/pandas/pandas on git:master o [16:56:32] C:5 $ scripts/validate_docstrings.py pandas.io.gbq.read_gbq ################################################################################ ###################### Docstring (pandas.io.gbq.read_gbq) ###################### ################################################################################ Load data from Google BigQuery. This function requires the `pandas-gbq package <https://pandas-gbq.readthedocs.io>`__. See :meth:`pandas_gbq.read_gbq`. Returns ------- df: DataFrame DataFrame representing results of query ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'kwargs', 'args'} not documented See Also section not found No examples section found (3.6.2/envs/pandas-dev) # swast @ swast-macbookpro2 in ~/src/pandas/pandas on git:master o [16:56:39] C:4 $ scripts/validate_docstrings.py pandas.DataFrame.to_gbq ################################################################################ ##################### Docstring (pandas.DataFrame.to_gbq) ##################### ################################################################################ Write a DataFrame to a Google BigQuery table. This function requires the `pandas-gbq package <https://pandas-gbq.readthedocs.io>`__. See: :meth:`pandas_gbq.to_gbq` ################################################################################ ################################## Validation ################################## ################################################################################ Errors found: Errors in parameters section Parameters {'args', 'kwargs'} not documented No returns section found See Also section not found No examples section found ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. **Validation script gives errors** This PR removes documentation which is duplicated in the `pandas-gbq` docs and add intersphinx links to the relevant methods. Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [ ] closes #xxxx - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20564
2018-03-30T23:58:01Z
2018-04-09T10:02:24Z
2018-04-09T10:02:24Z
2019-12-11T20:30:19Z
CLN: Use new-style classes instead of old-style classes
diff --git a/ci/lint.sh b/ci/lint.sh index 545ac9c90c5c1..2cbf6f7ae52a9 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -165,6 +165,14 @@ if [ "$LINT" ]; then RET=1 fi echo "Check for deprecated messages without sphinx directive DONE" + + echo "Check for old-style classes" + grep -R --include="*.py" -E "class\s\S*[^)]:" pandas scripts + + if [ $? = "0" ]; then + RET=1 + fi + echo "Check for old-style classes DONE" else echo "NOT Linting" diff --git a/pandas/_version.py b/pandas/_version.py index 624c7b5cd63a1..919db956b8f99 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -25,7 +25,7 @@ def get_keywords(): return keywords -class VersioneerConfig: +class VersioneerConfig(object): pass diff --git a/pandas/io/common.py b/pandas/io/common.py index 4769edd157b94..0827216975f15 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -534,7 +534,7 @@ def __next__(self): row = next(self.reader) return [compat.text_type(s, "utf-8") for s in row] - class UnicodeWriter: + class UnicodeWriter(object): """ A CSV writer which will write rows to CSV file "f", diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py index 806cbddaa2ee2..4d187a8282859 100644 --- a/pandas/io/sas/sas7bdat.py +++ b/pandas/io/sas/sas7bdat.py @@ -321,7 +321,7 @@ def _get_subheader_index(self, signature, compression, ptype): (compression == 0)) f2 = (ptype == const.compressed_subheader_type) if (self.compression != "") and f1 and f2: - index = const.index.dataSubheaderIndex + index = const.SASIndex.data_subheader_index else: self.close() raise ValueError("Unknown subheader signature") @@ -360,23 +360,23 @@ def _process_subheader(self, subheader_index, pointer): offset = pointer.offset length = pointer.length - if subheader_index == const.index.rowSizeIndex: + if subheader_index == const.SASIndex.row_size_index: processor = self._process_rowsize_subheader - elif subheader_index == const.index.columnSizeIndex: + elif subheader_index == const.SASIndex.column_size_index: processor = self._process_columnsize_subheader - elif subheader_index == const.index.columnTextIndex: + elif subheader_index == const.SASIndex.column_text_index: processor = self._process_columntext_subheader - elif subheader_index == const.index.columnNameIndex: + elif subheader_index == const.SASIndex.column_name_index: processor = self._process_columnname_subheader - elif subheader_index == const.index.columnAttributesIndex: + elif subheader_index == const.SASIndex.column_attributes_index: processor = self._process_columnattributes_subheader - elif subheader_index == const.index.formatAndLabelIndex: + elif subheader_index == const.SASIndex.format_and_label_index: processor = self._process_format_subheader - elif subheader_index == const.index.columnListIndex: + elif subheader_index == const.SASIndex.column_list_index: processor = self._process_columnlist_subheader - elif subheader_index == const.index.subheaderCountsIndex: + elif subheader_index == const.SASIndex.subheader_counts_index: processor = self._process_subheader_counts - elif subheader_index == const.index.dataSubheaderIndex: + elif subheader_index == const.SASIndex.data_subheader_index: self._current_page_data_subheader_pointers.append(pointer) return else: diff --git a/pandas/io/sas/sas_constants.py b/pandas/io/sas/sas_constants.py index c4b3588164305..98502d32d39e8 100644 --- a/pandas/io/sas/sas_constants.py +++ b/pandas/io/sas/sas_constants.py @@ -102,49 +102,49 @@ 61: "wcyrillic", 62: "wlatin1", 90: "ebcdic870"} -class index: - rowSizeIndex = 0 - columnSizeIndex = 1 - subheaderCountsIndex = 2 - columnTextIndex = 3 - columnNameIndex = 4 - columnAttributesIndex = 5 - formatAndLabelIndex = 6 - columnListIndex = 7 - dataSubheaderIndex = 8 +class SASIndex(object): + row_size_index = 0 + column_size_index = 1 + subheader_counts_index = 2 + column_text_index = 3 + column_name_index = 4 + column_attributes_index = 5 + format_and_label_index = 6 + column_list_index = 7 + data_subheader_index = 8 subheader_signature_to_index = { - b"\xF7\xF7\xF7\xF7": index.rowSizeIndex, - b"\x00\x00\x00\x00\xF7\xF7\xF7\xF7": index.rowSizeIndex, - b"\xF7\xF7\xF7\xF7\x00\x00\x00\x00": index.rowSizeIndex, - b"\xF7\xF7\xF7\xF7\xFF\xFF\xFB\xFE": index.rowSizeIndex, - b"\xF6\xF6\xF6\xF6": index.columnSizeIndex, - b"\x00\x00\x00\x00\xF6\xF6\xF6\xF6": index.columnSizeIndex, - b"\xF6\xF6\xF6\xF6\x00\x00\x00\x00": index.columnSizeIndex, - b"\xF6\xF6\xF6\xF6\xFF\xFF\xFB\xFE": index.columnSizeIndex, - b"\x00\xFC\xFF\xFF": index.subheaderCountsIndex, - b"\xFF\xFF\xFC\x00": index.subheaderCountsIndex, - b"\x00\xFC\xFF\xFF\xFF\xFF\xFF\xFF": index.subheaderCountsIndex, - b"\xFF\xFF\xFF\xFF\xFF\xFF\xFC\x00": index.subheaderCountsIndex, - b"\xFD\xFF\xFF\xFF": index.columnTextIndex, - b"\xFF\xFF\xFF\xFD": index.columnTextIndex, - b"\xFD\xFF\xFF\xFF\xFF\xFF\xFF\xFF": index.columnTextIndex, - b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFD": index.columnTextIndex, - b"\xFF\xFF\xFF\xFF": index.columnNameIndex, - b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF": index.columnNameIndex, - b"\xFC\xFF\xFF\xFF": index.columnAttributesIndex, - b"\xFF\xFF\xFF\xFC": index.columnAttributesIndex, - b"\xFC\xFF\xFF\xFF\xFF\xFF\xFF\xFF": index.columnAttributesIndex, - b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC": index.columnAttributesIndex, - b"\xFE\xFB\xFF\xFF": index.formatAndLabelIndex, - b"\xFF\xFF\xFB\xFE": index.formatAndLabelIndex, - b"\xFE\xFB\xFF\xFF\xFF\xFF\xFF\xFF": index.formatAndLabelIndex, - b"\xFF\xFF\xFF\xFF\xFF\xFF\xFB\xFE": index.formatAndLabelIndex, - b"\xFE\xFF\xFF\xFF": index.columnListIndex, - b"\xFF\xFF\xFF\xFE": index.columnListIndex, - b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF": index.columnListIndex, - b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE": index.columnListIndex} + b"\xF7\xF7\xF7\xF7": SASIndex.row_size_index, + b"\x00\x00\x00\x00\xF7\xF7\xF7\xF7": SASIndex.row_size_index, + b"\xF7\xF7\xF7\xF7\x00\x00\x00\x00": SASIndex.row_size_index, + b"\xF7\xF7\xF7\xF7\xFF\xFF\xFB\xFE": SASIndex.row_size_index, + b"\xF6\xF6\xF6\xF6": SASIndex.column_size_index, + b"\x00\x00\x00\x00\xF6\xF6\xF6\xF6": SASIndex.column_size_index, + b"\xF6\xF6\xF6\xF6\x00\x00\x00\x00": SASIndex.column_size_index, + b"\xF6\xF6\xF6\xF6\xFF\xFF\xFB\xFE": SASIndex.column_size_index, + b"\x00\xFC\xFF\xFF": SASIndex.subheader_counts_index, + b"\xFF\xFF\xFC\x00": SASIndex.subheader_counts_index, + b"\x00\xFC\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.subheader_counts_index, + b"\xFF\xFF\xFF\xFF\xFF\xFF\xFC\x00": SASIndex.subheader_counts_index, + b"\xFD\xFF\xFF\xFF": SASIndex.column_text_index, + b"\xFF\xFF\xFF\xFD": SASIndex.column_text_index, + b"\xFD\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_text_index, + b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFD": SASIndex.column_text_index, + b"\xFF\xFF\xFF\xFF": SASIndex.column_name_index, + b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_name_index, + b"\xFC\xFF\xFF\xFF": SASIndex.column_attributes_index, + b"\xFF\xFF\xFF\xFC": SASIndex.column_attributes_index, + b"\xFC\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_attributes_index, + b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC": SASIndex.column_attributes_index, + b"\xFE\xFB\xFF\xFF": SASIndex.format_and_label_index, + b"\xFF\xFF\xFB\xFE": SASIndex.format_and_label_index, + b"\xFE\xFB\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.format_and_label_index, + b"\xFF\xFF\xFF\xFF\xFF\xFF\xFB\xFE": SASIndex.format_and_label_index, + b"\xFE\xFF\xFF\xFF": SASIndex.column_list_index, + b"\xFF\xFF\xFF\xFE": SASIndex.column_list_index, + b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF": SASIndex.column_list_index, + b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE": SASIndex.column_list_index} # List of frequently used SAS date and datetime formats diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 7949636fcafbb..0d3add4c4ca11 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1215,7 +1215,7 @@ def wrapper(x): getattr(mixed, name)(axis=0) getattr(mixed, name)(axis=1) - class NonzeroFail: + class NonzeroFail(object): def __nonzero__(self): raise ValueError diff --git a/pandas/tests/indexing/test_panel.py b/pandas/tests/indexing/test_panel.py index c4f7bd28e4d90..81265c9f2941d 100644 --- a/pandas/tests/indexing/test_panel.py +++ b/pandas/tests/indexing/test_panel.py @@ -149,7 +149,7 @@ def test_panel_getitem(self): # with an object-like # GH 9140 - class TestObject: + class TestObject(object): def __str__(self): return "TestObject" diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index ab9f61cffc16b..0aab30e299c86 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1621,7 +1621,7 @@ def test_pprint_pathological_object(self): If the test fails, it at least won't hang. """ - class A: + class A(object): def __getitem__(self, key): return 3 # obviously simplified diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index e949772981eb7..89acbfdc9a746 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -460,11 +460,11 @@ def test_decodeFromUnicode(self): def test_encodeRecursionMax(self): # 8 is the max recursion depth - class O2: + class O2(object): member = 0 pass - class O1: + class O1(object): member = 0 pass @@ -772,14 +772,14 @@ def test_dumpToFile(self): assert "[1,2,3]" == f.getvalue() def test_dumpToFileLikeObject(self): - class filelike: + class FileLike(object): def __init__(self): self.bytes = '' def write(self, bytes): self.bytes += bytes - f = filelike() + f = FileLike() ujson.dump([1, 2, 3], f) assert "[1,2,3]" == f.bytes @@ -800,7 +800,7 @@ def test_loadFile(self): np.array([1, 2, 3, 4]), ujson.load(f, numpy=True)) def test_loadFileLikeObject(self): - class filelike: + class FileLike(object): def read(self): try: @@ -808,10 +808,10 @@ def read(self): except AttributeError: self.end = True return "[1,2,3,4]" - f = filelike() + f = FileLike() assert [1, 2, 3, 4] == ujson.load(f) - f = filelike() + f = FileLike() tm.assert_numpy_array_equal( np.array([1, 2, 3, 4]), ujson.load(f, numpy=True)) @@ -837,7 +837,7 @@ def test_encodeNumericOverflow(self): def test_encodeNumericOverflowNested(self): for n in range(0, 100): - class Nested: + class Nested(object): x = 12839128391289382193812939 nested = Nested() @@ -886,7 +886,7 @@ def test_decodeBigEscape(self): def test_toDict(self): d = {u("key"): 31337} - class DictTest: + class DictTest(object): def toDict(self): return d diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index a80c5d6611b8a..ab2bf92a26826 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -37,7 +37,7 @@ def test_ops_error_str(self): assert left != right def test_ops_notimplemented(self): - class Other: + class Other(object): pass other = Other() diff --git a/pandas/tests/sparse/frame/test_frame.py b/pandas/tests/sparse/frame/test_frame.py index 1062de3119efc..540933cb90be2 100644 --- a/pandas/tests/sparse/frame/test_frame.py +++ b/pandas/tests/sparse/frame/test_frame.py @@ -227,7 +227,7 @@ def test_constructor_from_dense_series(self): def test_constructor_from_unknown_type(self): # GH 19393 - class Unknown: + class Unknown(object): pass with pytest.raises(TypeError, message='SparseDataFrame called with unknown type ' diff --git a/pandas/tests/test_errors.py b/pandas/tests/test_errors.py index e2a142366a89e..7f9cddf9859a5 100644 --- a/pandas/tests/test_errors.py +++ b/pandas/tests/test_errors.py @@ -54,7 +54,7 @@ def test_error_rename(): pass -class Foo: +class Foo(object): @classmethod def classmethod(cls): raise AbstractMethodError(cls, methodtype='classmethod') diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 23cc18de34778..2264508fa9d91 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -1082,7 +1082,7 @@ def test_resample_how_callables(self): def fn(x, a=1): return str(type(x)) - class fn_class: + class FnClass(object): def __call__(self, x): return str(type(x)) @@ -1091,7 +1091,7 @@ def __call__(self, x): df_lambda = df.resample("M").apply(lambda x: str(type(x))) df_partial = df.resample("M").apply(partial(fn)) df_partial2 = df.resample("M").apply(partial(fn, a=2)) - df_class = df.resample("M").apply(fn_class()) + df_class = df.resample("M").apply(FnClass()) assert_frame_equal(df_standard, df_lambda) assert_frame_equal(df_standard, df_partial) diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index a7e121f9069fc..3863451757709 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -94,7 +94,7 @@ def _output_header(title, width=80, char='#'): full_line=full_line, title_line=title_line) -class Docstring: +class Docstring(object): def __init__(self, method_name, method_obj): self.method_name = method_name self.method_obj = method_obj diff --git a/versioneer.py b/versioneer.py index b0ae4fa2dc8e8..5dae3723ecf9c 100644 --- a/versioneer.py +++ b/versioneer.py @@ -352,7 +352,7 @@ import sys -class VersioneerConfig: +class VersioneerConfig(object): pass
Noticed some [lgtm.com alerts](https://lgtm.com/projects/g/pydata/pandas/snapshot/f85a69a8fdaed49747c4db61f5177a296cf290eb/files/scripts/validate_docstrings.py?sort=name&dir=ASC&mode=heatmap&showExcluded=false#L108) about the [`@property` decorator not working in old-style classes](https://lgtm.com/rules/10030086/) in `scripts/validate_docstrings.py`. I don't think this actually causes any undesired behavior in that script though. Figured this would be a good time to enforce new-style classes throughout the codebase: - Converted old-style classes to new-style classes - Basically just inserted `(object)`. - Added a check to `lint.sh` for old-style classes, since `flake8` doesn't look to be catching it. - Maybe there's a way to enforce this in `flake8` instead? - Didn't hit the Cython code; not exactly sure what the new-style vs. old-style conventions are there.
https://api.github.com/repos/pandas-dev/pandas/pulls/20563
2018-03-30T23:44:01Z
2018-04-03T07:00:44Z
2018-04-03T07:00:44Z
2018-09-24T17:24:43Z
CI: move 2.7_SLOW -> 3.6_SLOW
diff --git a/.travis.yml b/.travis.yml index 22ef6c819c6d4..e4dab4eb53afb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -56,7 +56,7 @@ matrix: # In allow_failures - dist: trusty env: - - JOB="2.7_SLOW" SLOW=true + - JOB="3.6_SLOW" SLOW=true # In allow_failures - dist: trusty env: @@ -72,7 +72,7 @@ matrix: allow_failures: - dist: trusty env: - - JOB="2.7_SLOW" SLOW=true + - JOB="3.6_SLOW" SLOW=true - dist: trusty env: - JOB="3.6_NUMPY_DEV" TEST_ARGS="--skip-slow --skip-network" PANDAS_TESTING_MODE="deprecate" diff --git a/ci/requirements-2.7_SLOW.build b/ci/requirements-3.6_SLOW.build similarity index 53% rename from ci/requirements-2.7_SLOW.build rename to ci/requirements-3.6_SLOW.build index a665ab9edd585..bdcfe28105866 100644 --- a/ci/requirements-2.7_SLOW.build +++ b/ci/requirements-3.6_SLOW.build @@ -1,5 +1,5 @@ -python=2.7* +python=3.6* python-dateutil pytz -numpy=1.10* +numpy cython diff --git a/ci/requirements-2.7_SLOW.pip b/ci/requirements-3.6_SLOW.pip similarity index 100% rename from ci/requirements-2.7_SLOW.pip rename to ci/requirements-3.6_SLOW.pip diff --git a/ci/requirements-2.7_SLOW.run b/ci/requirements-3.6_SLOW.run similarity index 83% rename from ci/requirements-2.7_SLOW.run rename to ci/requirements-3.6_SLOW.run index db95a6ccb2314..ab5253ad99e51 100644 --- a/ci/requirements-2.7_SLOW.run +++ b/ci/requirements-3.6_SLOW.run @@ -1,7 +1,7 @@ python-dateutil pytz -numpy=1.10* -matplotlib=1.4.3 +numpy +matplotlib scipy patsy xlwt
https://api.github.com/repos/pandas-dev/pandas/pulls/20559
2018-03-30T21:08:51Z
2018-03-31T15:27:26Z
2018-03-31T15:27:26Z
2018-03-31T15:28:00Z
BUG: usecols kwarg accepts string when it should only allow list-like or callable.
diff --git a/doc/source/io.rst b/doc/source/io.rst index ff505f525fc22..fd998d32cfbfb 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -130,11 +130,11 @@ index_col : int or sequence or ``False``, default ``None`` MultiIndex is used. If you have a malformed file with delimiters at the end of each line, you might consider ``index_col=False`` to force pandas to *not* use the first column as the index (row names). -usecols : array-like or callable, default ``None`` - Return a subset of the columns. If array-like, all elements must either +usecols : list-like or callable, default ``None`` + Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in `names` or - inferred from the document header row(s). For example, a valid array-like + inferred from the document header row(s). For example, a valid list-like `usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index e83f149db1f18..6524012d27fc9 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1077,6 +1077,7 @@ I/O - Bug in :meth:`pandas.io.stata.StataReader.value_labels` raising an ``AttributeError`` when called on very old files. Now returns an empty dict (:issue:`19417`) - Bug in :func:`read_pickle` when unpickling objects with :class:`TimedeltaIndex` or :class:`Float64Index` created with pandas prior to version 0.20 (:issue:`19939`) - Bug in :meth:`pandas.io.json.json_normalize` where subrecords are not properly normalized if any subrecords values are NoneType (:issue:`20030`) +- Bug in ``usecols`` parameter in :func:`pandas.io.read_csv` and :func:`pandas.io.read_table` where error is not raised correctly when passing a string. (:issue:`20529`) Plotting ^^^^^^^^ diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 52ca3d1226f79..a24e2cdd99f6f 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -445,10 +445,9 @@ cdef class TextReader: # suboptimal if usecols is not None: self.has_usecols = 1 - if callable(usecols): - self.usecols = usecols - else: - self.usecols = set(usecols) + # GH-20558, validate usecols at higher level and only pass clean + # usecols into TextReader. + self.usecols = usecols # XXX if skipfooter > 0: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 469cd6d82e4b4..780aa5d02f598 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -97,11 +97,11 @@ MultiIndex is used. If you have a malformed file with delimiters at the end of each line, you might consider index_col=False to force pandas to _not_ use the first column as the index (row names) -usecols : array-like or callable, default None - Return a subset of the columns. If array-like, all elements must either +usecols : list-like or callable, default None + Return a subset of the columns. If list-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in `names` or - inferred from the document header row(s). For example, a valid array-like + inferred from the document header row(s). For example, a valid list-like `usecols` parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To instantiate a DataFrame from ``data`` with element order preserved use @@ -1177,7 +1177,7 @@ def _validate_usecols_arg(usecols): Parameters ---------- - usecols : array-like, callable, or None + usecols : list-like, callable, or None List of columns to use when parsing or a callable that can be used to filter a list of table columns. @@ -1192,17 +1192,19 @@ def _validate_usecols_arg(usecols): 'usecols_dtype` is the inferred dtype of 'usecols' if an array-like is passed in or None if a callable or None is passed in. """ - msg = ("'usecols' must either be all strings, all unicode, " - "all integers or a callable") - + msg = ("'usecols' must either be list-like of all strings, all unicode, " + "all integers or a callable.") if usecols is not None: if callable(usecols): return usecols, None - usecols_dtype = lib.infer_dtype(usecols) - if usecols_dtype not in ('empty', 'integer', - 'string', 'unicode'): + # GH20529, ensure is iterable container but not string. + elif not is_list_like(usecols): raise ValueError(msg) - + else: + usecols_dtype = lib.infer_dtype(usecols) + if usecols_dtype not in ('empty', 'integer', + 'string', 'unicode'): + raise ValueError(msg) return set(usecols), usecols_dtype return usecols, None @@ -1697,11 +1699,12 @@ def __init__(self, src, **kwds): # #2442 kwds['allow_leading_cols'] = self.index_col is not False - self._reader = parsers.TextReader(src, **kwds) - - # XXX + # GH20529, validate usecol arg before TextReader self.usecols, self.usecols_dtype = _validate_usecols_arg( - self._reader.usecols) + kwds['usecols']) + kwds['usecols'] = self.usecols + + self._reader = parsers.TextReader(src, **kwds) passed_names = self.names is None diff --git a/pandas/tests/io/parser/usecols.py b/pandas/tests/io/parser/usecols.py index 195fb4cba2aed..584711528e9cb 100644 --- a/pandas/tests/io/parser/usecols.py +++ b/pandas/tests/io/parser/usecols.py @@ -16,6 +16,11 @@ class UsecolsTests(object): + msg_validate_usecols_arg = ("'usecols' must either be list-like of all " + "strings, all unicode, all integers or a " + "callable.") + msg_validate_usecols_names = ("Usecols do not match columns, columns " + "expected but not found: {0}") def test_raise_on_mixed_dtype_usecols(self): # See gh-12678 @@ -24,11 +29,9 @@ def test_raise_on_mixed_dtype_usecols(self): 4000,5000,6000 """ - msg = ("'usecols' must either be all strings, all unicode, " - "all integers or a callable") usecols = [0, 'b', 2] - with tm.assert_raises_regex(ValueError, msg): + with tm.assert_raises_regex(ValueError, self.msg_validate_usecols_arg): self.read_csv(StringIO(data), usecols=usecols) def test_usecols(self): @@ -85,6 +88,18 @@ def test_usecols(self): pytest.raises(ValueError, self.read_csv, StringIO(data), names=['a', 'b'], usecols=[1], header=None) + def test_usecols_single_string(self): + # GH 20558 + data = """foo, bar, baz + 1000, 2000, 3000 + 4000, 5000, 6000 + """ + + usecols = 'foo' + + with tm.assert_raises_regex(ValueError, self.msg_validate_usecols_arg): + self.read_csv(StringIO(data), usecols=usecols) + def test_usecols_index_col_False(self): # see gh-9082 s = "a,b,c,d\n1,2,3,4\n5,6,7,8" @@ -348,13 +363,10 @@ def test_usecols_with_mixed_encoding_strings(self): 3.568935038,7,False,a ''' - msg = ("'usecols' must either be all strings, all unicode, " - "all integers or a callable") - - with tm.assert_raises_regex(ValueError, msg): + with tm.assert_raises_regex(ValueError, self.msg_validate_usecols_arg): self.read_csv(StringIO(s), usecols=[u'AAA', b'BBB']) - with tm.assert_raises_regex(ValueError, msg): + with tm.assert_raises_regex(ValueError, self.msg_validate_usecols_arg): self.read_csv(StringIO(s), usecols=[b'AAA', u'BBB']) def test_usecols_with_multibyte_characters(self): @@ -480,11 +492,6 @@ def test_raise_on_usecols_names_mismatch(self): # GH 14671 data = 'a,b,c,d\n1,2,3,4\n5,6,7,8' - msg = ( - "Usecols do not match columns, " - "columns expected but not found: {missing}" - ) - usecols = ['a', 'b', 'c', 'd'] df = self.read_csv(StringIO(data), usecols=usecols) expected = DataFrame({'a': [1, 5], 'b': [2, 6], 'c': [3, 7], @@ -492,18 +499,21 @@ def test_raise_on_usecols_names_mismatch(self): tm.assert_frame_equal(df, expected) usecols = ['a', 'b', 'c', 'f'] - with tm.assert_raises_regex( - ValueError, msg.format(missing=r"\['f'\]")): + with tm.assert_raises_regex(ValueError, + self.msg_validate_usecols_names.format( + r"\['f'\]")): self.read_csv(StringIO(data), usecols=usecols) usecols = ['a', 'b', 'f'] - with tm.assert_raises_regex( - ValueError, msg.format(missing=r"\['f'\]")): + with tm.assert_raises_regex(ValueError, + self.msg_validate_usecols_names.format( + r"\['f'\]")): self.read_csv(StringIO(data), usecols=usecols) usecols = ['a', 'b', 'f', 'g'] - with tm.assert_raises_regex( - ValueError, msg.format(missing=r"\[('f', 'g'|'g', 'f')\]")): + with tm.assert_raises_regex(ValueError, + self.msg_validate_usecols_names.format( + r"\[('f', 'g'|'g', 'f')\]")): self.read_csv(StringIO(data), usecols=usecols) names = ['A', 'B', 'C', 'D'] @@ -527,11 +537,13 @@ def test_raise_on_usecols_names_mismatch(self): # tm.assert_frame_equal(df, expected) usecols = ['A', 'B', 'C', 'f'] - with tm.assert_raises_regex( - ValueError, msg.format(missing=r"\['f'\]")): + with tm.assert_raises_regex(ValueError, + self.msg_validate_usecols_names.format( + r"\['f'\]")): self.read_csv(StringIO(data), header=0, names=names, usecols=usecols) usecols = ['A', 'B', 'f'] - with tm.assert_raises_regex( - ValueError, msg.format(missing=r"\['f'\]")): + with tm.assert_raises_regex(ValueError, + self.msg_validate_usecols_names.format( + r"\['f'\]")): self.read_csv(StringIO(data), names=names, usecols=usecols)
- [x] closes #20529 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Since string is iterable, when passed into usecols in read_csv or read_table, it is currently treated as array of characters instead of being caught properly. For example, when usecols='bar', it is interpreted as ['b', 'a' ,'r'] in TextReader, and raising a column not found error in _validate_usecols_names when it really should raise ValueError as invalid value from _validate_usecols_arg, before the param being passed into TextReader. It's a bug in _validate_usecols_arg and TextReader which lack handling of string-type iterable. ``` >>> import os >>> from itertools import repeat >>> from pandas import * >>> >>> dummy = DataFrame({"foo": range(0, 5), ... "bar": range(10, 15), ... "b": [1, 2, 3, 5, 5], ... "a": list(repeat(3, 5)), ... "r": list(repeat(8, 5))}) >>> >>> dummy.to_csv('dummy.csv', index=False) >>> read_csv('dummy.csv', usecols=['foo']) foo 0 0 1 1 2 2 3 3 4 4 >>> read_csv('dummy.csv', usecols='bar') b a r 0 1 3 8 1 2 3 8 2 3 3 8 3 5 3 8 4 5 3 8 >>> >>> os.remove('dummy.csv') ``` Added is_list_like check in _validate_usecols_arg to ensure passed value is list-like but not string. Also, array_like is defined as list_like with dtype attribute so update docstring to list-like from array-like.
https://api.github.com/repos/pandas-dev/pandas/pulls/20558
2018-03-30T20:50:12Z
2018-04-01T13:42:26Z
2018-04-01T13:42:26Z
2018-04-01T15:22:40Z
BUG: Allow overwriting object columns with EAs
diff --git a/pandas/core/internals.py b/pandas/core/internals.py index a0e122d390240..f5956aacf8646 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2379,7 +2379,10 @@ def should_store(self, value): return not (issubclass(value.dtype.type, (np.integer, np.floating, np.complexfloating, np.datetime64, np.bool_)) or - is_extension_type(value)) + # TODO(ExtensionArray): remove is_extension_type + # when all extension arrays have been ported. + is_extension_type(value) or + is_extension_array_dtype(value)) def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True, mgr=None): diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index 9b9a614889bef..6f4d5b40515be 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -75,3 +75,9 @@ def test_set_frame_expand_extension_with_regular(self, data): df['B'] = [1] * len(data) expected = pd.DataFrame({"A": data, "B": [1] * len(data)}) self.assert_frame_equal(df, expected) + + def test_set_frame_overwrite_object(self, data): + # https://github.com/pandas-dev/pandas/issues/20555 + df = pd.DataFrame({"A": [1] * len(data)}, dtype=object) + df['A'] = data + assert df.dtypes['A'] == data.dtype
Closes https://github.com/pandas-dev/pandas/issues/20555
https://api.github.com/repos/pandas-dev/pandas/pulls/20556
2018-03-30T18:59:37Z
2018-03-31T16:03:00Z
2018-03-31T16:03:00Z
2018-03-31T16:03:05Z
COMPAT: Remove use of private re attribute
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index aefa1ddd6cf0b..8885064b22ea8 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -26,6 +26,7 @@ # pylint disable=W0611 # flake8: noqa +import re import functools import itertools from distutils.version import LooseVersion @@ -136,7 +137,6 @@ def lfilter(*args, **kwargs): else: # Python 2 - import re _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$") FileNotFoundError = IOError @@ -423,6 +423,14 @@ def raise_with_traceback(exc, traceback=Ellipsis): parse_date = _date_parser.parse +# In Python 3.7, the private re._pattern_type is removed. +# Python 3.5+ have typing.re.Pattern +if PY35: + import typing + re_type = typing.re.Pattern +else: + re_type = type(re.compile('')) + # https://github.com/pandas-dev/pandas/pull/9123 def is_platform_little_endian(): """ am I little endian """ diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index a02f0c5b2a4d6..d747e69d1ff39 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -6,7 +6,7 @@ from collections import Iterable from numbers import Number from pandas.compat import (PY2, string_types, text_type, - string_and_binary_types) + string_and_binary_types, re_type) from pandas._libs import lib is_bool = lib.is_bool @@ -216,7 +216,7 @@ def is_re(obj): False """ - return isinstance(obj, re._pattern_type) + return isinstance(obj, re_type) def is_re_compilable(obj):
Closes https://github.com/pandas-dev/pandas/issues/20551
https://api.github.com/repos/pandas-dev/pandas/pulls/20553
2018-03-30T16:58:42Z
2018-03-31T16:04:13Z
2018-03-31T16:04:12Z
2018-05-16T13:30:13Z
TST: tests for inconsistent indexing with datetimes
diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 6d74ce54faa94..7149c9e27408f 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -1548,6 +1548,25 @@ def test_setitem_single_column_mixed_datetime(self): # pytest.raises( # Exception, df.loc.__setitem__, ('d', 'timestamp'), [nan]) + def test_setitem_mixed_datetime(self): + # GH 9336 + expected = DataFrame({'a': [0, 0, 0, 0, 13, 14], + 'b': [pd.datetime(2012, 1, 1), + 1, + 'x', + 'y', + pd.datetime(2013, 1, 1), + pd.datetime(2014, 1, 1)]}) + df = pd.DataFrame(0, columns=list('ab'), index=range(6)) + df['b'] = pd.NaT + df.loc[0, 'b'] = pd.datetime(2012, 1, 1) + df.loc[1, 'b'] = 1 + df.loc[[2, 3], 'b'] = 'x', 'y' + A = np.array([[13, np.datetime64('2013-01-01T00:00:00')], + [14, np.datetime64('2014-01-01T00:00:00')]]) + df.loc[[4, 5], ['a', 'b']] = A + assert_frame_equal(df, expected) + def test_setitem_frame(self): piece = self.frame.loc[self.frame.index[:2], ['A', 'B']] self.frame.loc[self.frame.index[-2]:, ['A', 'B']] = piece.values
- [X] closes #9336 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20550
2018-03-30T14:18:18Z
2018-05-29T01:34:34Z
2018-05-29T01:34:34Z
2018-05-29T01:34:39Z
Fixed WOM offset when n=0
diff --git a/doc/source/api.rst b/doc/source/api.rst index e224e9927f55c..e43632ea46bfb 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -2106,6 +2106,7 @@ Standard moving window functions Rolling.skew Rolling.kurt Rolling.apply + Rolling.aggregate Rolling.quantile Window.mean Window.sum @@ -2133,6 +2134,7 @@ Standard expanding window functions Expanding.skew Expanding.kurt Expanding.apply + Expanding.aggregate Expanding.quantile Exponentially-weighted moving window functions diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 1c9849730edd6..e340acc17fe9f 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -438,6 +438,7 @@ Other Enhancements ``SQLAlchemy`` dialects supporting multivalue inserts include: ``mysql``, ``postgresql``, ``sqlite`` and any dialect with ``supports_multivalues_insert``. (:issue:`14315`, :issue:`8953`) - :func:`read_html` now accepts a ``displayed_only`` keyword argument to controls whether or not hidden elements are parsed (``True`` by default) (:issue:`20027`) - zip compression is supported via ``compression=zip`` in :func:`DataFrame.to_pickle`, :func:`Series.to_pickle`, :func:`DataFrame.to_csv`, :func:`Series.to_csv`, :func:`DataFrame.to_json`, :func:`Series.to_json`. (:issue:`17778`) +- :class:`WeekOfMonth` constructor now supports ``n=0`` (:issue:`20517`). - :class:`DataFrame` and :class:`Series` now support matrix multiplication (```@```) operator (:issue:`10259`) for Python>=3.5 - Updated ``to_gbq`` and ``read_gbq`` signature and documentation to reflect changes from the Pandas-GBQ library version 0.4.0. Adds intersphinx mapping to Pandas-GBQ @@ -847,7 +848,7 @@ Other API Changes - :func:`DatetimeIndex.strftime` and :func:`PeriodIndex.strftime` now return an ``Index`` instead of a numpy array to be consistent with similar accessors (:issue:`20127`) - Constructing a Series from a list of length 1 no longer broadcasts this list when a longer index is specified (:issue:`19714`, :issue:`20391`). - :func:`DataFrame.to_dict` with ``orient='index'`` no longer casts int columns to float for a DataFrame with only int and float columns (:issue:`18580`) -- A user-defined-function that is passed to :func:`Series.rolling().aggregate() <pandas.core.window.Rolling.aggregate>`, :func:`DataFrame.rolling().aggregate() <pandas.core.window.Rolling.aggregate>`, or its expanding cousins, will now *always* be passed a ``Series``, rather than an ``np.array``; ``.apply()`` only has the ``raw`` keyword, see :ref:`here <whatsnew_0230.enhancements.window_raw>`. This is consistent with the signatures of ``.aggregate()`` across pandas (:issue:`20584`) +- A user-defined-function that is passed to :func:`Series.rolling().aggregate() <pandas.core.window.Rolling.aggregate>`, :func:`DataFrame.rolling().aggregate() <pandas.core.window.Rolling.aggregate>`, or its expanding cousins, will now *always* be passed a ``Series``, rather than a ``np.array``; ``.apply()`` only has the ``raw`` keyword, see :ref:`here <whatsnew_0230.enhancements.window_raw>`. This is consistent with the signatures of ``.aggregate()`` across pandas (:issue:`20584`) .. _whatsnew_0230.deprecations: diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 2dfd4ae3e6e3a..e5291ed52a86c 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -236,6 +236,12 @@ def test_catch_infinite_loop(self): pytest.raises(Exception, date_range, datetime(2011, 11, 11), datetime(2011, 11, 12), freq=offset) + @pytest.mark.parametrize('periods', (1, 2)) + def test_wom_len(self, periods): + # https://github.com/pandas-dev/pandas/issues/20517 + res = date_range(start='20110101', periods=periods, freq='WOM-1MON') + assert len(res) == periods + class TestGenRangeGeneration(object): diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index d96ebab615d12..5369b1a94a956 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -2228,8 +2228,6 @@ class TestWeekOfMonth(Base): _offset = WeekOfMonth def test_constructor(self): - tm.assert_raises_regex(ValueError, "^N cannot be 0", - WeekOfMonth, n=0, week=1, weekday=1) tm.assert_raises_regex(ValueError, "^Week", WeekOfMonth, n=1, week=4, weekday=0) tm.assert_raises_regex(ValueError, "^Week", WeekOfMonth, @@ -2261,6 +2259,19 @@ def test_offset(self): (-1, 2, 1, date3, datetime(2010, 12, 21)), (-1, 2, 1, date4, datetime(2011, 1, 18)), + (0, 0, 1, date1, datetime(2011, 1, 4)), + (0, 0, 1, date2, datetime(2011, 2, 1)), + (0, 0, 1, date3, datetime(2011, 2, 1)), + (0, 0, 1, date4, datetime(2011, 2, 1)), + (0, 1, 1, date1, datetime(2011, 1, 11)), + (0, 1, 1, date2, datetime(2011, 1, 11)), + (0, 1, 1, date3, datetime(2011, 2, 8)), + (0, 1, 1, date4, datetime(2011, 2, 8)), + (0, 0, 1, date1, datetime(2011, 1, 4)), + (0, 1, 1, date2, datetime(2011, 1, 11)), + (0, 2, 1, date3, datetime(2011, 1, 18)), + (0, 3, 1, date4, datetime(2011, 1, 25)), + (1, 0, 0, date1, datetime(2011, 2, 7)), (1, 0, 0, date2, datetime(2011, 2, 7)), (1, 0, 0, date3, datetime(2011, 2, 7)), diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 2e4be7fbdeebf..749165f894819 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1461,9 +1461,6 @@ def __init__(self, n=1, normalize=False, week=0, weekday=0): self.weekday = weekday self.week = week - if self.n == 0: - raise ValueError('N cannot be 0') - if self.weekday < 0 or self.weekday > 6: raise ValueError('Day must be 0<=day<=6, got {day}' .format(day=self.weekday))
Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [x] closes #20517 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20549
2018-03-30T14:10:52Z
2018-04-21T18:14:15Z
2018-04-21T18:14:15Z
2018-04-21T18:38:01Z
ERR: disallow non-hashables in Index/MultiIndex construction & rename
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index e19aedac80213..3f7c4b3b0ccb7 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -827,6 +827,7 @@ Other API Changes - A :class:`Series` of ``dtype=category`` constructed from an empty ``dict`` will now have categories of ``dtype=object`` rather than ``dtype=float64``, consistently with the case in which an empty list is passed (:issue:`18515`) - All-NaN levels in a ``MultiIndex`` are now assigned ``float`` rather than ``object`` dtype, promoting consistency with ``Index`` (:issue:`17929`). - Levels names of a ``MultiIndex`` (when not None) are now required to be unique: trying to create a ``MultiIndex`` with repeated names will raise a ``ValueError`` (:issue:`18872`) +- Both construction and renaming of ``Index``/``MultiIndex`` with non-hashable ``name``/``names`` will now raise ``TypeError`` (:issue:`20527`) - :func:`Index.map` can now accept ``Series`` and dictionary input objects (:issue:`12756`, :issue:`18482`, :issue:`18509`). - :func:`DataFrame.unstack` will now default to filling with ``np.nan`` for ``object`` columns. (:issue:`12815`) - :class:`IntervalIndex` constructor will raise if the ``closed`` parameter conflicts with how the input data is inferred to be closed (:issue:`18421`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 12bb09e8f8a8a..f392a716d9e5b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -42,6 +42,7 @@ is_datetime64_any_dtype, is_datetime64tz_dtype, is_timedelta64_dtype, + is_hashable, needs_i8_conversion, is_iterator, is_list_like, is_scalar) @@ -1311,9 +1312,33 @@ def _get_names(self): return FrozenList((self.name, )) def _set_names(self, values, level=None): + """ + Set new names on index. Each name has to be a hashable type. + + Parameters + ---------- + values : str or sequence + name(s) to set + level : int, level name, or sequence of int/level names (default None) + If the index is a MultiIndex (hierarchical), level(s) to set (None + for all levels). Otherwise level must be None + + Raises + ------ + TypeError if each name is not hashable. + """ + if not is_list_like(values): + raise ValueError('Names must be a list-like') if len(values) != 1: raise ValueError('Length of new names must be 1, got %d' % len(values)) + + # GH 20527 + # All items in 'name' need to be hashable: + for name in values: + if not is_hashable(name): + raise TypeError('{}.name must be a hashable type' + .format(self.__class__.__name__)) self.name = values[0] names = property(fset=_set_names, fget=_get_names) @@ -1339,9 +1364,9 @@ def set_names(self, names, level=None, inplace=False): Examples -------- >>> Index([1, 2, 3, 4]).set_names('foo') - Int64Index([1, 2, 3, 4], dtype='int64') + Int64Index([1, 2, 3, 4], dtype='int64', name='foo') >>> Index([1, 2, 3, 4]).set_names(['foo']) - Int64Index([1, 2, 3, 4], dtype='int64') + Int64Index([1, 2, 3, 4], dtype='int64', name='foo') >>> idx = MultiIndex.from_tuples([(1, u'one'), (1, u'two'), (2, u'one'), (2, u'two')], names=['foo', 'bar']) @@ -1354,6 +1379,7 @@ def set_names(self, names, level=None, inplace=False): labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[u'baz', u'bar']) """ + if level is not None and self.nlevels == 1: raise ValueError('Level must be None for non-MultiIndex') diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 8098f7bb7d246..fbcf06a28c1e5 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -16,6 +16,7 @@ _ensure_platform_int, is_categorical_dtype, is_object_dtype, + is_hashable, is_iterator, is_list_like, pandas_dtype, @@ -634,12 +635,29 @@ def _get_names(self): def _set_names(self, names, level=None, validate=True): """ + Set new names on index. Each name has to be a hashable type. + + Parameters + ---------- + values : str or sequence + name(s) to set + level : int, level name, or sequence of int/level names (default None) + If the index is a MultiIndex (hierarchical), level(s) to set (None + for all levels). Otherwise level must be None + validate : boolean, default True + validate that the names match level lengths + + Raises + ------ + TypeError if each name is not hashable. + + Notes + ----- sets names on levels. WARNING: mutates! Note that you generally want to set this *after* changing levels, so that it only acts on copies """ - # GH 15110 # Don't allow a single string for names in a MultiIndex if names is not None and not is_list_like(names): @@ -662,10 +680,20 @@ def _set_names(self, names, level=None, validate=True): # set the name for l, name in zip(level, names): - if name is not None and name in used: - raise ValueError('Duplicated level name: "{}", assigned to ' - 'level {}, is already used for level ' - '{}.'.format(name, l, used[name])) + if name is not None: + + # GH 20527 + # All items in 'names' need to be hashable: + if not is_hashable(name): + raise TypeError('{}.name must be a hashable type' + .format(self.__class__.__name__)) + + if name in used: + raise ValueError( + 'Duplicated level name: "{}", assigned to ' + 'level {}, is already used for level ' + '{}.'.format(name, l, used[name])) + self.levels[l].rename(name, inplace=True) used[name] = l diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index a8b81b1b03552..8e10e4c4fbc65 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -125,12 +125,12 @@ def test_getitem_list(self): # tuples df = DataFrame(randn(8, 3), columns=Index([('foo', 'bar'), ('baz', 'qux'), - ('peek', 'aboo')], name=['sth', 'sth2'])) + ('peek', 'aboo')], name=('sth', 'sth2'))) result = df[[('foo', 'bar'), ('baz', 'qux')]] expected = df.iloc[:, :2] assert_frame_equal(result, expected) - assert result.columns.names == ['sth', 'sth2'] + assert result.columns.names == ('sth', 'sth2') def test_getitem_callable(self): # GH 12533 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 7e19de4cca292..682517f5a6fb1 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -435,6 +435,24 @@ def test_constructor_empty(self): assert isinstance(empty, MultiIndex) assert not len(empty) + def test_constructor_nonhashable_name(self, indices): + # GH 20527 + + if isinstance(indices, MultiIndex): + pytest.skip("multiindex handled in test_multi.py") + + name = ['0'] + message = "Index.name must be a hashable type" + tm.assert_raises_regex(TypeError, message, name=name) + + # With .rename() + renamed = [['1']] + tm.assert_raises_regex(TypeError, message, + indices.rename, name=renamed) + # With .set_names() + tm.assert_raises_regex(TypeError, message, + indices.set_names, names=renamed) + def test_view_with_args(self): restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex', diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 984f37042d600..88dc4cbaf7bb3 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -615,8 +615,27 @@ def test_constructor_mismatched_label_levels(self): with tm.assert_raises_regex(ValueError, label_error): self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]]) - @pytest.mark.parametrize('names', [['a', 'b', 'a'], [1, 1, 2], - [1, 'a', 1]]) + def test_constructor_nonhashable_names(self): + # GH 20527 + levels = [[1, 2], [u'one', u'two']] + labels = [[0, 0, 1, 1], [0, 1, 0, 1]] + names = ((['foo'], ['bar'])) + message = "MultiIndex.name must be a hashable type" + tm.assert_raises_regex(TypeError, message, + MultiIndex, levels=levels, + labels=labels, names=names) + + # With .rename() + mi = MultiIndex(levels=[[1, 2], [u'one', u'two']], + labels=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=('foo', 'bar')) + renamed = [['foor'], ['barr']] + tm.assert_raises_regex(TypeError, message, mi.rename, names=renamed) + # With .set_names() + tm.assert_raises_regex(TypeError, message, mi.set_names, names=renamed) + + @pytest.mark.parametrize('names', [['a', 'b', 'a'], ['1', '1', '2'], + ['1', 'a', '1']]) def test_duplicate_level_names(self, names): # GH18872 pytest.raises(ValueError, pd.MultiIndex.from_product,
Index & MultiIndex names need to be hashable. Both constructing and renaming without a hashable name raise TypeError exceptions now. **Examples:** - Index: ``` In [2]: pd.Index([1, 2, 3], name=['foo']) >>> Int64Index([1, 2, 3], dtype='int64', name=['foo']) ``` ``` In [3]: pd.Index([1, 2, 3], name='foo').rename(['bar']) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-f3327eccf0fc> in <module>() ----> 1 pd.Index([1, 2, 3], name='foo').rename(['bar']) ~/Documents/GitHub/pandas/pandas/core/indexes/base.py in rename(self, name, inplace) 1406 new index (of same type and class...etc) [if inplace, returns None] 1407 """ -> 1408 return self.set_names([name], inplace=inplace) 1409 1410 @property ~/Documents/GitHub/pandas/pandas/core/indexes/base.py in set_names(self, names, level, inplace) 1387 else: 1388 idx = self._shallow_copy() -> 1389 idx._set_names(names, level=level) 1390 if not inplace: 1391 return idx ~/Documents/GitHub/pandas/pandas/core/indexes/base.py in _set_names(self, values, level) 1323 if not is_hashable(name): 1324 raise TypeError('{}.name must be a hashable type' -> 1325 .format(self.__class__.__name__)) 1326 if len(values) != 1: 1327 raise ValueError('Length of new names must be 1, got %d' % TypeError: Int64Index.name must be a hashable type ``` - MultiIndex: ``` In [4]: pd.MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=((['foo'], ['bar']))) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-4-d211526eaa3d> in <module>() 1 pd.MultiIndex(levels=[[1, 2], [u'one', u'two']], 2 labels=[[0, 0, 1, 1], [0, 1, 0, 1]], ----> 3 names=((['foo'], ['bar']))) 4 ~/Documents/GitHub/pandas/pandas/core/indexes/multi.py in __new__(cls, levels, labels, sortorder, names, dtype, copy, name, verify_integrity, _set_identity) 230 if names is not None: 231 # handles name validation --> 232 result._set_names(names) 233 234 if sortorder is not None: ~/Documents/GitHub/pandas/pandas/core/indexes/multi.py in _set_names(self, names, level, validate) 646 if not is_hashable(name): 647 raise TypeError('{}.name must be a hashable type' --> 648 .format(self.__class__.__name__)) 649 650 # GH 15110 TypeError: MultiIndex.name must be a hashable type ``` ``` In [10]: pd.MultiIndex(levels=[[1, 2], [u'one', u'two']], labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=('foo', 'bar')).rename(([1], [2])) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-ff74dfc48455> in <module>() 1 pd.MultiIndex(levels=[[1, 2], [u'one', u'two']], 2 labels=[[0, 0, 1, 1], [0, 1, 0, 1]], ----> 3 names=('foo', 'bar')).rename(([1], [2])) 4 ~/Documents/GitHub/pandas/pandas/core/indexes/base.py in set_names(self, names, level, inplace) 1387 else: 1388 idx = self._shallow_copy() -> 1389 idx._set_names(names, level=level) 1390 if not inplace: 1391 return idx ~/Documents/GitHub/pandas/pandas/core/indexes/multi.py in _set_names(self, names, level, validate) 646 if not is_hashable(name): 647 raise TypeError('{}.name must be a hashable type' --> 648 .format(self.__class__.__name__)) 649 650 # GH 15110 TypeError: MultiIndex.name must be a hashable type ``` Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [x] closes [#20527](https://github.com/pandas-dev/pandas/issues/20527) - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20548
2018-03-30T12:41:55Z
2018-04-23T19:05:14Z
2018-04-23T19:05:13Z
2018-06-27T21:13:53Z
CLN: Use pandas.compat instead of sys.version_info for Python version checks
diff --git a/pandas/_version.py b/pandas/_version.py index 624c7b5cd63a1..26e4d987e9f2e 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -12,6 +12,7 @@ import re import subprocess import sys +from pandas.compat import PY3 def get_keywords(): @@ -83,7 +84,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): print("unable to find command, tried %s" % (commands,)) return None stdout = p.communicate()[0].strip() - if sys.version_info[0] >= 3: + if PY3: stdout = stdout.decode() if p.returncode != 0: if verbose: diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index aefa1ddd6cf0b..dc52b5c283678 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -369,7 +369,7 @@ def callable(obj): return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) -if sys.version_info[0] < 3: +if PY2: # In PY2 functools.wraps doesn't provide metadata pytest needs to generate # decorated tests using parametrization. See pytest GH issue #2782 def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, diff --git a/pandas/io/clipboard/clipboards.py b/pandas/io/clipboard/clipboards.py index 285d93e3ca497..0793ca6877cdb 100644 --- a/pandas/io/clipboard/clipboards.py +++ b/pandas/io/clipboard/clipboards.py @@ -1,12 +1,10 @@ -import sys import subprocess from .exceptions import PyperclipException +from pandas.compat import PY2, text_type EXCEPT_MSG = """ Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.org """ -PY2 = sys.version_info[0] == 2 -text_type = unicode if PY2 else str # noqa def init_osx_clipboard(): diff --git a/pandas/io/formats/terminal.py b/pandas/io/formats/terminal.py index 07ab445182680..52262ea05bf96 100644 --- a/pandas/io/formats/terminal.py +++ b/pandas/io/formats/terminal.py @@ -14,8 +14,9 @@ from __future__ import print_function import os -import sys import shutil +from pandas.compat import PY3 + __all__ = ['get_terminal_size', 'is_terminal'] @@ -29,7 +30,7 @@ def get_terminal_size(): """ import platform - if sys.version_info[0] >= 3: + if PY3: return shutil.get_terminal_size() current_os = platform.system() diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 7949636fcafbb..0dd068b90f30f 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -4,9 +4,7 @@ import warnings from datetime import timedelta -from distutils.version import LooseVersion import operator -import sys import pytest from string import ascii_lowercase @@ -1857,13 +1855,8 @@ def test_round(self): 'col1': [1.123, 2.123, 3.123], 'col2': [1.2, 2.2, 3.2]}) - if LooseVersion(sys.version) < LooseVersion('2.7'): - # Rounding with decimal is a ValueError in Python < 2.7 - with pytest.raises(ValueError): - df.round(nan_round_Series) - else: - with pytest.raises(TypeError): - df.round(nan_round_Series) + with pytest.raises(TypeError): + df.round(nan_round_Series) # Make sure this doesn't break existing Series.round tm.assert_series_equal(df['col1'].round(1), expected_rounded['col1']) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index b2cbd0b07d7f5..78a19029db567 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -7,8 +7,6 @@ # pylint: disable-msg=W0612,E1101 from copy import deepcopy import pydoc -import sys -from distutils.version import LooseVersion from pandas.compat import range, lrange, long from pandas import compat @@ -253,18 +251,14 @@ def test_itertuples(self): '[(0, 1, 4), (1, 2, 5), (2, 3, 6)]') tup = next(df.itertuples(name='TestName')) - - if LooseVersion(sys.version) >= LooseVersion('2.7'): - assert tup._fields == ('Index', 'a', 'b') - assert (tup.Index, tup.a, tup.b) == tup - assert type(tup).__name__ == 'TestName' + assert tup._fields == ('Index', 'a', 'b') + assert (tup.Index, tup.a, tup.b) == tup + assert type(tup).__name__ == 'TestName' df.columns = ['def', 'return'] tup2 = next(df.itertuples(name='TestName')) assert tup2 == (0, 1, 4) - - if LooseVersion(sys.version) >= LooseVersion('2.7'): - assert tup2._fields == ('Index', '_1', '_2') + assert tup2._fields == ('Index', '_1', '_2') df3 = DataFrame({'f' + str(i): [i] for i in range(1024)}) # will raise SyntaxError if trying to create namedtuple diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index fb7677bb1449c..45be3974dad63 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -1,6 +1,5 @@ """ test to_datetime """ -import sys import pytz import pytest import locale @@ -149,9 +148,6 @@ def test_to_datetime_with_non_exact(self, cache): # GH 10834 # 8904 # exact kw - if sys.version_info < (2, 7): - pytest.skip('on python version < 2.7') - s = Series(['19MAY11', 'foobar19MAY11', '19MAY11:00:00:00', '19MAY11 00:00:00Z']) result = to_datetime(s, format='%d%b%y', exact=False, cache=cache) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index ab9f61cffc16b..dde0691907b20 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1256,8 +1256,6 @@ def test_to_string_float_formatting(self): df_s = df.to_string() - # Python 2.5 just wants me to be sad. And debian 32-bit - # sys.version_info[0] == 2 and sys.version_info[1] < 6: if _three_digit_exp(): expected = (' x\n0 0.00000e+000\n1 2.50000e-001\n' '2 3.45600e+003\n3 1.20000e+046\n4 1.64000e+006\n' @@ -1281,8 +1279,7 @@ def test_to_string_float_formatting(self): df = DataFrame({'x': [1e9, 0.2512]}) df_s = df.to_string() - # Python 2.5 just wants me to be sad. And debian 32-bit - # sys.version_info[0] == 2 and sys.version_info[1] < 6: + if _three_digit_exp(): expected = (' x\n' '0 1.000000e+009\n' diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index cf7ec9e2f2652..2423ddcd9a1a0 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -1275,10 +1275,8 @@ def test_verbose_import(self): else: # Python engine assert output == 'Filled 1 NA values in column a\n' + @pytest.mark.skipif(PY3, reason="won't work in Python 3") def test_iteration_open_handle(self): - if PY3: - pytest.skip( - "won't work in Python 3 {0}".format(sys.version_info)) with tm.ensure_clean() as path: with open(path, 'wb') as f: diff --git a/pandas/tests/io/test_excel.py b/pandas/tests/io/test_excel.py index 6b39717213c0d..cbb5932a890dc 100644 --- a/pandas/tests/io/test_excel.py +++ b/pandas/tests/io/test_excel.py @@ -1,6 +1,5 @@ # pylint: disable=E1101 import os -import sys import warnings from datetime import datetime, date, time, timedelta from distutils.version import LooseVersion @@ -16,7 +15,7 @@ import pandas.util.testing as tm import pandas.util._test_decorators as td from pandas import DataFrame, Index, MultiIndex -from pandas.compat import u, range, map, BytesIO, iteritems +from pandas.compat import u, range, map, BytesIO, iteritems, PY36 from pandas.core.config import set_option, get_option from pandas.io.common import URLError from pandas.io.excel import ( @@ -585,9 +584,6 @@ def test_read_from_s3_url(self, ext): def test_read_from_file_url(self, ext): # FILE - if sys.version_info[:2] < (2, 6): - pytest.skip("file:// not supported with Python < 2.6") - localtable = os.path.join(self.dirpath, 'test1' + ext) local_table = read_excel(localtable) @@ -2314,9 +2310,9 @@ def custom_converter(css): @td.skip_if_no('openpyxl') +@pytest.mark.skipif(not PY36, reason='requires fspath') class TestFSPath(object): - @pytest.mark.skipif(sys.version_info < (3, 6), reason='requires fspath') def test_excelfile_fspath(self): with tm.ensure_clean('foo.xlsx') as path: df = DataFrame({"A": [1, 2]}) @@ -2325,8 +2321,6 @@ def test_excelfile_fspath(self): result = os.fspath(xl) assert result == path - @pytest.mark.skipif(sys.version_info < (3, 6), reason='requires fspath') - # @pytest.mark.xfail def test_excelwriter_fspath(self): with tm.ensure_clean('foo.xlsx') as path: writer = ExcelWriter(path) diff --git a/pandas/tests/io/test_packers.py b/pandas/tests/io/test_packers.py index 919b34dc09f6f..cfac77291803d 100644 --- a/pandas/tests/io/test_packers.py +++ b/pandas/tests/io/test_packers.py @@ -4,7 +4,6 @@ import os import datetime import numpy as np -import sys from distutils.version import LooseVersion from pandas import compat @@ -298,11 +297,6 @@ def test_nat(self): def test_datetimes(self): - # fails under 2.6/win32 (np.datetime64 seems broken) - - if LooseVersion(sys.version) < LooseVersion('2.7'): - pytest.skip('2.6 with np.datetime64 is broken') - for i in [datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 1, 5, 1), datetime.date(2013, 1, 1), diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 6bc3af2ba3fd2..fbe2174e603e2 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -20,13 +20,12 @@ from distutils.version import LooseVersion import pandas as pd from pandas import Index -from pandas.compat import is_platform_little_endian +from pandas.compat import is_platform_little_endian, PY3 import pandas import pandas.util.testing as tm import pandas.util._test_decorators as td from pandas.tseries.offsets import Day, MonthEnd import shutil -import sys @pytest.fixture(scope='module') @@ -474,21 +473,12 @@ def test_read(self, protocol, get_random_path): tm.assert_frame_equal(df, df2) @pytest.mark.parametrize('protocol', [3, 4]) - @pytest.mark.skipif(sys.version_info[:2] >= (3, 4), - reason="Testing invalid parameters for " - "Python 2.x and 3.y (y < 4).") + @pytest.mark.skipif(PY3, reason="Testing invalid parameters for Python 2") def test_read_bad_versions(self, protocol, get_random_path): - # For Python 2.x (respectively 3.y with y < 4), [expected] - # HIGHEST_PROTOCOL should be 2 (respectively 3). Hence, the protocol - # parameter should not exceed 2 (respectively 3). - if sys.version_info[:2] < (3, 0): - expect_hp = 2 - else: - expect_hp = 3 - with tm.assert_raises_regex(ValueError, - "pickle protocol %d asked for; the highest" - " available protocol is %d" % (protocol, - expect_hp)): + # For Python 2, HIGHEST_PROTOCOL should be 2. + msg = ("pickle protocol {protocol} asked for; the highest available " + "protocol is 2").format(protocol=protocol) + with tm.assert_raises_regex(ValueError, msg): with tm.ensure_clean(get_random_path) as path: df = tm.makeDataFrame() df.to_pickle(path, protocol=protocol) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 49ad07b79d111..972a47ef91c05 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -4,10 +4,8 @@ import datetime as dt import os import struct -import sys import warnings from datetime import datetime -from distutils.version import LooseVersion from collections import OrderedDict import numpy as np @@ -144,8 +142,6 @@ def test_read_dta1(self, file): tm.assert_frame_equal(parsed, expected) def test_read_dta2(self): - if LooseVersion(sys.version) < LooseVersion('2.7'): - pytest.skip('datetime interp under 2.6 is faulty') expected = DataFrame.from_records( [ diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index 72d87be619917..50e72c11abc4b 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -import sys from datetime import datetime import operator @@ -9,7 +8,7 @@ from dateutil.tz import tzutc from pytz import utc -from pandas.compat import long +from pandas.compat import long, PY2 from pandas import Timestamp @@ -104,7 +103,7 @@ def test_cant_compare_tz_naive_w_aware(self): pytest.raises(Exception, b.__lt__, a) pytest.raises(Exception, b.__gt__, a) - if sys.version_info < (3, 3): + if PY2: pytest.raises(Exception, a.__eq__, b.to_pydatetime()) pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: @@ -125,7 +124,7 @@ def test_cant_compare_tz_naive_w_aware_explicit_pytz(self): pytest.raises(Exception, b.__lt__, a) pytest.raises(Exception, b.__gt__, a) - if sys.version_info < (3, 3): + if PY2: pytest.raises(Exception, a.__eq__, b.to_pydatetime()) pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: @@ -146,7 +145,7 @@ def test_cant_compare_tz_naive_w_aware_dateutil(self): pytest.raises(Exception, b.__lt__, a) pytest.raises(Exception, b.__gt__, a) - if sys.version_info < (3, 3): + if PY2: pytest.raises(Exception, a.__eq__, b.to_pydatetime()) pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index 2bc017ef226ce..145be7f85b193 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -7,7 +7,7 @@ from collections import OrderedDict import pytest -from pandas.compat import intern +from pandas.compat import intern, PY3 import pandas.core.common as com from pandas.util._move import move_into_mutable_buffer, BadMove, stolenbuf from pandas.util._decorators import deprecate_kwarg, make_signature @@ -374,10 +374,7 @@ def test_exactly_one_ref(self): # materialize as bytearray to show that it is mutable assert bytearray(as_stolen_buf) == b'test' - @pytest.mark.skipif( - sys.version_info[0] > 2, - reason='bytes objects cannot be interned in py3', - ) + @pytest.mark.skipif(PY3, reason='bytes objects cannot be interned in py3') def test_interned(self): salt = uuid4().hex diff --git a/pandas/util/testing.py b/pandas/util/testing.py index f72c3b061208c..6e13a17eba68c 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2088,7 +2088,7 @@ def dec(f): # and conditionally raise on these exception types _network_error_classes = (IOError, httplib.HTTPException) -if sys.version_info >= (3, 3): +if PY3: _network_error_classes += (TimeoutError,) # noqa
Hopefully this will make code changes related to dropping support for specific versions of Python slightly easier to identify. Summary: - Replaced instances `sys.version_info` with equivalent checks from `pandas.compat` - Removed code blocks specific to unsupported versions of Python (<2.7, 3.0-3.4) <br /> There were some very specific examples that I left as-is: https://github.com/pandas-dev/pandas/blob/c4b4a81f56205082ec7f12bf77766e3b74d27c37/pandas/tests/io/formats/test_to_csv.py#L13 Didn't change any Cython related code, as it appears that we want to avoid imports from outside `_libs`: https://github.com/pandas-dev/pandas/blob/c4b4a81f56205082ec7f12bf77766e3b74d27c37/pandas/_libs/tslibs/parsing.pyx#L25-L26
https://api.github.com/repos/pandas-dev/pandas/pulls/20545
2018-03-30T02:41:28Z
2018-03-31T16:01:21Z
2018-03-31T16:01:21Z
2018-09-24T17:25:07Z
Deprecated Index.get_duplicates()
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 3f7c4b3b0ccb7..eb0fa49170d44 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -887,6 +887,7 @@ Deprecations - :func:`Series.rolling().apply() <pandas.core.window.Rolling.apply>`, :func:`DataFrame.rolling().apply() <pandas.core.window.Rolling.apply>`, :func:`Series.expanding().apply() <pandas.core.window.Expanding.apply>`, and :func:`DataFrame.expanding().apply() <pandas.core.window.Expanding.apply>` have deprecated passing an ``np.array`` by default. One will need to pass the new ``raw`` parameter to be explicit about what is passed (:issue:`20584`) - ``DatetimeIndex.offset`` is deprecated. Use ``DatetimeIndex.freq`` instead (:issue:`20716`) +- ``Index.get_duplicates()`` is deprecated and will be removed in a future version (:issue:`20239`) .. _whatsnew_0230.prior_deprecations: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b67ed9cfd2241..35bfd12466429 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3879,7 +3879,7 @@ def set_index(self, keys, drop=True, append=False, inplace=False, index = _ensure_index_from_sequences(arrays, names) if verify_integrity and not index.is_unique: - duplicates = index.get_duplicates() + duplicates = index[index.duplicated()].unique() raise ValueError('Index has duplicate keys: {dup}'.format( dup=duplicates)) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2e6e039add8a4..3d60eefc5b598 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1851,6 +1851,9 @@ def get_duplicates(self): Returns a sorted list of index elements which appear more than once in the index. + .. deprecated:: 0.23.0 + Use idx[idx.duplicated()].unique() instead + Returns ------- array-like @@ -1897,13 +1900,12 @@ def get_duplicates(self): >>> pd.Index(dates).get_duplicates() DatetimeIndex([], dtype='datetime64[ns]', freq=None) """ - from collections import defaultdict - counter = defaultdict(lambda: 0) - for k in self.values: - counter[k] += 1 - return sorted(k for k, v in compat.iteritems(counter) if v > 1) + warnings.warn("'get_duplicates' is deprecated and will be removed in " + "a future release. You can use " + "idx[idx.duplicated()].unique() instead", + FutureWarning, stacklevel=2) - _get_duplicates = get_duplicates + return self[self.duplicated()].unique() def _cleanup(self): self._engine.clear_mapping() diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 95186b2e79a16..51cd1837fecca 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -502,10 +502,6 @@ def take(self, indices, axis=0, allow_fill=True, freq = self.freq if isinstance(self, ABCPeriodIndex) else None return self._shallow_copy(taken, freq=freq) - def get_duplicates(self): - values = Index.get_duplicates(self) - return self._simple_new(values) - _can_hold_na = True _na_value = NaT diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 20f4384a3d698..6e564975f34cd 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -504,7 +504,7 @@ def _get_concat_axis(self): def _maybe_check_integrity(self, concat_index): if self.verify_integrity: if not concat_index.is_unique: - overlap = concat_index.get_duplicates() + overlap = concat_index[concat_index.duplicated()].unique() raise ValueError('Indexes have overlapping values: ' '{overlap!s}'.format(overlap=overlap)) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 2d55dfff7a8f3..0722b9175c0c6 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -1,3 +1,4 @@ +import warnings import pytest @@ -178,7 +179,10 @@ def test_get_duplicates(self): idx = DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-02', '2000-01-03', '2000-01-03', '2000-01-04']) - result = idx.get_duplicates() + with warnings.catch_warnings(record=True): + # Deprecated - see GH20239 + result = idx.get_duplicates() + ex = DatetimeIndex(['2000-01-02', '2000-01-03']) tm.assert_index_equal(result, ex) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 682517f5a6fb1..8cb75f8cfb906 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2078,6 +2078,11 @@ def test_cached_properties_not_settable(self): with tm.assert_raises_regex(AttributeError, "Can't set attribute"): idx.is_unique = False + def test_get_duplicates_deprecated(self): + idx = pd.Index([1, 2, 3]) + with tm.assert_produces_warning(FutureWarning): + idx.get_duplicates() + class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 88dc4cbaf7bb3..cc006baa64ce6 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -2432,7 +2432,12 @@ def check(nlevels, with_nulls): for a in [101, 102]: mi = MultiIndex.from_arrays([[101, a], [3.5, np.nan]]) assert not mi.has_duplicates - assert mi.get_duplicates() == [] + + with warnings.catch_warnings(record=True): + # Deprecated - see GH20239 + assert mi.get_duplicates().equals(MultiIndex.from_arrays( + [[], []])) + tm.assert_numpy_array_equal(mi.duplicated(), np.zeros( 2, dtype='bool')) @@ -2444,7 +2449,12 @@ def check(nlevels, with_nulls): labels=np.random.permutation(list(lab)).T) assert len(mi) == (n + 1) * (m + 1) assert not mi.has_duplicates - assert mi.get_duplicates() == [] + + with warnings.catch_warnings(record=True): + # Deprecated - see GH20239 + assert mi.get_duplicates().equals(MultiIndex.from_arrays( + [[], []])) + tm.assert_numpy_array_equal(mi.duplicated(), np.zeros( len(mi), dtype='bool')) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 4692b6d675e6b..d7745ffd94cd9 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -1,3 +1,5 @@ +import warnings + import pytest import numpy as np @@ -145,7 +147,10 @@ def test_get_duplicates(self): idx = TimedeltaIndex(['1 day', '2 day', '2 day', '3 day', '3day', '4day']) - result = idx.get_duplicates() + with warnings.catch_warnings(record=True): + # Deprecated - see GH20239 + result = idx.get_duplicates() + ex = TimedeltaIndex(['2 day', '3day']) tm.assert_index_equal(result, ex)
- [X] closes #20239 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20544
2018-03-30T01:37:36Z
2018-04-24T10:17:16Z
2018-04-24T10:17:16Z
2018-04-24T15:41:53Z
DOC: Sprint recap
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index e83f149db1f18..560eb0df8ccf7 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -901,6 +901,22 @@ Performance Improvements Documentation Changes ~~~~~~~~~~~~~~~~~~~~~ +Thanks to all of the contributors who participated in the Pandas Documentation +Sprint, which took place on March 10th. We had about 500 participants from over +30 locations across the world. You should notice that many of the +:ref:`API docstrings <api>` have greatly improved. + +There were too many simultaneous contributions to include a release note for each +improvement, but this `GitHub search`_ should give you an idea of how many docstrings +were improved. + +Special thanks to Marc Garcia for organizing the sprint. For more information, +read the `NumFOCUS blogpost`_ recapping the sprint. + +.. _GitHub search: https://github.com/pandas-dev/pandas/pulls?utf8=%E2%9C%93&q=is%3Apr+label%3ADocs+created%3A2018-03-10..2018-03-15+ +.. _NumFOCUS blogpost: https://www.numfocus.org/blog/worldwide-pandas-sprint/ + + - Changed spelling of "numpy" to "NumPy", and "python" to "Python". (:issue:`19017`) - Consistency when introducing code samples, using either colon or period. Rewrote some sentences for greater clarity, added more dynamic references
Included a small note for this. Should we plan a blogpost as well? closes #20515
https://api.github.com/repos/pandas-dev/pandas/pulls/20543
2018-03-29T21:31:09Z
2018-03-30T20:03:41Z
2018-03-30T20:03:41Z
2018-10-25T19:10:38Z
[WIP]DOC: Fixed more warnings
diff --git a/doc/source/merging.rst b/doc/source/merging.rst index cfd3f9e88e4ea..74b21c21252ec 100644 --- a/doc/source/merging.rst +++ b/doc/source/merging.rst @@ -583,7 +583,7 @@ and ``right`` is a subclass of DataFrame, the return type will still be ``merge`` is a function in the pandas namespace, and it is also available as a ``DataFrame`` instance method :meth:`~DataFrame.merge`, with the calling -``DataFrame `` being implicitly considered the left object in the join. +``DataFrame`` being implicitly considered the left object in the join. The related :meth:`~DataFrame.join` method, uses ``merge`` internally for the index-on-index (by default) and column(s)-on-index join. If you are joining on @@ -1202,7 +1202,7 @@ Overlapping value columns ~~~~~~~~~~~~~~~~~~~~~~~~~ The merge ``suffixes`` argument takes a tuple of list of strings to append to -overlapping column names in the input ``DataFrame``s to disambiguate the result +overlapping column names in the input ``DataFrame``\ s to disambiguate the result columns: .. ipython:: python diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 6e5e113e859d7..e1b561c4deacb 100644 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -58,7 +58,7 @@ We can render the HTML to get the following table. :file: whatsnew_0171_html_table.html :class:`~pandas.core.style.Styler` interacts nicely with the Jupyter Notebook. -See the :ref:`documentation <style.ipynb>` for more. +See the :doc:`documentation <style>` for more. .. _whatsnew_0171.enhancements: diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index d04a34f7a44d6..5f22b518ab6c4 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -389,7 +389,7 @@ For example, after running the following, ``styled.xlsx`` renders as below: import os os.remove('styled.xlsx') -See the :ref:`Style documentation <style.ipynb#Export-to-Excel>` for more detail. +See the :ref:`Style documentation </style.ipynb#Export-to-Excel>` for more detail. .. _whatsnew_0200.enhancements.intervalindex: @@ -499,7 +499,7 @@ Other Enhancements - ``DataFrame.to_excel()`` has a new ``freeze_panes`` parameter to turn on Freeze Panes when exporting to Excel (:issue:`15160`) - ``pd.read_html()`` will parse multiple header rows, creating a MutliIndex header. (:issue:`13434`). - HTML table output skips ``colspan`` or ``rowspan`` attribute if equal to 1. (:issue:`15403`) -- :class:`pandas.io.formats.style.Styler` template now has blocks for easier extension, :ref:`see the example notebook <style.ipynb#Subclassing>` (:issue:`15649`) +- :class:`pandas.io.formats.style.Styler` template now has blocks for easier extension, see the :ref:`example notebook </style.ipynb#Subclassing>` (:issue:`15649`) - :meth:`Styler.render() <pandas.io.formats.style.Styler.render>` now accepts ``**kwargs`` to allow user-defined variables in the template (:issue:`15649`) - Compatibility with Jupyter notebook 5.0; MultiIndex column labels are left-aligned and MultiIndex row-labels are top-aligned (:issue:`15379`) - ``TimedeltaIndex`` now has a custom date-tick formatter specifically designed for nanosecond level precision (:issue:`8711`) diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index e83f149db1f18..9e561a288f1d8 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -330,7 +330,6 @@ for storing ip addresses. .. code-block:: ipython In [3]: ser = pd.Series(values) - ...: In [4]: ser Out[4]: @@ -342,8 +341,9 @@ for storing ip addresses. Notice that the dtype is ``ip``. The missing value semantics of the underlying array are respected: +.. code-block:: ipython + In [5]: ser.isna() - ...: Out[5]: 0 True 1 False
Also trying to fail on warnings. I think it's not working yet.
https://api.github.com/repos/pandas-dev/pandas/pulls/20542
2018-03-29T21:12:20Z
2018-04-04T19:20:20Z
2018-04-04T19:20:20Z
2018-04-08T09:58:34Z
DOC: Plans for 2.7
diff --git a/doc/source/install.rst b/doc/source/install.rst index c96d4fbeb4ad2..82a97ba7b04e1 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -15,6 +15,31 @@ Instructions for installing from source, `PyPI <http://pypi.python.org/pypi/pandas>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, various Linux distributions, or a `development version <http://github.com/pandas-dev/pandas>`__ are also provided. +.. _install.dropping_27 + +Plan for dropping Python 2.7 +---------------------------- + +The Python core team plans to stop supporting Python 2.7 on January 1st, 2020. +In line with `NumPy's plans`_, all pandas releases through December 31, 2018 +will support Python 2. + +The final release before **December 31, 2018** will be the last release to +support Python 2. The released package will continue to be available on +PyPI and through conda. + +Starting **January 1, 2019**, all releases will be Python 3 only. + +If there are people interested in continued support for Python 2.7 past December +31, 2018 (either backporting bugfixes or funding) please reach out to the +maintainers on the issue tracker. + +For more information, see the `Python 3 statement`_ and the `Porting to Python 3 guide`_. + +.. _NumPy's plans: https://github.com/numpy/numpy/blob/master/doc/neps/nep-0014-dropping-python2.7-proposal.rst#plan-for-dropping-python-27-support +.. _Python 3 statement: http://python3statement.org/ +.. _Porting to Python 3 guide: https://docs.python.org/3/howto/pyporting.html + Python version support ---------------------- diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index c6dadb7589869..de49ea754fc69 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -8,6 +8,11 @@ deprecations, new features, enhancements, and performance improvements along with a large number of bug fixes. We recommend that all users upgrade to this version. +.. warning:: + + Starting January 1, 2019, pandas feature releases will support Python 3 only. + See :ref:`install.dropping_27` for more. + .. _whatsnew_0230.enhancements: New features
Closes https://github.com/pandas-dev/pandas/issues/18894 Just some sample text, essentially following NumPy. Of course, it'd be nice if 1.0 happened to be the LTS, but we'll see.
https://api.github.com/repos/pandas-dev/pandas/pulls/20540
2018-03-29T19:34:02Z
2018-04-14T13:41:44Z
2018-04-14T13:41:43Z
2018-05-06T08:08:48Z
ERR: Better error message for missing matplotlib
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index c6dadb7589869..5f008a7bc8dea 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1024,6 +1024,7 @@ I/O Plotting ^^^^^^^^ +- Better error message when attempting to plot but matplotlib is not installed (:issue:`19810`). - :func:`DataFrame.plot` now raises a ``ValueError`` when the ``x`` or ``y`` argument is improperly formed (:issue:`18671`) - Bug in :func:`DataFrame.plot` when ``x`` and ``y`` arguments given as positions caused incorrect referenced columns for line, bar and area plots (:issue:`20056`) - Bug in formatting tick labels with ``datetime.time()`` and fractional seconds (:issue:`18478`). diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 6c3d07124215b..c5f72cb391572 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -44,12 +44,19 @@ try: from pandas.plotting import _converter except ImportError: - pass + _HAS_MPL = False else: + _HAS_MPL = True if get_option('plotting.matplotlib.register_converters'): _converter.register(explicit=True) +def _raise_if_no_mpl(): + # TODO(mpl_converter): remove once converter is explicit + if not _HAS_MPL: + raise ImportError("matplotlib is required for plotting.") + + def _get_standard_kind(kind): return {'density': 'kde'}.get(kind, kind) @@ -97,6 +104,7 @@ def __init__(self, data, kind=None, by=None, subplots=False, sharex=None, secondary_y=False, colormap=None, table=False, layout=None, **kwds): + _raise_if_no_mpl() _converter._WARN = False self.data = data self.by = by @@ -2264,6 +2272,7 @@ def hist_frame(data, column=None, by=None, grid=True, xlabelsize=None, ... }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3) """ + _raise_if_no_mpl() _converter._WARN = False if by is not None: axes = grouped_hist(data, column=column, by=by, ax=ax, grid=grid, @@ -2403,6 +2412,7 @@ def grouped_hist(data, column=None, by=None, ax=None, bins=50, figsize=None, ------- axes: collection of Matplotlib Axes """ + _raise_if_no_mpl() _converter._WARN = False def plot_group(group, ax): @@ -2469,6 +2479,7 @@ def boxplot_frame_groupby(grouped, subplots=True, column=None, fontsize=None, >>> grouped = df.unstack(level='lvl1').groupby(level=0, axis=1) >>> boxplot_frame_groupby(grouped, subplots=False) """ + _raise_if_no_mpl() _converter._WARN = False if subplots is True: naxes = len(grouped) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index c5ce8aba9d80e..c82c939584dc7 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -17,6 +17,15 @@ from pandas.tests.plotting.common import TestPlotBase, _check_plot_works +@td.skip_if_mpl +def test_import_error_message(): + # GH-19810 + df = DataFrame({"A": [1, 2]}) + + with tm.assert_raises_regex(ImportError, 'matplotlib is required'): + df.plot() + + @td.skip_if_no_mpl class TestSeriesPlots(TestPlotBase): diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index 8ad73538fbec1..ab6dfee9c862c 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -160,6 +160,8 @@ def decorated_func(func): skip_if_no_mpl = pytest.mark.skipif(_skip_if_no_mpl(), reason="Missing matplotlib dependency") +skip_if_mpl = pytest.mark.skipif(not _skip_if_no_mpl(), + reason="matplotlib is present") skip_if_mpl_1_5 = pytest.mark.skipif(_skip_if_mpl_1_5(), reason="matplotlib 1.5") xfail_if_mpl_2_2 = pytest.mark.xfail(_skip_if_mpl_2_2(),
Closes https://github.com/pandas-dev/pandas/issues/19810
https://api.github.com/repos/pandas-dev/pandas/pulls/20538
2018-03-29T18:45:37Z
2018-04-09T08:01:39Z
2018-04-09T08:01:39Z
2018-04-09T08:01:39Z
BUG: Presence of softlink in HDF5 file breaks HDFStore.keys() (GH20523)
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 09bd09b06d9b9..fb63dc16249b2 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1098,6 +1098,7 @@ I/O - Bug in :func:`read_pickle` when unpickling objects with :class:`TimedeltaIndex` or :class:`Float64Index` created with pandas prior to version 0.20 (:issue:`19939`) - Bug in :meth:`pandas.io.json.json_normalize` where subrecords are not properly normalized if any subrecords values are NoneType (:issue:`20030`) - Bug in ``usecols`` parameter in :func:`pandas.io.read_csv` and :func:`pandas.io.read_table` where error is not raised correctly when passing a string. (:issue:`20529`) +- Bug in :func:`HDFStore.keys` when reading a file with a softlink causes exception (:issue:`20523`) Plotting ^^^^^^^^ diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 2437b7d396e84..f9a496edb45a3 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1073,10 +1073,11 @@ def groups(self): self._check_if_open() return [ g for g in self._handle.walk_nodes() - if (getattr(g._v_attrs, 'pandas_type', None) or - getattr(g, 'table', None) or + if (not isinstance(g, _table_mod.link.Link) and + (getattr(g._v_attrs, 'pandas_type', None) or + getattr(g, 'table', None) or (isinstance(g, _table_mod.table.Table) and - g._v_name != u('table'))) + g._v_name != u('table')))) ] def get_node(self, key): diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index e690b1e302d8b..b34723d6cf72c 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -373,6 +373,23 @@ def test_keys(self): assert set(store.keys()) == expected assert set(store) == expected + def test_keys_ignore_hdf_softlink(self): + + # GH 20523 + # Puts a softlink into HDF file and rereads + + with ensure_clean_store(self.path) as store: + + df = DataFrame(dict(A=lrange(5), B=lrange(5))) + store.put("df", df) + + assert store.keys() == ["/df"] + + store._handle.create_soft_link(store._handle.root, "symlink", "df") + + # Should ignore the softlink + assert store.keys() == ["/df"] + def test_iter_empty(self): with ensure_clean_store(self.path) as store:
- [x] closes #20523 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20537
2018-03-29T13:43:21Z
2018-04-03T13:00:17Z
2018-04-03T13:00:16Z
2018-04-03T13:01:48Z
DOC: Extension whatsenw
diff --git a/ci/build_docs.sh b/ci/build_docs.sh index 5de9e158bcdb6..90a666dc34ed7 100755 --- a/ci/build_docs.sh +++ b/ci/build_docs.sh @@ -24,6 +24,7 @@ if [ "$DOC" ]; then source activate pandas mv "$TRAVIS_BUILD_DIR"/doc /tmp + mv "$TRAVIS_BUILD_DIR/LICENSE" /tmp # included in the docs. cd /tmp/doc echo ############################### diff --git a/doc/source/api.rst b/doc/source/api.rst index a5d24302e69e2..5e794c11658e8 100644 --- a/doc/source/api.rst +++ b/doc/source/api.rst @@ -2576,4 +2576,3 @@ objects. generated/pandas.Series.ix generated/pandas.Series.imag generated/pandas.Series.real - generated/pandas.Timestamp.offset diff --git a/doc/source/io.rst b/doc/source/io.rst index 68b431925d983..ff505f525fc22 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2263,7 +2263,7 @@ round-trippable manner. new_df.dtypes Please note that the literal string 'index' as the name of an :class:`Index` -is not round-trippable, nor are any names beginning with 'level_' within a +is not round-trippable, nor are any names beginning with ``'level_'`` within a :class:`MultiIndex`. These are used by default in :func:`DataFrame.to_json` to indicate missing values and the subsequent read cannot distinguish the intent. diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index 86cff4a358975..adb4cdf2974a0 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -198,8 +198,9 @@ This could also potentially speed up the conversion considerably. pd.to_datetime('12-11-2010 00:00', format='%d-%m-%Y %H:%M') For more information on the choices available when specifying the ``format`` -option, see the Python `datetime documentation -<https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior`__. +option, see the Python `datetime documentation`_. + +.. _datetime documentation: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior Assembling Datetime from Multiple DataFrame Columns ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index c6dadb7589869..e83f149db1f18 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -299,6 +299,63 @@ Supplying a ``CategoricalDtype`` will make the categories in each column consist df['A'].dtype df['B'].dtype +.. _whatsnew_023.enhancements.extension: + +Extending Pandas with Custom Types +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Pandas now supports storing array-like objects that aren't necessarily 1-D NumPy +arrays as columns in a DataFrame or values in a Series. This allows third-party +libraries to implement extensions to NumPy's types, similar to how pandas +implemented categoricals, datetimes with timezones, periods, and intervals. + +As a demonstration, we'll use cyberpandas_, which provides an ``IPArray`` type +for storing ip addresses. + +.. code-block:: ipython + + In [1]: from cyberpandas import IPArray + + In [2]: values = IPArray([ + ...: 0, + ...: 3232235777, + ...: 42540766452641154071740215577757643572 + ...: ]) + ...: + ...: + +``IPArray`` isn't a normal 1-D NumPy array, but because it's a pandas +``ExtensionArray``, it can be stored properly inside pandas' containers. + +.. code-block:: ipython + + In [3]: ser = pd.Series(values) + ...: + + In [4]: ser + Out[4]: + 0 0.0.0.0 + 1 192.168.1.1 + 2 2001:db8:85a3::8a2e:370:7334 + dtype: ip + +Notice that the dtype is ``ip``. The missing value semantics of the underlying +array are respected: + + In [5]: ser.isna() + ...: + Out[5]: + 0 True + 1 False + 2 False + dtype: bool + +For more, see the :ref:`extension types <extending.extension-types>` +documentation. If you build an extension array, publicize it on our +:ref:`ecosystem page <ecosystem.extensions>`. + +.. _cyberpandas: https://cyberpandas.readthedocs.io/en/latest/ + .. _whatsnew_0230.enhancements.other: Other Enhancements diff --git a/pandas/core/series.py b/pandas/core/series.py index 89075e5e6acbb..30e0319346961 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -468,7 +468,7 @@ def asobject(self): .. deprecated :: 0.23.0 - Use ``astype(object) instead. + Use ``astype(object)`` instead. *this is an internal non-public method* """
Closes https://github.com/pandas-dev/pandas/issues/20532
https://api.github.com/repos/pandas-dev/pandas/pulls/20533
2018-03-29T12:10:56Z
2018-03-29T20:10:04Z
2018-03-29T20:10:04Z
2018-03-29T20:10:09Z
COMPAT: 32-bit compat for testing
diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index ada4f880e92a4..8a8a6f7de70d7 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -266,7 +266,7 @@ def test_parametrized_factorize_na_value_default(self, data): # arrays that include the NA default for that type, but isn't used. l, u = algos.factorize(data) expected_uniques = data[[0, 1]] - expected_labels = np.array([0, 1, 0], dtype='i8') + expected_labels = np.array([0, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(l, expected_labels) tm.assert_numpy_array_equal(u, expected_uniques) @@ -283,7 +283,7 @@ def test_parametrized_factorize_na_value_default(self, data): def test_parametrized_factorize_na_value(self, data, na_value): l, u = algos._factorize_array(data, na_value=na_value) expected_uniques = data[[1, 3]] - expected_labels = np.array([-1, 0, -1, 1], dtype='i8') + expected_labels = np.array([-1, 0, -1, 1], dtype=np.intp) tm.assert_numpy_array_equal(l, expected_labels) tm.assert_numpy_array_equal(u, expected_uniques)
xref #20502
https://api.github.com/repos/pandas-dev/pandas/pulls/20528
2018-03-29T10:17:36Z
2018-03-30T19:01:17Z
2018-03-30T19:01:17Z
2018-03-30T19:01:48Z
PERF: GH2003 Series.isin for categorical dtypes
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 7743921003353..0ffd5f881d626 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -148,3 +148,24 @@ def time_rank_int_cat(self): def time_rank_int_cat_ordered(self): self.s_int_cat_ordered.rank() + + +class Isin(object): + + goal_time = 0.2 + + params = ['object', 'int64'] + param_names = ['dtype'] + + def setup(self, dtype): + np.random.seed(1234) + n = 5 * 10**5 + sample_size = 100 + arr = [i for i in np.random.randint(0, n // 10, size=n)] + if dtype == 'object': + arr = ['s%04d' % i for i in arr] + self.sample = np.random.choice(arr, sample_size) + self.series = pd.Series(arr).astype('category') + + def time_isin_categorical(self, dtype): + self.series.isin(self.sample) diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 43e384b01ad2c..2b73a84810045 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -954,6 +954,7 @@ Performance Improvements - Improved performance of :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` (:issue:`11296`) - Improved performance of :func:`pandas.core.groupby.GroupBy.any` and :func:`pandas.core.groupby.GroupBy.all` (:issue:`15435`) - Improved performance of :func:`pandas.core.groupby.GroupBy.pct_change` (:issue:`19165`) +- Improved performance of :func:`Series.isin` in the case of categorical dtypes (:issue:`20003`) - Fixed a performance regression for :func:`GroupBy.nth` and :func:`GroupBy.last` with some object columns (:issue:`19283`) .. _whatsnew_0230.docs: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 065a5782aced1..5493348334223 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -407,6 +407,13 @@ def isin(comps, values): if not isinstance(values, (ABCIndex, ABCSeries, np.ndarray)): values = construct_1d_object_array_from_listlike(list(values)) + if is_categorical_dtype(comps): + # TODO(extension) + # handle categoricals + return comps._values.isin(values) + + comps = com._values_from_object(comps) + comps, dtype, _ = _ensure_data(comps) values, _, _ = _ensure_data(values, dtype=dtype) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 599161521f3a7..7f0d54de9def8 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -39,6 +39,8 @@ from pandas.util._decorators import ( Appender, cache_readonly, deprecate_kwarg, Substitution) +import pandas.core.algorithms as algorithms + from pandas.io.formats.terminal import get_terminal_size from pandas.util._validators import validate_bool_kwarg, validate_fillna_kwargs from pandas.core.config import get_option @@ -2216,6 +2218,60 @@ def _concat_same_type(self, to_concat): def _formatting_values(self): return self + def isin(self, values): + """ + Check whether `values` are contained in Categorical. + + Return a boolean NumPy Array showing whether each element in + the Categorical matches an element in the passed sequence of + `values` exactly. + + Parameters + ---------- + values : set or list-like + The sequence of values to test. Passing in a single string will + raise a ``TypeError``. Instead, turn a single string into a + list of one element. + + Returns + ------- + isin : numpy.ndarray (bool dtype) + + Raises + ------ + TypeError + * If `values` is not a set or list-like + + See Also + -------- + pandas.Series.isin : equivalent method on Series + + Examples + -------- + + >>> s = pd.Categorical(['lama', 'cow', 'lama', 'beetle', 'lama', + ... 'hippo']) + >>> s.isin(['cow', 'lama']) + array([ True, True, True, False, True, False]) + + Passing a single string as ``s.isin('lama')`` will raise an error. Use + a list of one element instead: + + >>> s.isin(['lama']) + array([ True, False, True, False, True, False]) + """ + from pandas.core.series import _sanitize_array + if not is_list_like(values): + raise TypeError("only list-like objects are allowed to be passed" + " to isin(), you passed a [{values_type}]" + .format(values_type=type(values).__name__)) + values = _sanitize_array(values, None, None) + null_mask = np.asarray(isna(values)) + code_values = self.categories.get_indexer(values) + code_values = code_values[null_mask | (code_values >= 0)] + return algorithms.isin(self.codes, code_values) + + # The Series.cat accessor diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 3d60eefc5b598..21006c4831ac5 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3516,7 +3516,7 @@ def isin(self, values, level=None): """ if level is not None: self._validate_index_level(level) - return algos.isin(np.array(self), values) + return algos.isin(self, values) def _can_reindex(self, indexer): """ diff --git a/pandas/core/series.py b/pandas/core/series.py index aa4cb510feb62..f2ee225f50514 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3567,7 +3567,7 @@ def isin(self, values): 5 False Name: animal, dtype: bool """ - result = algorithms.isin(com._values_from_object(self), values) + result = algorithms.isin(self, values) return self._constructor(result, index=self.index).__finalize__(self) def between(self, left, right, inclusive=True): diff --git a/pandas/tests/categorical/test_algos.py b/pandas/tests/categorical/test_algos.py index f727184e862d8..1c68377786dd4 100644 --- a/pandas/tests/categorical/test_algos.py +++ b/pandas/tests/categorical/test_algos.py @@ -47,3 +47,25 @@ def test_factorized_sort_ordered(): tm.assert_numpy_array_equal(labels, expected_labels) tm.assert_categorical_equal(uniques, expected_uniques) + + +def test_isin_cats(): + # GH2003 + cat = pd.Categorical(["a", "b", np.nan]) + + result = cat.isin(["a", np.nan]) + expected = np.array([True, False, True], dtype=bool) + tm.assert_numpy_array_equal(expected, result) + + result = cat.isin(["a", "c"]) + expected = np.array([True, False, False], dtype=bool) + tm.assert_numpy_array_equal(expected, result) + + +@pytest.mark.parametrize("empty", [[], pd.Series(), np.array([])]) +def test_isin_empty(empty): + s = pd.Categorical(["a", "b"]) + expected = np.array([False, False], dtype=bool) + + result = s.isin(empty) + tm.assert_numpy_array_equal(expected, result)
I have added a branching for the categorical case in `Series.isin` function. I have also added a test for the most crucial cases (nans). closes #20003
https://api.github.com/repos/pandas-dev/pandas/pulls/20522
2018-03-28T18:49:50Z
2018-04-25T12:38:18Z
2018-04-25T12:38:18Z
2018-04-25T12:38:43Z
API/BUG: Enforce "normalized" pytz timezones for DatetimeIndex
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index fb63dc16249b2..852a8d327707d 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -767,6 +767,8 @@ Datetimelike API Changes - :func:`pandas.merge` provides a more informative error message when trying to merge on timezone-aware and timezone-naive columns (:issue:`15800`) - For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with ``freq=None``, addition or subtraction of integer-dtyped array or ``Index`` will raise ``NullFrequencyError`` instead of ``TypeError`` (:issue:`19895`) - :class:`Timestamp` constructor now accepts a `nanosecond` keyword or positional argument (:issue:`18898`) +- :class:`DatetimeIndex` will now raise an ``AttributeError`` when the ``tz`` attribute is set after instantiation (:issue:`3746`) +- :class:`DatetimeIndex` with a ``pytz`` timezone will now return a consistent ``pytz`` timezone (:issue:`18595`) .. _whatsnew_0230.api.other: @@ -1123,6 +1125,7 @@ Groupby/Resample/Rolling - Bug in :func:`DataFrame.resample().aggregate` not raising a ``KeyError`` when aggregating a non-existent column (:issue:`16766`, :issue:`19566`) - Fixed a performance regression for ``GroupBy.nth`` and ``GroupBy.last`` with some object columns (:issue:`19283`) - Bug in :func:`DataFrameGroupBy.cumsum` and :func:`DataFrameGroupBy.cumprod` when ``skipna`` was passed (:issue:`19806`) +- Bug in :func:`Dataframe.resample` that dropped timezone information (:issue:`13238`) Sparse ^^^^^^ diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 9818d53e386bd..ba5ebdab82ddc 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -700,6 +700,12 @@ class Timestamp(_Timestamp): """ return self.tzinfo + @tz.setter + def tz(self, value): + # GH 3746: Prevent localizing or converting the index by setting tz + raise AttributeError("Cannot directly set timezone. Use tz_localize() " + "or tz_convert() as appropriate") + def __setstate__(self, state): self.value = state[0] self.freq = state[1] diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index 215ae9ce087ee..74fadbdb64763 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -314,3 +314,41 @@ cpdef bint tz_compare(object start, object end): """ # GH 18523 return get_timezone(start) == get_timezone(end) + + +cpdef tz_standardize(object tz): + """ + If the passed tz is a pytz timezone object, "normalize" it to the a + consistent version + + Parameters + ---------- + tz : tz object + + Returns: + ------- + tz object + + Examples: + -------- + >>> tz + <DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD> + + >>> tz_standardize(tz) + <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD> + + >>> tz + <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD> + + >>> tz_standardize(tz) + <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD> + + >>> tz + dateutil.tz.tz.tzutc + + >>> tz_standardize(tz) + dateutil.tz.tz.tzutc + """ + if treat_tz_as_pytz(tz): + return pytz.timezone(str(tz)) + return tz diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index b906ea0f4784c..95e1f8438c704 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -1005,7 +1005,7 @@ def shift(self, n, freq=None): result = self + offset if hasattr(self, 'tz'): - result.tz = self.tz + result._tz = self.tz return result diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 75f4ec4f0d341..88ea3511d4ee3 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -511,13 +511,7 @@ def _generate(cls, start, end, periods, name, offset, 'different timezones') inferred_tz = timezones.maybe_get_tz(inferred_tz) - - # these may need to be localized tz = timezones.maybe_get_tz(tz) - if tz is not None: - date = start or end - if date.tzinfo is not None and hasattr(tz, 'localize'): - tz = tz.localize(date.replace(tzinfo=None)).tzinfo if tz is not None and inferred_tz is not None: if not timezones.tz_compare(inferred_tz, tz): @@ -654,7 +648,8 @@ def _simple_new(cls, values, name=None, freq=None, tz=None, result._data = values result.name = name result.offset = freq - result.tz = timezones.maybe_get_tz(tz) + result._tz = timezones.maybe_get_tz(tz) + result._tz = timezones.tz_standardize(result._tz) result._reset_identity() return result @@ -684,6 +679,17 @@ def _values(self): else: return self.values + @property + def tz(self): + # GH 18595 + return self._tz + + @tz.setter + def tz(self, value): + # GH 3746: Prevent localizing or converting the index by setting tz + raise AttributeError("Cannot directly set timezone. Use tz_localize() " + "or tz_convert() as appropriate") + @property def tzinfo(self): """ @@ -754,7 +760,7 @@ def _cached_range(cls, start=None, end=None, periods=None, offset=None, cachedRange = DatetimeIndex._simple_new(arr) cachedRange.offset = offset - cachedRange.tz = None + cachedRange = cachedRange.tz_localize(None) cachedRange.name = None drc[offset] = cachedRange else: @@ -831,7 +837,7 @@ def __setstate__(self, state): self.name = own_state[0] self.offset = own_state[1] - self.tz = own_state[2] + self._tz = timezones.tz_standardize(own_state[2]) # provide numpy < 1.7 compat if nd_state[2] == 'M8[us]': @@ -1175,7 +1181,7 @@ def union(self, other): else: result = Index.union(this, other) if isinstance(result, DatetimeIndex): - result.tz = this.tz + result._tz = timezones.tz_standardize(this.tz) if (result.freq is None and (this.freq is not None or other.freq is not None)): result.offset = to_offset(result.inferred_freq) @@ -1223,7 +1229,7 @@ def union_many(self, others): tz = this.tz this = Index.union(this, other) if isinstance(this, DatetimeIndex): - this.tz = tz + this._tz = timezones.tz_standardize(tz) if this.freq is None: this.offset = to_offset(this.inferred_freq) diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 3e0ba26c20eb0..785bb128512fc 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -249,8 +249,8 @@ def test_set_index_cast_datetimeindex(self): # convert to utc df['C'] = i.to_series().reset_index(drop=True) result = df['C'] - comp = pd.DatetimeIndex(expected.values).copy() - comp.tz = None + comp = pd.DatetimeIndex(expected.values) + comp = comp.tz_localize(None) tm.assert_numpy_array_equal(result.values, comp.values) # list of datetimes with a tz diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index 176f5bd0c1a2a..97e01478c736b 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -441,6 +441,34 @@ def test_000constructor_resolution(self): assert idx.nanosecond[0] == t1.nanosecond + def test_disallow_setting_tz(self): + # GH 3746 + dti = DatetimeIndex(['2010'], tz='UTC') + with pytest.raises(AttributeError): + dti.tz = pytz.timezone('US/Pacific') + + @pytest.mark.parametrize('tz', [ + None, 'America/Los_Angeles', pytz.timezone('America/Los_Angeles'), + Timestamp('2000', tz='America/Los_Angeles').tz]) + def test_constructor_start_end_with_tz(self, tz): + # GH 18595 + start = Timestamp('2013-01-01 06:00:00', tz='America/Los_Angeles') + end = Timestamp('2013-01-02 06:00:00', tz='America/Los_Angeles') + result = DatetimeIndex(freq='D', start=start, end=end, tz=tz) + expected = DatetimeIndex(['2013-01-01 06:00:00', + '2013-01-02 06:00:00'], + tz='America/Los_Angeles') + tm.assert_index_equal(result, expected) + # Especially assert that the timezone is consistent for pytz + assert pytz.timezone('America/Los_Angeles') is result.tz + + @pytest.mark.parametrize('tz', ['US/Pacific', 'US/Eastern', 'Asia/Tokyo']) + def test_constructor_with_non_normalized_pytz(self, tz): + # GH 18595 + non_norm_tz = Timestamp('2010', tz=tz).tz + result = DatetimeIndex(['2010'], tz=non_norm_tz) + assert pytz.timezone(tz) is result.tz + class TestTimeSeries(object): diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index cde5baf47c18e..55ed7e6cfa8db 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -521,6 +521,13 @@ def test_today(self): assert (abs(ts_from_string_tz.tz_localize(None) - ts_from_method_tz.tz_localize(None)) < delta) + @pytest.mark.parametrize('tz', [None, pytz.timezone('US/Pacific')]) + def test_disallow_setting_tz(self, tz): + # GH 3746 + ts = Timestamp('2010') + with pytest.raises(AttributeError): + ts.tz = tz + class TestTimestamp(object): diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 896002d007a69..2180e38e24e6c 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -2532,6 +2532,18 @@ def test_with_local_timezone_pytz(self): expected = Series(1, index=expected_index) assert_series_equal(result, expected) + def test_resample_with_pytz(self): + # GH 13238 + s = Series(2, index=pd.date_range('2017-01-01', periods=48, freq="H", + tz="US/Eastern")) + result = s.resample("D").mean() + expected = Series(2, index=pd.DatetimeIndex(['2017-01-01', + '2017-01-02'], + tz="US/Eastern")) + assert_series_equal(result, expected) + # Especially assert that the timezone is LMT for pytz + assert result.index.tz == pytz.timezone('US/Eastern') + def test_with_local_timezone_dateutil(self): # see gh-5430 local_timezone = 'dateutil/America/Los_Angeles'
closes #3746 closes #18595 closes #13238 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Addressing 3 birds with 2 stones here. Using @pganssle suggested implementation for a tz property and directly raising an error per #3746 (could depreciate and error in a future version as well, open to feedback on the prefered path of API change) Additionally, solves the issue of resampling a DataFrame/Series with a DatetimeIndex that retained a local timezone instead of the "LMT" version.
https://api.github.com/repos/pandas-dev/pandas/pulls/20510
2018-03-28T03:19:52Z
2018-04-11T02:29:55Z
2018-04-11T02:29:54Z
2018-04-11T17:10:07Z
DOC: Fix various warnings
diff --git a/doc/source/comparison_with_r.rst b/doc/source/comparison_with_r.rst index eb97aeeb7e696..a7586f623a160 100644 --- a/doc/source/comparison_with_r.rst +++ b/doc/source/comparison_with_r.rst @@ -397,7 +397,7 @@ In Python, this list would be a list of tuples, so pd.DataFrame(a) For more details and examples see :ref:`the Into to Data Structures -documentation <basics.dataframe.from_items>`. +documentation <dsintro>`. |meltdf|_ ~~~~~~~~~~~~~~~~ diff --git a/doc/source/contributing.rst b/doc/source/contributing.rst index 967d1fe3369f0..6d5ac31c39a62 100644 --- a/doc/source/contributing.rst +++ b/doc/source/contributing.rst @@ -298,6 +298,11 @@ Some other important things to know about the docs: Standard**. Follow the :ref:`pandas docstring guide <docstring>` for detailed instructions on how to write a correct docstring. + .. toctree:: + :maxdepth: 2 + + contributing_docstring.rst + - The tutorials make heavy use of the `ipython directive <http://matplotlib.org/sampledoc/ipython_directive.html>`_ sphinx extension. This directive lets you put code in the documentation which will be run @@ -900,7 +905,7 @@ Documenting your code Changes should be reflected in the release notes located in ``doc/source/whatsnew/vx.y.z.txt``. This file contains an ongoing change log for each release. Add an entry to this file to document your fix, enhancement or (unavoidable) breaking change. Make sure to include the -GitHub issue number when adding your entry (using `` :issue:`1234` `` where `1234` is the +GitHub issue number when adding your entry (using ``:issue:`1234``` where ``1234`` is the issue/pull request number). If your code is an enhancement, it is most likely necessary to add usage @@ -1020,7 +1025,7 @@ release. To submit a pull request: #. Click ``Send Pull Request``. This request then goes to the repository maintainers, and they will review -the code. +the code. .. _contributing.update-pr: @@ -1028,7 +1033,7 @@ Updating your pull request -------------------------- Based on the review you get on your pull request, you will probably need to make -some changes to the code. In that case, you can make them in your branch, +some changes to the code. In that case, you can make them in your branch, add a new commit to that branch, push it to GitHub, and the pull request will be automatically updated. Pushing them to GitHub again is done by:: @@ -1039,7 +1044,7 @@ This will automatically update your pull request with the latest code and restar Another reason you might need to update your pull request is to solve conflicts with changes that have been merged into the master branch since you opened your -pull request. +pull request. To do this, you need to "merge upstream master" in your branch:: diff --git a/doc/source/cookbook.rst b/doc/source/cookbook.rst index b6690eff89836..4e61228d5c0ad 100644 --- a/doc/source/cookbook.rst +++ b/doc/source/cookbook.rst @@ -411,6 +411,8 @@ Levels `Flatten Hierarchical columns <http://stackoverflow.com/questions/14507794/python-pandas-how-to-flatten-a-hierarchical-index-in-columns>`__ +.. _cookbook.missing_data: + Missing Data ------------ diff --git a/doc/source/io.rst b/doc/source/io.rst index d6bd81861adee..68b431925d983 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -3862,6 +3862,8 @@ Then create the index when finished appending. See `here <http://stackoverflow.com/questions/17893370/ptrepack-sortby-needs-full-index>`__ for how to create a completely-sorted-index (CSI) on an existing store. +.. _io.hdf5-query-data-columns: + Query via Data Columns ++++++++++++++++++++++ diff --git a/doc/source/release.rst b/doc/source/release.rst index 8e063116cbf07..da3362b47b29b 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -71,7 +71,7 @@ Highlights include: - Temporarily restore matplotlib datetime plotting functionality. This should resolve issues for users who relied implicitly on pandas to plot datetimes - with matplotlib. See :ref:`here <whatsnew_0211.special>`. + with matplotlib. See :ref:`here <whatsnew_0211.converters>`. - Improvements to the Parquet IO functions introduced in 0.21.0. See :ref:`here <whatsnew_0211.enhancements.parquet>`. diff --git a/doc/source/whatsnew/v0.10.0.txt b/doc/source/whatsnew/v0.10.0.txt index 222a2da23865c..3fc05158b7fe7 100644 --- a/doc/source/whatsnew/v0.10.0.txt +++ b/doc/source/whatsnew/v0.10.0.txt @@ -409,7 +409,7 @@ N Dimensional Panels (Experimental) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Adding experimental support for Panel4D and factory functions to create n-dimensional named panels. -:ref:`Docs <dsintro.panel4d>` for NDim. Here is a taste of what to expect. +Here is a taste of what to expect. .. code-block:: ipython diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index 9e1dc391d7ace..5c716f6ad45c1 100644 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -26,7 +26,7 @@ Highlights include: .. warning:: - In pandas 0.17.0, the sub-package ``pandas.io.data`` will be removed in favor of a separately installable package. See :ref:`here for details <remote_data.pandas_datareader>` (:issue:`8961`) + In pandas 0.17.0, the sub-package ``pandas.io.data`` will be removed in favor of a separately installable package (:issue:`8961`). Enhancements ~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index a19b71c27d998..9a8659dfd8b06 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -331,7 +331,7 @@ Other Enhancements :func:`pandas.api.extensions.register_series_accessor`, and :func:`pandas.api.extensions.register_index_accessor`, accessor for libraries downstream of pandas to register custom accessors like ``.cat`` on pandas objects. See - :ref:`Registering Custom Accessors <developer.register-accessors>` for more (:issue:`14781`). + :ref:`Registering Custom Accessors <extending.register-accessors>` for more (:issue:`14781`). - ``IntervalIndex.astype`` now supports conversions between subtypes when passed an ``IntervalDtype`` (:issue:`19197`) - :class:`IntervalIndex` and its associated constructor methods (``from_arrays``, ``from_breaks``, ``from_tuples``) have gained a ``dtype`` parameter (:issue:`19262`) diff --git a/doc/source/whatsnew/v0.6.1.txt b/doc/source/whatsnew/v0.6.1.txt index a2dab738546f9..acd5b0774f2bb 100644 --- a/doc/source/whatsnew/v0.6.1.txt +++ b/doc/source/whatsnew/v0.6.1.txt @@ -16,12 +16,12 @@ New features - Add PyQt table widget to sandbox (:issue:`435`) - DataFrame.align can :ref:`accept Series arguments <basics.align.frame.series>` and an :ref:`axis option <basics.df_join>` (:issue:`461`) -- Implement new :ref:`SparseArray <sparse.array>` and :ref:`SparseList <sparse.list>` +- Implement new :ref:`SparseArray <sparse.array>` and `SparseList` data structures. SparseSeries now derives from SparseArray (:issue:`463`) - :ref:`Better console printing options <basics.console_output>` (:issue:`453`) - Implement fast :ref:`data ranking <computation.ranking>` for Series and DataFrame, fast versions of scipy.stats.rankdata (:issue:`428`) -- Implement :ref:`DataFrame.from_items <basics.dataframe.from_items>` alternate +- Implement `DataFrame.from_items` alternate constructor (:issue:`444`) - DataFrame.convert_objects method for :ref:`inferring better dtypes <basics.cast>` for object columns (:issue:`302`) diff --git a/doc/source/whatsnew/v0.7.3.txt b/doc/source/whatsnew/v0.7.3.txt index 6b5199c55cbf5..77cc72d8707cf 100644 --- a/doc/source/whatsnew/v0.7.3.txt +++ b/doc/source/whatsnew/v0.7.3.txt @@ -22,7 +22,7 @@ New features from pandas.tools.plotting import scatter_matrix scatter_matrix(df, alpha=0.2) -.. image:: _static/scatter_matrix_kde.png +.. image:: savefig/scatter_matrix_kde.png :width: 5in - Add ``stacked`` argument to Series and DataFrame's ``plot`` method for @@ -32,14 +32,14 @@ New features df.plot(kind='bar', stacked=True) -.. image:: _static/bar_plot_stacked_ex.png +.. image:: savefig/bar_plot_stacked_ex.png :width: 4in .. code-block:: python df.plot(kind='barh', stacked=True) -.. image:: _static/barh_plot_stacked_ex.png +.. image:: savefig/barh_plot_stacked_ex.png :width: 4in - Add log x and y :ref:`scaling options <visualization.basic>` to diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f1fa43818ce64..d5cd22732f0a9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1900,7 +1900,7 @@ def to_hdf(self, path_or_buf, key, **kwargs): In order to add another DataFrame or Series to an existing HDF file please use append mode and a different a key. - For more information see the :ref:`user guide <io.html#io-hdf5>`. + For more information see the :ref:`user guide <io.hdf5>`. Parameters ---------- @@ -1929,8 +1929,7 @@ def to_hdf(self, path_or_buf, key, **kwargs): data_columns : list of columns or True, optional List of columns to create as indexed data columns for on-disk queries, or True to use all columns. By default only the axes - of the object are indexed. See `here - <http://pandas.pydata.org/pandas-docs/stable/io.html#query-via-data-columns>`__. + of the object are indexed. See :ref:`io.hdf5-query-data-columns`. Applicable only to format='table'. complevel : {0-9}, optional Specifies a compression level for data. @@ -2141,7 +2140,7 @@ def to_pickle(self, path, compression='infer', .. versionadded:: 0.20.0 protocol : int Int which indicates which protocol should be used by the pickler, - default HIGHEST_PROTOCOL (see [1], paragraph 12.1.2). The possible + default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible values for this parameter depend on the version of Python. For Python 2.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a valid value. For Python >= 3.4, 4 is a valid value. A negative diff --git a/pandas/core/series.py b/pandas/core/series.py index 62f0ea3ce8b2a..d066e9409b594 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -467,8 +467,8 @@ def asobject(self): """Return object Series which contains boxed values. .. deprecated :: 0.23.0 - Use ``astype(object) instead. + Use ``astype(object) instead. *this is an internal non-public method* """ @@ -1772,18 +1772,20 @@ def idxmax(self, axis=0, skipna=True, *args, **kwargs): return self.index[i] # ndarray compat - argmin = deprecate('argmin', idxmin, '0.21.0', - msg="'argmin' is deprecated, use 'idxmin' instead. " - "The behavior of 'argmin' will be corrected to " - "return the positional minimum in the future. " - "Use 'series.values.argmin' to get the position of " - "the minimum now.") - argmax = deprecate('argmax', idxmax, '0.21.0', - msg="'argmax' is deprecated, use 'idxmax' instead. " - "The behavior of 'argmax' will be corrected to " - "return the positional maximum in the future. " - "Use 'series.values.argmax' to get the position of " - "the maximum now.") + argmin = deprecate( + 'argmin', idxmin, '0.21.0', + msg=dedent("""\ + 'argmin' is deprecated, use 'idxmin' instead. The behavior of 'argmin' + will be corrected to return the positional minimum in the future. + Use 'series.values.argmin' to get the position of the minimum now.""") + ) + argmax = deprecate( + 'argmax', idxmax, '0.21.0', + msg=dedent("""\ + 'argmax' is deprecated, use 'idxmax' instead. The behavior of 'argmax' + will be corrected to return the positional maximum in the future. + Use 'series.values.argmax' to get the position of the maximum now.""") + ) def round(self, decimals=0, *args, **kwargs): """ diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 89e04f03cda32..6c3d07124215b 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -3100,7 +3100,7 @@ def hist(self, by=None, bins=10, **kwds): A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame - into bins, and draws all bins in only one :ref:`matplotlib.axes.Axes`. + into bins and draws all bins in one :class:`matplotlib.axes.Axes`. This is useful when the DataFrame's Series are in a similar scale. Parameters diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index 1753bc8b8fc33..624fbbbd4f05e 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -45,13 +45,18 @@ def wrapper(*args, **kwargs): return alternative(*args, **kwargs) # adding deprecated directive to the docstring - msg = msg or 'Use `{alt_name}` instead.' - docstring = '.. deprecated:: {}\n'.format(version) - docstring += dedent(' ' + ('\n'.join(wrap(msg, 70)))) - - if getattr(wrapper, '__doc__') is not None: - docstring += dedent(wrapper.__doc__) - + msg = msg or 'Use `{alt_name}` instead.'.format(alt_name=alt_name) + tpl = dedent(""" + .. deprecated:: {version} + + {msg} + + {rest} + """) + rest = getattr(wrapper, '__doc__', '') + docstring = tpl.format(version=version, + msg='\n '.join(wrap(msg, 70)), + rest=dedent(rest)) wrapper.__doc__ = docstring return wrapper
https://api.github.com/repos/pandas-dev/pandas/pulls/20509
2018-03-27T21:29:47Z
2018-03-29T02:31:38Z
2018-03-29T02:31:38Z
2018-03-29T02:31:41Z
Move GroupBy to Submodule and Add FutureWarning
diff --git a/pandas/core/api.py b/pandas/core/api.py index aa37ddffa1156..640baf31268a7 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -7,7 +7,7 @@ from pandas.core.algorithms import factorize, unique, value_counts from pandas.core.dtypes.missing import isna, isnull, notna, notnull from pandas.core.arrays import Categorical -from pandas.core.groupby import Grouper +from pandas.core.groupby.groupby import Grouper from pandas.io.formats.format import set_eng_float_format from pandas.core.index import (Index, CategoricalIndex, Int64Index, UInt64Index, RangeIndex, Float64Index, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 33617964d7e59..ae9d160db08e9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6589,7 +6589,7 @@ def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True, resample : Convenience method for frequency conversion and resampling of time series. """ - from pandas.core.groupby import groupby + from pandas.core.groupby.groupby import groupby if level is None and by is None: raise TypeError("You have to supply one of 'by' and 'level'") diff --git a/pandas/core/groupby/__init__.py b/pandas/core/groupby/__init__.py new file mode 100644 index 0000000000000..4b2ebdf16b89b --- /dev/null +++ b/pandas/core/groupby/__init__.py @@ -0,0 +1,4 @@ +# flake8: noqa +from pandas.core.groupby.groupby import ( + Grouper, GroupBy, SeriesGroupBy, DataFrameGroupBy +) diff --git a/pandas/core/groupby.py b/pandas/core/groupby/groupby.py similarity index 100% rename from pandas/core/groupby.py rename to pandas/core/groupby/groupby.py diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 7c087ac7deafc..e08d0a7368ccb 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -912,7 +912,7 @@ def groupby(self, function, axis='major'): ------- grouped : PanelGroupBy """ - from pandas.core.groupby import PanelGroupBy + from pandas.core.groupby.groupby import PanelGroupBy axis = self._get_axis_number(axis) return PanelGroupBy(self, function, axis=axis) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index b3ab90fd67de4..0d0023b9f67d3 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -7,9 +7,10 @@ import pandas as pd from pandas.core.base import GroupByMixin -from pandas.core.groupby import (BinGrouper, Grouper, _GroupBy, GroupBy, - SeriesGroupBy, groupby, PanelGroupBy, - _pipe_template) +from pandas.core.groupby.groupby import ( + BinGrouper, Grouper, _GroupBy, GroupBy, SeriesGroupBy, groupby, + PanelGroupBy, _pipe_template +) from pandas.tseries.frequencies import to_offset, is_subperiod, is_superperiod from pandas.core.indexes.datetimes import DatetimeIndex, date_range diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index a4c9848dca900..74a9b59d3194a 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -6,7 +6,7 @@ from pandas.core.reshape.concat import concat from pandas.core.series import Series -from pandas.core.groupby import Grouper +from pandas.core.groupby.groupby import Grouper from pandas.core.reshape.util import cartesian_product from pandas.core.index import Index, _get_objs_combined_axis from pandas.compat import range, lrange, zip diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 7cc6c2fa7b88c..d85719d328ff2 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -10,7 +10,7 @@ import pandas as pd from pandas import concat, DataFrame, Index, MultiIndex, Series -from pandas.core.groupby import Grouping, SpecificationError +from pandas.core.groupby.groupby import Grouping, SpecificationError from pandas.compat import OrderedDict import pandas.util.testing as tm diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index cef3a699ed24b..80383c895a5e5 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -14,7 +14,7 @@ from pandas import (bdate_range, DataFrame, Index, Series, Timestamp, Timedelta, NaT) -from pandas.core.groupby import DataError +from pandas.core.groupby.groupby import DataError import pandas.util.testing as tm diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index 4c407ad8a0d93..7c6cb5b9615cb 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -18,7 +18,7 @@ from pandas import ( date_range, DataFrame, Index, MultiIndex, PeriodIndex, period_range, Series ) -from pandas.core.groupby import SpecificationError +from pandas.core.groupby.groupby import SpecificationError from pandas.io.formats.printing import pprint_thing import pandas.util.testing as tm diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index 979b2f7a539af..c293f49c5bc2a 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -54,7 +54,7 @@ def setup_method(self, method): self.bins = np.array([3, 6], dtype=np.int64) def test_generate_bins(self): - from pandas.core.groupby import generate_bins_generic + from pandas.core.groupby.groupby import generate_bins_generic values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64) binner = np.array([0, 3, 6, 9], dtype=np.int64) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 8702062e9cd0a..57becd342d370 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -340,7 +340,7 @@ def test_groupby_grouper_f_sanity_checked(self): pytest.raises(AssertionError, ts.groupby, lambda key: key[0:6]) def test_grouping_error_on_multidim_input(self): - from pandas.core.groupby import Grouping + from pandas.core.groupby.groupby import Grouping pytest.raises(ValueError, Grouping, self.df.index, self.df[['A', 'A']]) diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index d359bfa5351a9..17ca5d31b6b59 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -57,11 +57,12 @@ def test_groupby_with_timegrouper(self): result3 = df.groupby(pd.Grouper(freq='5D')).sum() assert_frame_equal(result3, expected) - def test_groupby_with_timegrouper_methods(self): + @pytest.mark.parametrize("should_sort", [True, False]) + def test_groupby_with_timegrouper_methods(self, should_sort): # GH 3881 # make sure API of timegrouper conforms - df_original = pd.DataFrame({ + df = pd.DataFrame({ 'Branch': 'A A A A A B'.split(), 'Buyer': 'Carl Mark Carl Joe Joe Carl'.split(), 'Quantity': [1, 3, 5, 8, 9, 3], @@ -75,16 +76,18 @@ def test_groupby_with_timegrouper_methods(self): ] }) - df_sorted = df_original.sort_values(by='Quantity', ascending=False) + if should_sort: + df = df.sort_values(by='Quantity', ascending=False) - for df in [df_original, df_sorted]: - df = df.set_index('Date', drop=False) - g = df.groupby(pd.Grouper(freq='6M')) - assert g.group_keys - assert isinstance(g.grouper, pd.core.groupby.BinGrouper) - groups = g.groups - assert isinstance(groups, dict) - assert len(groups) == 3 + df = df.set_index('Date', drop=False) + g = df.groupby(pd.Grouper(freq='6M')) + assert g.group_keys + + import pandas.core.groupby.groupby + assert isinstance(g.grouper, pandas.core.groupby.groupby.BinGrouper) + groups = g.groups + assert isinstance(groups, dict) + assert len(groups) == 3 def test_timegrouper_with_reg_groups(self): diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index bce38b8cf9eed..23326d1b105fe 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -13,7 +13,7 @@ from .common import MixIn, assert_fp_equal from pandas.util.testing import assert_frame_equal, assert_series_equal -from pandas.core.groupby import DataError +from pandas.core.groupby.groupby import DataError from pandas.core.config import option_context diff --git a/pandas/tests/test_resample.py b/pandas/tests/test_resample.py index 23cc18de34778..ef09b64d5b6eb 100644 --- a/pandas/tests/test_resample.py +++ b/pandas/tests/test_resample.py @@ -21,7 +21,7 @@ from pandas.core.dtypes.generic import ABCSeries, ABCDataFrame from pandas.compat import range, lrange, zip, product, OrderedDict from pandas.errors import UnsupportedFunctionCall -from pandas.core.groupby import DataError +from pandas.core.groupby.groupby import DataError import pandas.core.common as com from pandas.tseries.frequencies import to_offset
ref #20485 @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/20506
2018-03-27T17:04:15Z
2018-04-02T22:38:33Z
2018-04-02T22:38:32Z
2018-05-14T21:11:31Z
ENH: Support ExtensionArray in Groupby
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 601acac20c96d..7c89cab6b1428 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -44,7 +44,7 @@ DataError, SpecificationError) from pandas.core.index import (Index, MultiIndex, CategoricalIndex, _ensure_index) -from pandas.core.arrays import Categorical +from pandas.core.arrays import ExtensionArray, Categorical from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame, _shared_docs from pandas.core.internals import BlockManager, make_block @@ -2968,7 +2968,7 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None, # no level passed elif not isinstance(self.grouper, - (Series, Index, Categorical, np.ndarray)): + (Series, Index, ExtensionArray, np.ndarray)): if getattr(self.grouper, 'ndim', 1) != 1: t = self.name or str(type(self.grouper)) raise ValueError("Grouper for '%s' not 1-dimensional" % t) diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py index 27c106efd0524..f8078d2798b32 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -44,6 +44,7 @@ class TestMyDtype(BaseDtypeTests): from .constructors import BaseConstructorsTests # noqa from .dtype import BaseDtypeTests # noqa from .getitem import BaseGetitemTests # noqa +from .groupby import BaseGroupbyTests # noqa from .interface import BaseInterfaceTests # noqa from .methods import BaseMethodsTests # noqa from .missing import BaseMissingTests # noqa diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py new file mode 100644 index 0000000000000..a29ef2a509a63 --- /dev/null +++ b/pandas/tests/extension/base/groupby.py @@ -0,0 +1,69 @@ +import pytest + +import pandas.util.testing as tm +import pandas as pd +from .base import BaseExtensionTests + + +class BaseGroupbyTests(BaseExtensionTests): + """Groupby-specific tests.""" + + def test_grouping_grouper(self, data_for_grouping): + df = pd.DataFrame({ + "A": ["B", "B", None, None, "A", "A", "B", "C"], + "B": data_for_grouping + }) + gr1 = df.groupby("A").grouper.groupings[0] + gr2 = df.groupby("B").grouper.groupings[0] + + tm.assert_numpy_array_equal(gr1.grouper, df.A.values) + tm.assert_extension_array_equal(gr2.grouper, data_for_grouping) + + @pytest.mark.parametrize('as_index', [True, False]) + def test_groupby_extension_agg(self, as_index, data_for_grouping): + df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], + "B": data_for_grouping}) + result = df.groupby("B", as_index=as_index).A.mean() + _, index = pd.factorize(data_for_grouping, sort=True) + # TODO(ExtensionIndex): remove astype + index = pd.Index(index.astype(object), name="B") + expected = pd.Series([3, 1, 4], index=index, name="A") + if as_index: + self.assert_series_equal(result, expected) + else: + expected = expected.reset_index() + self.assert_frame_equal(result, expected) + + def test_groupby_extension_no_sort(self, data_for_grouping): + df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], + "B": data_for_grouping}) + result = df.groupby("B", sort=False).A.mean() + _, index = pd.factorize(data_for_grouping, sort=False) + # TODO(ExtensionIndex): remove astype + index = pd.Index(index.astype(object), name="B") + expected = pd.Series([1, 3, 4], index=index, name="A") + self.assert_series_equal(result, expected) + + def test_groupby_extension_transform(self, data_for_grouping): + valid = data_for_grouping[~data_for_grouping.isna()] + df = pd.DataFrame({"A": [1, 1, 3, 3, 1, 4], + "B": valid}) + + result = df.groupby("B").A.transform(len) + expected = pd.Series([3, 3, 2, 2, 3, 1], name="A") + + self.assert_series_equal(result, expected) + + @pytest.mark.parametrize('op', [ + lambda x: 1, + lambda x: [1] * len(x), + lambda x: pd.Series([1] * len(x)), + lambda x: x, + ], ids=['scalar', 'list', 'series', 'object']) + def test_groupby_extension_apply(self, data_for_grouping, op): + df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], + "B": data_for_grouping}) + df.groupby("B").apply(op) + df.groupby("B").A.apply(op) + df.groupby("A").apply(op) + df.groupby("A").B.apply(op) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 22c1a67a0d60d..d509170565e1a 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -127,6 +127,10 @@ class TestCasting(BaseDecimal, base.BaseCastingTests): pass +class TestGroupby(BaseDecimal, base.BaseGroupbyTests): + pass + + def test_series_constructor_coerce_data_to_extension_dtype_raises(): xpr = ("Cannot cast data to extension dtype 'decimal'. Pass the " "extension array directly.") diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 51a68a3701046..d9ae49d87804a 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -113,8 +113,8 @@ def _concat_same_type(cls, to_concat): return cls(data) def _values_for_factorize(self): - frozen = tuple(tuple(x.items()) for x in self) - return np.array(frozen, dtype=object), () + frozen = self._values_for_argsort() + return frozen, () def _values_for_argsort(self): # Disable NumPy's shape inference by including an empty tuple... diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 63d97d5e7a2c5..5e9639c487c37 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -89,11 +89,12 @@ def test_fillna_frame(self): """We treat dictionaries as a mapping in fillna, not a scalar.""" -class TestMethods(base.BaseMethodsTests): - unhashable = pytest.mark.skip(reason="Unhashable") - unstable = pytest.mark.skipif(not PY36, # 3.6 or higher - reason="Dictionary order unstable") +unhashable = pytest.mark.skip(reason="Unhashable") +unstable = pytest.mark.skipif(not PY36, # 3.6 or higher + reason="Dictionary order unstable") + +class TestMethods(base.BaseMethodsTests): @unhashable def test_value_counts(self, all_data, dropna): pass @@ -118,6 +119,7 @@ def test_sort_values(self, data_for_sorting, ascending): super(TestMethods, self).test_sort_values( data_for_sorting, ascending) + @unstable @pytest.mark.parametrize('ascending', [True, False]) def test_sort_values_missing(self, data_missing_for_sorting, ascending): super(TestMethods, self).test_sort_values_missing( @@ -126,3 +128,34 @@ def test_sort_values_missing(self, data_missing_for_sorting, ascending): class TestCasting(base.BaseCastingTests): pass + + +class TestGroupby(base.BaseGroupbyTests): + + @unhashable + def test_groupby_extension_transform(self): + """ + This currently fails in Series.name.setter, since the + name must be hashable, but the value is a dictionary. + I think this is what we want, i.e. `.name` should be the original + values, and not the values for factorization. + """ + + @unhashable + def test_groupby_extension_apply(self): + """ + This fails in Index._do_unique_check with + + > hash(val) + E TypeError: unhashable type: 'UserDict' with + + I suspect that once we support Index[ExtensionArray], + we'll be able to dispatch unique. + """ + + @unstable + @pytest.mark.parametrize('as_index', [True, False]) + def test_groupby_extension_agg(self, as_index, data_for_grouping): + super(TestGroupby, self).test_groupby_extension_agg( + as_index, data_for_grouping + )
```python In [1]: import pandas as pd In [2]: from cyberpandas import IPArray In [3]: df = pd.DataFrame({"A": IPArray([0, 0, 1, 2, 2]), "B": [1, 5, 1, 1, 3]}) In [4]: df Out[4]: A B 0 0.0.0.0 1 1 0.0.0.0 5 2 0.0.0.1 1 3 0.0.0.2 1 4 0.0.0.2 3 In [5]: df.groupby("A").B.mean() Out[5]: A 0.0.0.1 1 0.0.0.2 2 Name: B, dtype: int64 ``` Note that right now `Out[5].index` just just an `Index` with object dtype. In the future, we could tie an Index type to an ExtensionArray type, and ensure that the extension type propagates through.
https://api.github.com/repos/pandas-dev/pandas/pulls/20502
2018-03-27T15:54:39Z
2018-03-28T10:35:45Z
2018-03-28T10:35:45Z
2018-05-02T13:10:02Z
Add interpolation options to rolling quantile
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index ba25ad6c5eda6..e3bf551fa5f2b 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -22,6 +22,7 @@ def setup(self, constructor, window, dtype, method): def time_rolling(self, constructor, window, dtype, method): getattr(self.roll, method)() + class VariableWindowMethods(Methods): sample_time = 0.2 params = (['DataFrame', 'Series'], @@ -37,6 +38,7 @@ def setup(self, constructor, window, dtype, method): index = pd.date_range('2017-01-01', periods=N, freq='5s') self.roll = getattr(pd, constructor)(arr, index=index).rolling(window) + class Pairwise(object): sample_time = 0.2 @@ -59,18 +61,19 @@ def time_pairwise(self, window, method, pairwise): class Quantile(object): - sample_time = 0.2 params = (['DataFrame', 'Series'], [10, 1000], ['int', 'float'], - [0, 0.5, 1]) + [0, 0.5, 1], + ['linear', 'nearest', 'lower', 'higher', 'midpoint']) param_names = ['constructor', 'window', 'dtype', 'percentile'] - def setup(self, constructor, window, dtype, percentile): - N = 10**5 + def setup(self, constructor, window, dtype, percentile, interpolation): + N = 10 ** 5 arr = np.random.random(N).astype(dtype) self.roll = getattr(pd, constructor)(arr).rolling(window) - def time_quantile(self, constructor, window, dtype, percentile): - self.roll.quantile(percentile) + def time_quantile(self, constructor, window, dtype, percentile, + interpolation): + self.roll.quantile(percentile, interpolation=interpolation) diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 9d9ce0b49f760..69d41f29506d1 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -443,6 +443,7 @@ Other Enhancements - :meth:`DataFrame.to_sql` now performs a multivalue insert if the underlying connection supports itk rather than inserting row by row. ``SQLAlchemy`` dialects supporting multivalue inserts include: ``mysql``, ``postgresql``, ``sqlite`` and any dialect with ``supports_multivalues_insert``. (:issue:`14315`, :issue:`8953`) - :func:`read_html` now accepts a ``displayed_only`` keyword argument to controls whether or not hidden elements are parsed (``True`` by default) (:issue:`20027`) +- :meth:`Rolling.quantile` and :meth:`Expanding.quantile` now accept the ``interpolation`` keyword, ``linear`` by default (:issue:`20497`) - zip compression is supported via ``compression=zip`` in :func:`DataFrame.to_pickle`, :func:`Series.to_pickle`, :func:`DataFrame.to_csv`, :func:`Series.to_csv`, :func:`DataFrame.to_json`, :func:`Series.to_json`. (:issue:`17778`) - :class:`WeekOfMonth` constructor now supports ``n=0`` (:issue:`20517`). - :class:`DataFrame` and :class:`Series` now support matrix multiplication (```@```) operator (:issue:`10259`) for Python>=3.5 diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index e524f823605a4..6b1239e198e26 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -1357,25 +1357,50 @@ cdef _roll_min_max(ndarray[numeric] input, int64_t win, int64_t minp, return output +cdef enum InterpolationType: + LINEAR, + LOWER, + HIGHER, + NEAREST, + MIDPOINT + + +interpolation_types = { + 'linear': LINEAR, + 'lower': LOWER, + 'higher': HIGHER, + 'nearest': NEAREST, + 'midpoint': MIDPOINT, +} + + def roll_quantile(ndarray[float64_t, cast=True] input, int64_t win, int64_t minp, object index, object closed, - double quantile): + double quantile, str interpolation): """ O(N log(window)) implementation using skip list """ cdef: - double val, prev, midpoint - IndexableSkiplist skiplist + double val, prev, midpoint, idx_with_fraction + skiplist_t *skiplist int64_t nobs = 0, i, j, s, e, N Py_ssize_t idx bint is_variable ndarray[int64_t] start, end ndarray[double_t] output double vlow, vhigh + InterpolationType interpolation_type + int ret = 0 if quantile <= 0.0 or quantile >= 1.0: raise ValueError("quantile value {0} not in [0, 1]".format(quantile)) + try: + interpolation_type = interpolation_types[interpolation] + except KeyError: + raise ValueError("Interpolation '{}' is not supported" + .format(interpolation)) + # we use the Fixed/Variable Indexer here as the # actual skiplist ops outweigh any window computation costs start, end, N, win, minp, is_variable = get_window_indexer( @@ -1383,51 +1408,78 @@ def roll_quantile(ndarray[float64_t, cast=True] input, int64_t win, minp, index, closed, use_mock=False) output = np.empty(N, dtype=float) - skiplist = IndexableSkiplist(win) - - for i in range(0, N): - s = start[i] - e = end[i] - - if i == 0: - - # setup - val = input[i] - if val == val: - nobs += 1 - skiplist.insert(val) + skiplist = skiplist_init(<int>win) + if skiplist == NULL: + raise MemoryError("skiplist_init failed") - else: + with nogil: + for i in range(0, N): + s = start[i] + e = end[i] - # calculate deletes - for j in range(start[i - 1], s): - val = input[j] - if val == val: - skiplist.remove(val) - nobs -= 1 + if i == 0: - # calculate adds - for j in range(end[i - 1], e): - val = input[j] + # setup + val = input[i] if val == val: nobs += 1 - skiplist.insert(val) + skiplist_insert(skiplist, val) - if nobs >= minp: - idx = int(quantile * <double>(nobs - 1)) + else: - # Single value in skip list - if nobs == 1: - output[i] = skiplist.get(0) + # calculate deletes + for j in range(start[i - 1], s): + val = input[j] + if val == val: + skiplist_remove(skiplist, val) + nobs -= 1 - # Interpolated quantile + # calculate adds + for j in range(end[i - 1], e): + val = input[j] + if val == val: + nobs += 1 + skiplist_insert(skiplist, val) + + if nobs >= minp: + if nobs == 1: + # Single value in skip list + output[i] = skiplist_get(skiplist, 0, &ret) + else: + idx_with_fraction = quantile * (nobs - 1) + idx = <int> idx_with_fraction + + if idx_with_fraction == idx: + # no need to interpolate + output[i] = skiplist_get(skiplist, idx, &ret) + continue + + if interpolation_type == LINEAR: + vlow = skiplist_get(skiplist, idx, &ret) + vhigh = skiplist_get(skiplist, idx + 1, &ret) + output[i] = ((vlow + (vhigh - vlow) * + (idx_with_fraction - idx))) + elif interpolation_type == LOWER: + output[i] = skiplist_get(skiplist, idx, &ret) + elif interpolation_type == HIGHER: + output[i] = skiplist_get(skiplist, idx + 1, &ret) + elif interpolation_type == NEAREST: + # the same behaviour as round() + if idx_with_fraction - idx == 0.5: + if idx % 2 == 0: + output[i] = skiplist_get(skiplist, idx, &ret) + else: + output[i] = skiplist_get(skiplist, idx + 1, &ret) + elif idx_with_fraction - idx < 0.5: + output[i] = skiplist_get(skiplist, idx, &ret) + else: + output[i] = skiplist_get(skiplist, idx + 1, &ret) + elif interpolation_type == MIDPOINT: + vlow = skiplist_get(skiplist, idx, &ret) + vhigh = skiplist_get(skiplist, idx + 1, &ret) + output[i] = <double> (vlow + vhigh) / 2 else: - vlow = skiplist.get(idx) - vhigh = skiplist.get(idx + 1) - output[i] = ((vlow + (vhigh - vlow) * - (quantile * (nobs - 1) - idx))) - else: - output[i] = NaN + output[i] = NaN return output diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 35bfd12466429..de6985ef3b4ea 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7079,6 +7079,10 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, a b 0.1 1.3 3.7 0.5 2.5 55.0 + + See Also + -------- + pandas.core.window.Rolling.quantile """ self._check_percentile(q) diff --git a/pandas/core/series.py b/pandas/core/series.py index 13e94f971d003..aa4cb510feb62 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1855,6 +1855,9 @@ def quantile(self, q=0.5, interpolation='linear'): 0.75 3.25 dtype: float64 + See Also + -------- + pandas.core.window.Rolling.quantile """ self._check_percentile(q) diff --git a/pandas/core/window.py b/pandas/core/window.py index f8b5aa292f309..96630258c3e50 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -1276,9 +1276,53 @@ def kurt(self, **kwargs): Parameters ---------- quantile : float - 0 <= quantile <= 1""") + 0 <= quantile <= 1 + interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} + .. versionadded:: 0.23.0 + + This optional parameter specifies the interpolation method to use, + when the desired quantile lies between two data points `i` and `j`: + + * linear: `i + (j - i) * fraction`, where `fraction` is the + fractional part of the index surrounded by `i` and `j`. + * lower: `i`. + * higher: `j`. + * nearest: `i` or `j` whichever is nearest. + * midpoint: (`i` + `j`) / 2. + + Returns + ------- + Series or DataFrame + Returned object type is determined by the caller of the %(name)s + calculation. + + Examples + -------- + >>> s = Series([1, 2, 3, 4]) + >>> s.rolling(2).quantile(.4, interpolation='lower') + 0 NaN + 1 1.0 + 2 2.0 + 3 3.0 + dtype: float64 + + >>> s.rolling(2).quantile(.4, interpolation='midpoint') + 0 NaN + 1 1.5 + 2 2.5 + 3 3.5 + dtype: float64 + + See Also + -------- + pandas.Series.quantile : Computes value at the given quantile over all data + in Series. + pandas.DataFrame.quantile : Computes values at the given quantile over + requested axis in DataFrame. + + """) - def quantile(self, quantile, **kwargs): + def quantile(self, quantile, interpolation='linear', **kwargs): window = self._get_window() index, indexi = self._get_index() @@ -1292,7 +1336,8 @@ def f(arg, *args, **kwargs): self.closed) else: return _window.roll_quantile(arg, window, minp, indexi, - self.closed, quantile) + self.closed, quantile, + interpolation) return self._apply(f, 'quantile', quantile=quantile, **kwargs) @@ -1613,8 +1658,10 @@ def kurt(self, **kwargs): @Substitution(name='rolling') @Appender(_doc_template) @Appender(_shared_docs['quantile']) - def quantile(self, quantile, **kwargs): - return super(Rolling, self).quantile(quantile=quantile, **kwargs) + def quantile(self, quantile, interpolation='linear', **kwargs): + return super(Rolling, self).quantile(quantile=quantile, + interpolation=interpolation, + **kwargs) @Substitution(name='rolling') @Appender(_doc_template) @@ -1872,8 +1919,10 @@ def kurt(self, **kwargs): @Substitution(name='expanding') @Appender(_doc_template) @Appender(_shared_docs['quantile']) - def quantile(self, quantile, **kwargs): - return super(Expanding, self).quantile(quantile=quantile, **kwargs) + def quantile(self, quantile, interpolation='linear', **kwargs): + return super(Expanding, self).quantile(quantile=quantile, + interpolation=interpolation, + **kwargs) @Substitution(name='expanding') @Appender(_doc_template) diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 605230390ff1d..304e3d02466a5 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -6,6 +6,7 @@ from datetime import datetime, timedelta from numpy.random import randn import numpy as np +from pandas import _np_version_under1p12 import pandas as pd from pandas import (Series, DataFrame, bdate_range, @@ -1166,15 +1167,40 @@ def test_rolling_quantile_np_percentile(self): tm.assert_almost_equal(df_quantile.values, np.array(np_percentile)) - def test_rolling_quantile_series(self): - # #16211: Tests that rolling window's quantile default behavior - # is analogus to Series' quantile - arr = np.arange(100) - s = Series(arr) - q1 = s.quantile(0.1) - q2 = s.rolling(100).quantile(0.1).iloc[-1] + @pytest.mark.skipif(_np_version_under1p12, + reason='numpy midpoint interpolation is broken') + @pytest.mark.parametrize('quantile', [0.0, 0.1, 0.45, 0.5, 1]) + @pytest.mark.parametrize('interpolation', ['linear', 'lower', 'higher', + 'nearest', 'midpoint']) + @pytest.mark.parametrize('data', [[1., 2., 3., 4., 5., 6., 7.], + [8., 1., 3., 4., 5., 2., 6., 7.], + [0., np.nan, 0.2, np.nan, 0.4], + [np.nan, np.nan, np.nan, np.nan], + [np.nan, 0.1, np.nan, 0.3, 0.4, 0.5], + [0.5], [np.nan, 0.7, 0.6]]) + def test_rolling_quantile_interpolation_options(self, quantile, + interpolation, data): + # Tests that rolling window's quantile behavior is analogous to + # Series' quantile for each interpolation option + s = Series(data) + + q1 = s.quantile(quantile, interpolation) + q2 = s.expanding(min_periods=1).quantile( + quantile, interpolation).iloc[-1] + + if np.isnan(q1): + assert np.isnan(q2) + else: + assert q1 == q2 + + def test_invalid_quantile_value(self): + data = np.arange(5) + s = Series(data) - tm.assert_almost_equal(q1, q2) + with pytest.raises(ValueError, match="Interpolation 'invalid'" + " is not supported"): + s.rolling(len(data), min_periods=1).quantile( + 0.5, interpolation='invalid') def test_rolling_quantile_param(self): ser = Series([0.0, .1, .5, .9, 1.0])
It version 0.21.0 rolling quantile started to use linear interpolation, it broke backward compatibility. Regular (not rolling) quantile supports these interpolation options: `linear`, `lower`, `higher`, `nearest` and `midpoint`. This commit adds the same options to moving quantile. Performance issues of this commit (note: I re-run benchmarks, see message below) This code has 15% worse performance on benchmarks with small values of window (`window=10`). This is because loop inside `roll_quantile` now contains switch. I tried to replace switch with callback but it led to even worse performance. Even if I move some of the code to new function (without any change in logic) it still makes performance much worse. How bad is it? Could you please give me an advice on how to arrange the code such that it has the same performance? - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20497
2018-03-27T09:34:52Z
2018-04-24T11:29:35Z
2018-04-24T11:29:34Z
2018-04-24T11:30:07Z
DOC: update the pandas.Series.str.endswith docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index b98fa106336fc..1703de5714bdf 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -348,19 +348,54 @@ def str_startswith(arr, pat, na=np.nan): def str_endswith(arr, pat, na=np.nan): """ - Return boolean Series indicating whether each string in the - Series/Index ends with passed pattern. Equivalent to - :meth:`str.endswith`. + Test if the end of each string element matches a pattern. + + Equivalent to :meth:`str.endswith`. Parameters ---------- - pat : string - Character sequence - na : bool, default NaN + pat : str + Character sequence. Regular expressions are not accepted. + na : object, default NaN + Object shown if element tested is not a string. Returns ------- - endswith : Series/array of boolean values + Series or Index of bool + A Series of booleans indicating whether the given pattern matches + the end of each string element. + + See Also + -------- + str.endswith : Python standard library string method. + Series.str.startswith : Same as endswith, but tests the start of string. + Series.str.contains : Tests if string element contains a pattern. + + Examples + -------- + >>> s = pd.Series(['bat', 'bear', 'caT', np.nan]) + >>> s + 0 bat + 1 bear + 2 caT + 3 NaN + dtype: object + + >>> s.str.endswith('t') + 0 True + 1 False + 2 False + 3 NaN + dtype: object + + Specifying `na` to be `False` instead of `NaN`. + + >>> s.str.endswith('t', na=False) + 0 True + 1 False + 2 False + 3 False + dtype: bool """ f = lambda x: x.endswith(pat) return _na_map(f, arr, na, dtype=bool)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [ X] PR title is "DOC: update the <your-function-or-method> docstring" - [X ] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [ X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X ] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [ X ] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ #################### Docstring (pandas.Series.str.endswith) #################### ################################################################################ Test if the end of each string element matches a pattern. Equivalent to :meth:`str.endswith`. Parameters ---------- pat : str Character sequence. Regular expressions are not accepted. na : object, default NaN Object shown if element tested is not a string. Returns ------- Series or Index of bool A Series of booleans indicating whether the given pattern matches the end of each string element. See Also -------- str.endswith : Python standard library string method. Series.str.startswith : Same as endswith, but tests the start of string. Series.str.contains : Tests if string element contains a pattern. Examples -------- >>> s = pd.Series(['bat', 'bear', 'caT', np.nan]) >>> s 0 bat 1 bear 2 caT 3 NaN dtype: object >>> s.str.endswith('t') 0 True 1 False 2 False 3 NaN dtype: object Specifying `na` to be `False` instead of `NaN`. >>> s.str.endswith('t', na=False) 0 True 1 False 2 False 3 False dtype: bool ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Series.str.endswith" correct. :) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20491
2018-03-26T14:20:57Z
2018-03-28T16:15:13Z
2018-03-28T16:15:13Z
2018-03-28T16:15:13Z
CLN: remove deprecated infer_dst keyword
diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index e1a6bc7a68e9d..eada401d2930b 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -75,8 +75,7 @@ def setup(self): freq='S')) def time_infer_dst(self): - with warnings.catch_warnings(record=True): - self.index.tz_localize('US/Eastern', infer_dst=True) + self.index.tz_localize('US/Eastern', ambiguous='infer') class ResetIndex(object): diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index 466c48b780861..86cff4a358975 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -2191,10 +2191,9 @@ Ambiguous Times when Localizing In some cases, localize cannot determine the DST and non-DST hours when there are duplicates. This often happens when reading files or database records that simply -duplicate the hours. Passing ``ambiguous='infer'`` (``infer_dst`` argument in prior -releases) into ``tz_localize`` will attempt to determine the right offset. Below -the top example will fail as it contains ambiguous times and the bottom will -infer the right offset. +duplicate the hours. Passing ``ambiguous='infer'`` into ``tz_localize`` will +attempt to determine the right offset. Below the top example will fail as it +contains ambiguous times and the bottom will infer the right offset. .. ipython:: python diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 39bfc8c633dbb..ced3cdd7a81f4 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -777,6 +777,10 @@ Removal of prior version deprecations/changes - The top-level functions ``pd.rolling_*``, ``pd.expanding_*`` and ``pd.ewm*`` have been removed (Deprecated since v0.18). Instead, use the DataFrame/Series methods :attr:`~DataFrame.rolling`, :attr:`~DataFrame.expanding` and :attr:`~DataFrame.ewm` (:issue:`18723`) - Imports from ``pandas.core.common`` for functions such as ``is_datetime64_dtype`` are now removed. These are located in ``pandas.api.types``. (:issue:`13634`, :issue:`19769`) +- The ``infer_dst`` keyword in :meth:`Series.tz_localize`, :meth:`DatetimeIndex.tz_localize` + and :class:`DatetimeIndex` have been removed. ``infer_dst=True`` is equivalent to + ``ambiguous='infer'``, and ``infer_dst=False`` to ``ambiguous='raise'`` (:issue:`7963`). + .. _whatsnew_0230.performance: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fc6eda0290c28..6810aff56806f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7937,9 +7937,6 @@ def _tz_convert(ax, tz): result.set_axis(ax, axis=axis, inplace=True) return result.__finalize__(self) - @deprecate_kwarg(old_arg_name='infer_dst', new_arg_name='ambiguous', - mapping={True: 'infer', - False: 'raise'}) def tz_localize(self, tz, axis=0, level=None, copy=True, ambiguous='raise'): """ @@ -7963,9 +7960,6 @@ def tz_localize(self, tz, axis=0, level=None, copy=True, - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times - infer_dst : boolean, default False - .. deprecated:: 0.15.0 - Attempt to infer fall dst-transition hours based on order Returns ------- diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e8bc9a2519333..75f4ec4f0d341 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -208,9 +208,6 @@ class DatetimeIndex(DatelikeOps, TimelikeOps, DatetimeIndexOpsMixin, times) - 'NaT' will return NaT where there are ambiguous times - 'raise' will raise an AmbiguousTimeError if there are ambiguous times - infer_dst : boolean, default False - .. deprecated:: 0.15.0 - Attempt to infer fall dst-transition hours based on order name : object Name to be stored in the index dayfirst : bool, default False @@ -329,8 +326,6 @@ def _add_comparison_methods(cls): _is_numeric_dtype = False _infer_as_myclass = True - @deprecate_kwarg(old_arg_name='infer_dst', new_arg_name='ambiguous', - mapping={True: 'infer', False: 'raise'}) def __new__(cls, data=None, freq=None, start=None, end=None, periods=None, tz=None, normalize=False, closed=None, ambiguous='raise', @@ -2270,8 +2265,6 @@ def tz_convert(self, tz): # No conversion since timestamps are all UTC to begin with return self._shallow_copy(tz=tz) - @deprecate_kwarg(old_arg_name='infer_dst', new_arg_name='ambiguous', - mapping={True: 'infer', False: 'raise'}) def tz_localize(self, tz, ambiguous='raise', errors='raise'): """ Localize tz-naive DatetimeIndex to tz-aware DatetimeIndex. @@ -2306,10 +2299,6 @@ def tz_localize(self, tz, ambiguous='raise', errors='raise'): .. versionadded:: 0.19.0 - infer_dst : boolean, default False - .. deprecated:: 0.15.0 - Attempt to infer fall dst-transition hours based on order - Returns ------- DatetimeIndex diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 705dc36d92522..4a224d4e6ee7f 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1095,7 +1095,7 @@ def tz_convert(self, tz): """ raise NotImplementedError("Not yet implemented for PeriodIndex") - def tz_localize(self, tz, infer_dst=False): + def tz_localize(self, tz, ambiguous='raise'): """ Localize tz-naive DatetimeIndex to given time zone (using pytz/dateutil), or remove timezone from tz-aware DatetimeIndex @@ -1106,8 +1106,6 @@ def tz_localize(self, tz, infer_dst=False): Time zone for time. Corresponding timestamps would be converted to time zone of the TimeSeries. None will remove timezone holding local time. - infer_dst : boolean, default False - Attempt to infer fall dst-transition hours based on order Returns ------- diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 2913812db0dd4..a8191816238b1 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -341,9 +341,6 @@ def test_dti_tz_localize_ambiguous_infer(self, tz): di = DatetimeIndex(times) localized = di.tz_localize(tz, ambiguous='infer') tm.assert_index_equal(dr, localized) - with tm.assert_produces_warning(FutureWarning): - localized_old = di.tz_localize(tz, infer_dst=True) - tm.assert_index_equal(dr, localized_old) tm.assert_index_equal(dr, DatetimeIndex(times, tz=tz, ambiguous='infer')) @@ -353,9 +350,6 @@ def test_dti_tz_localize_ambiguous_infer(self, tz): localized = dr.tz_localize(tz) localized_infer = dr.tz_localize(tz, ambiguous='infer') tm.assert_index_equal(localized, localized_infer) - with tm.assert_produces_warning(FutureWarning): - localized_infer_old = dr.tz_localize(tz, infer_dst=True) - tm.assert_index_equal(localized, localized_infer_old) @pytest.mark.parametrize('tz', [pytz.timezone('US/Eastern'), gettz('US/Eastern')]) @@ -525,7 +519,7 @@ def test_dti_tz_localize_ambiguous_flags(self, tz): localized = DatetimeIndex(times, tz=tz, ambiguous=is_dst) tm.assert_index_equal(dr, localized) - # Test duplicate times where infer_dst fails + # Test duplicate times where inferring the dst fails times += times di = DatetimeIndex(times)
This has come up a few times during the docstring improvements: we still had the `infer_dst` deprecations left over (deprecated in 0.15)
https://api.github.com/repos/pandas-dev/pandas/pulls/20490
2018-03-26T13:12:29Z
2018-03-27T10:22:33Z
2018-03-27T10:22:33Z
2018-03-27T11:21:12Z
CI: Fixed deprecationWarning
diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 7d959ea4fcd84..b6303ededd0dc 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -134,7 +134,7 @@ def test_series_constructor_with_same_dtype_ok(): def test_series_constructor_coerce_extension_array_to_dtype_raises(): arr = DecimalArray([decimal.Decimal('10.0')]) - xpr = "Cannot specify a dtype 'int64' .* \('decimal'\)." + xpr = r"Cannot specify a dtype 'int64' .* \('decimal'\)." with tm.assert_raises_regex(ValueError, xpr): pd.Series(arr, dtype='int64')
Closes #20479 Hopefully. I can't reproduce locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/20489
2018-03-26T12:19:50Z
2018-03-26T14:29:06Z
2018-03-26T14:29:05Z
2018-03-26T14:29:17Z
BUG: raise error when setting cached properties
diff --git a/pandas/_libs/properties.pyx b/pandas/_libs/properties.pyx index e3f16f224db1c..0f2900619fdb6 100644 --- a/pandas/_libs/properties.pyx +++ b/pandas/_libs/properties.pyx @@ -37,6 +37,9 @@ cdef class CachedProperty(object): PyDict_SetItem(cache, self.name, val) return val + def __set__(self, obj, value): + raise AttributeError("Can't set attribute") + cache_readonly = CachedProperty diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 22ef2fe7aa19e..ff9c86fbfe384 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2056,6 +2056,11 @@ def test_iadd_preserves_name(self): ser.index -= 1 assert ser.index.name == "foo" + def test_cached_properties_not_settable(self): + idx = pd.Index([1, 2, 3]) + with tm.assert_raises_regex(AttributeError, "Can't set attribute"): + idx.is_unique = False + class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ
A bug I introduced myself some time ago in https://github.com/pandas-dev/pandas/pull/19991. Apparently the object needs to explicitly raise in the `__set__` method, otherwise the property is assumed to be settable: ``` In [6]: idx = pd.Index([1, 2, 3]) In [7]: idx.is_unique Out[7]: True In [8]: idx.is_unique = False In [9]: idx.is_unique Out[9]: False In [10]: idx.is_monotonic Out[10]: True In [11]: idx.is_monotonic = False --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-11-b2a74ac7466c> in <module>() ----> 1 idx.is_monotonic = False AttributeError: can't set attribute ``` `is_unique` is a cached property, didn't raise anymore on master (see above), in contrast to normal property `is_monotonic`. This patch ensures also cached properties have the same error.
https://api.github.com/repos/pandas-dev/pandas/pulls/20487
2018-03-26T09:49:38Z
2018-03-26T12:48:49Z
2018-03-26T12:48:49Z
2018-03-26T12:48:53Z
TST: test_nanops some parametrize & catch warnings (RuntimeWarning: All-Nan slice in tests)
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 7b68ad67675ff..601acac20c96d 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -3860,7 +3860,7 @@ def count(self): mask = (ids != -1) & ~isna(val) ids = _ensure_platform_int(ids) - out = np.bincount(ids[mask], minlength=ngroups or None) + out = np.bincount(ids[mask], minlength=ngroups or 0) return Series(out, index=self.grouper.result_index, diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 40f543e211f0c..12bb09e8f8a8a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -99,9 +99,14 @@ def cmp_method(self, other): # don't pass MultiIndex with np.errstate(all='ignore'): result = ops._comp_method_OBJECT_ARRAY(op, self.values, other) + else: - with np.errstate(all='ignore'): - result = op(self.values, np.asarray(other)) + + # numpy will show a DeprecationWarning on invalid elementwise + # comparisons, this will raise in the future + with warnings.catch_warnings(record=True): + with np.errstate(all='ignore'): + result = op(self.values, np.asarray(other)) # technically we could support bool dtyped Index # for now just return the indexing array directly diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 59a30fc69905f..8efa140237614 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -529,7 +529,8 @@ def wrapper(x): self._check_stat_op('median', wrapper, check_dates=True) def test_min(self): - self._check_stat_op('min', np.min, check_dates=True) + with warnings.catch_warnings(record=True): + self._check_stat_op('min', np.min, check_dates=True) self._check_stat_op('min', np.min, frame=self.intframe) def test_cummin(self): @@ -579,7 +580,8 @@ def test_cummax(self): assert np.shape(cummax_xs) == np.shape(self.tsframe) def test_max(self): - self._check_stat_op('max', np.max, check_dates=True) + with warnings.catch_warnings(record=True): + self._check_stat_op('max', np.max, check_dates=True) self._check_stat_op('max', np.max, frame=self.intframe) def test_mad(self): diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index dffb303af6ae1..a70ee80aee180 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -301,24 +301,6 @@ def check_funs(self, testfunc, targfunc, allow_complex=True, allow_complex=allow_complex) self.check_fun(testfunc, targfunc, 'arr_obj', **kwargs) - def check_funs_ddof(self, - testfunc, - targfunc, - allow_complex=True, - allow_all_nan=True, - allow_str=True, - allow_date=False, - allow_tdelta=False, - allow_obj=True, ): - for ddof in range(3): - try: - self.check_funs(testfunc, targfunc, allow_complex, - allow_all_nan, allow_str, allow_date, - allow_tdelta, allow_obj, ddof=ddof) - except BaseException as exc: - exc.args += ('ddof %s' % ddof, ) - raise - def _badobj_wrap(self, value, func, allow_complex=True, **kwargs): if value.dtype.kind == 'O': if allow_complex: @@ -381,37 +363,46 @@ def test_nanmedian(self): allow_str=False, allow_date=False, allow_tdelta=True, allow_obj='convert') - def test_nanvar(self): - self.check_funs_ddof(nanops.nanvar, np.var, allow_complex=False, - allow_str=False, allow_date=False, - allow_tdelta=True, allow_obj='convert') + @pytest.mark.parametrize('ddof', range(3)) + def test_nanvar(self, ddof): + self.check_funs(nanops.nanvar, np.var, allow_complex=False, + allow_str=False, allow_date=False, + allow_tdelta=True, allow_obj='convert', ddof=ddof) - def test_nanstd(self): - self.check_funs_ddof(nanops.nanstd, np.std, allow_complex=False, - allow_str=False, allow_date=False, - allow_tdelta=True, allow_obj='convert') + @pytest.mark.parametrize('ddof', range(3)) + def test_nanstd(self, ddof): + self.check_funs(nanops.nanstd, np.std, allow_complex=False, + allow_str=False, allow_date=False, + allow_tdelta=True, allow_obj='convert', ddof=ddof) @td.skip_if_no('scipy', min_version='0.17.0') - def test_nansem(self): + @pytest.mark.parametrize('ddof', range(3)) + def test_nansem(self, ddof): from scipy.stats import sem with np.errstate(invalid='ignore'): - self.check_funs_ddof(nanops.nansem, sem, allow_complex=False, - allow_str=False, allow_date=False, - allow_tdelta=False, allow_obj='convert') + self.check_funs(nanops.nansem, sem, allow_complex=False, + allow_str=False, allow_date=False, + allow_tdelta=False, allow_obj='convert', ddof=ddof) def _minmax_wrap(self, value, axis=None, func=None): + + # numpy warns if all nan res = func(value, axis) if res.dtype.kind == 'm': res = np.atleast_1d(res) return res def test_nanmin(self): - func = partial(self._minmax_wrap, func=np.min) - self.check_funs(nanops.nanmin, func, allow_str=False, allow_obj=False) + with warnings.catch_warnings(record=True): + func = partial(self._minmax_wrap, func=np.min) + self.check_funs(nanops.nanmin, func, + allow_str=False, allow_obj=False) def test_nanmax(self): - func = partial(self._minmax_wrap, func=np.max) - self.check_funs(nanops.nanmax, func, allow_str=False, allow_obj=False) + with warnings.catch_warnings(record=True): + func = partial(self._minmax_wrap, func=np.max) + self.check_funs(nanops.nanmax, func, + allow_str=False, allow_obj=False) def _argminmax_wrap(self, value, axis=None, func=None): res = func(value, axis) @@ -425,17 +416,15 @@ def _argminmax_wrap(self, value, axis=None, func=None): return res def test_nanargmax(self): - func = partial(self._argminmax_wrap, func=np.argmax) - self.check_funs(nanops.nanargmax, func, allow_str=False, - allow_obj=False, allow_date=True, allow_tdelta=True) + with warnings.catch_warnings(record=True): + func = partial(self._argminmax_wrap, func=np.argmax) + self.check_funs(nanops.nanargmax, func, + allow_str=False, allow_obj=False, + allow_date=True, allow_tdelta=True) def test_nanargmin(self): - func = partial(self._argminmax_wrap, func=np.argmin) - if tm.sys.version_info[0:2] == (2, 6): - self.check_funs(nanops.nanargmin, func, allow_date=True, - allow_tdelta=True, allow_str=False, - allow_obj=False) - else: + with warnings.catch_warnings(record=True): + func = partial(self._argminmax_wrap, func=np.argmin) self.check_funs(nanops.nanargmin, func, allow_str=False, allow_obj=False) diff --git a/pandas/tests/test_panel.py b/pandas/tests/test_panel.py index 301a7fc437fcf..7973b27601237 100644 --- a/pandas/tests/test_panel.py +++ b/pandas/tests/test_panel.py @@ -100,10 +100,12 @@ def wrapper(x): self._check_stat_op('median', wrapper) def test_min(self): - self._check_stat_op('min', np.min) + with catch_warnings(record=True): + self._check_stat_op('min', np.min) def test_max(self): - self._check_stat_op('max', np.max) + with catch_warnings(record=True): + self._check_stat_op('max', np.max) @td.skip_if_no_scipy def test_skew(self):
closes #20011
https://api.github.com/repos/pandas-dev/pandas/pulls/20484
2018-03-25T22:56:33Z
2018-03-26T01:17:39Z
2018-03-26T01:17:39Z
2018-03-26T01:17:39Z
TST: 32-bit compat for categorical factorization tests
diff --git a/pandas/tests/categorical/test_algos.py b/pandas/tests/categorical/test_algos.py index 61764ec0ff632..f727184e862d8 100644 --- a/pandas/tests/categorical/test_algos.py +++ b/pandas/tests/categorical/test_algos.py @@ -15,7 +15,7 @@ def test_factorize(categories, ordered): categories=categories, ordered=ordered) labels, uniques = pd.factorize(cat) - expected_labels = np.array([0, 0, 1, 2, -1], dtype='int64') + expected_labels = np.array([0, 0, 1, 2, -1], dtype=np.intp) expected_uniques = pd.Categorical(['b', 'a', 'c'], categories=categories, ordered=ordered) @@ -27,7 +27,7 @@ def test_factorize(categories, ordered): def test_factorized_sort(): cat = pd.Categorical(['b', 'b', None, 'a']) labels, uniques = pd.factorize(cat, sort=True) - expected_labels = np.array([1, 1, -1, 0], dtype='int64') + expected_labels = np.array([1, 1, -1, 0], dtype=np.intp) expected_uniques = pd.Categorical(['a', 'b']) tm.assert_numpy_array_equal(labels, expected_labels) @@ -40,7 +40,7 @@ def test_factorized_sort_ordered(): ordered=True) labels, uniques = pd.factorize(cat, sort=True) - expected_labels = np.array([0, 0, -1, 1], dtype='int64') + expected_labels = np.array([0, 0, -1, 1], dtype=np.intp) expected_uniques = pd.Categorical(['b', 'a'], categories=['c', 'b', 'a'], ordered=True)
https://travis-ci.org/MacPython/pandas-wheels/jobs/357947315 cc @TomAugspurger
https://api.github.com/repos/pandas-dev/pandas/pulls/20482
2018-03-25T13:38:15Z
2018-03-25T14:10:14Z
2018-03-25T14:10:14Z
2018-03-25T14:10:15Z
removed not necessary bn switch decorator on nansum
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index d4851f579dda4..90333c23817c5 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -326,7 +326,6 @@ def nanall(values, axis=None, skipna=True): @disallow('M8') -@bottleneck_switch() def nansum(values, axis=None, skipna=True, min_count=0): values, mask, dtype, dtype_max = _get_values(values, skipna, 0) dtype_sum = dtype_max
Removed not necessary bottleneck_switch decorator on nansum function like nanprod.
https://api.github.com/repos/pandas-dev/pandas/pulls/20481
2018-03-25T09:50:01Z
2018-03-29T02:31:13Z
2018-03-29T02:31:13Z
2018-03-31T16:37:48Z
Additional DOC and BUG fix related to merging with mix of columns and…
diff --git a/doc/source/merging.rst b/doc/source/merging.rst index 98914c13d4d31..8a25d991c149b 100644 --- a/doc/source/merging.rst +++ b/doc/source/merging.rst @@ -31,10 +31,10 @@ operations. Concatenating objects --------------------- -The :func:`~pandas.concat` function (in the main pandas namespace) does all of -the heavy lifting of performing concatenation operations along an axis while -performing optional set logic (union or intersection) of the indexes (if any) on -the other axes. Note that I say "if any" because there is only a single possible +The :func:`~pandas.concat` function (in the main pandas namespace) does all of +the heavy lifting of performing concatenation operations along an axis while +performing optional set logic (union or intersection) of the indexes (if any) on +the other axes. Note that I say "if any" because there is only a single possible axis of concatenation for Series. Before diving into all of the details of ``concat`` and what it can do, here is @@ -109,9 +109,9 @@ some configurable handling of "what to do with the other axes": to the actual data concatenation. * ``copy`` : boolean, default True. If False, do not copy data unnecessarily. -Without a little bit of context many of these arguments don't make much sense. -Let's revisit the above example. Suppose we wanted to associate specific keys -with each of the pieces of the chopped up DataFrame. We can do this using the +Without a little bit of context many of these arguments don't make much sense. +Let's revisit the above example. Suppose we wanted to associate specific keys +with each of the pieces of the chopped up DataFrame. We can do this using the ``keys`` argument: .. ipython:: python @@ -138,9 +138,9 @@ It's not a stretch to see how this can be very useful. More detail on this functionality below. .. note:: - It is worth noting that :func:`~pandas.concat` (and therefore - :func:`~pandas.append`) makes a full copy of the data, and that constantly - reusing this function can create a significant performance hit. If you need + It is worth noting that :func:`~pandas.concat` (and therefore + :func:`~pandas.append`) makes a full copy of the data, and that constantly + reusing this function can create a significant performance hit. If you need to use the operation over several datasets, use a list comprehension. :: @@ -224,8 +224,8 @@ DataFrame: Concatenating using ``append`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A useful shortcut to :func:`~pandas.concat` are the :meth:`~DataFrame.append` -instance methods on ``Series`` and ``DataFrame``. These methods actually predated +A useful shortcut to :func:`~pandas.concat` are the :meth:`~DataFrame.append` +instance methods on ``Series`` and ``DataFrame``. These methods actually predated ``concat``. They concatenate along ``axis=0``, namely the index: .. ipython:: python @@ -271,8 +271,8 @@ need to be: .. note:: - Unlike the :py:meth:`~list.append` method, which appends to the original list - and returns ``None``, :meth:`~DataFrame.append` here **does not** modify + Unlike the :py:meth:`~list.append` method, which appends to the original list + and returns ``None``, :meth:`~DataFrame.append` here **does not** modify ``df1`` and returns its copy with ``df2`` appended. .. _merging.ignore_index: @@ -370,9 +370,9 @@ Passing ``ignore_index=True`` will drop all name references. More concatenating with group keys ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A fairly common use of the ``keys`` argument is to override the column names +A fairly common use of the ``keys`` argument is to override the column names when creating a new ``DataFrame`` based on existing ``Series``. -Notice how the default behaviour consists on letting the resulting ``DataFrame`` +Notice how the default behaviour consists on letting the resulting ``DataFrame`` inherit the parent ``Series``' name, when these existed. .. ipython:: python @@ -468,7 +468,7 @@ Appending rows to a DataFrame ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While not especially efficient (since a new object must be created), you can -append a single row to a ``DataFrame`` by passing a ``Series`` or dict to +append a single row to a ``DataFrame`` by passing a ``Series`` or dict to ``append``, which returns a new ``DataFrame`` as above. .. ipython:: python @@ -513,7 +513,7 @@ pandas has full-featured, **high performance** in-memory join operations idiomatically very similar to relational databases like SQL. These methods perform significantly better (in some cases well over an order of magnitude better) than other open source implementations (like ``base::merge.data.frame`` -in R). The reason for this is careful algorithmic design and the internal layout +in R). The reason for this is careful algorithmic design and the internal layout of the data in ``DataFrame``. See the :ref:`cookbook<cookbook.merge>` for some advanced strategies. @@ -521,7 +521,7 @@ See the :ref:`cookbook<cookbook.merge>` for some advanced strategies. Users who are familiar with SQL but new to pandas might be interested in a :ref:`comparison with SQL<compare_with_sql.join>`. -pandas provides a single function, :func:`~pandas.merge`, as the entry point for +pandas provides a single function, :func:`~pandas.merge`, as the entry point for all standard database join operations between ``DataFrame`` or named ``Series`` objects: :: @@ -590,7 +590,7 @@ The return type will be the same as ``left``. If ``left`` is a ``DataFrame`` or and ``right`` is a subclass of ``DataFrame``, the return type will still be ``DataFrame``. ``merge`` is a function in the pandas namespace, and it is also available as a -``DataFrame`` instance method :meth:`~DataFrame.merge`, with the calling +``DataFrame`` instance method :meth:`~DataFrame.merge`, with the calling ``DataFrame`` being implicitly considered the left object in the join. The related :meth:`~DataFrame.join` method, uses ``merge`` internally for the @@ -602,7 +602,7 @@ Brief primer on merge methods (relational algebra) Experienced users of relational databases like SQL will be familiar with the terminology used to describe join operations between two SQL-table like -structures (``DataFrame`` objects). There are several cases to consider which +structures (``DataFrame`` objects). There are several cases to consider which are very important to understand: * **one-to-one** joins: for example when joining two ``DataFrame`` objects on @@ -642,8 +642,8 @@ key combination: labels=['left', 'right'], vertical=False); plt.close('all'); -Here is a more complicated example with multiple join keys. Only the keys -appearing in ``left`` and ``right`` are present (the intersection), since +Here is a more complicated example with multiple join keys. Only the keys +appearing in ``left`` and ``right`` are present (the intersection), since ``how='inner'`` by default. .. ipython:: python @@ -759,13 +759,13 @@ Checking for duplicate keys .. versionadded:: 0.21.0 -Users can use the ``validate`` argument to automatically check whether there -are unexpected duplicates in their merge keys. Key uniqueness is checked before -merge operations and so should protect against memory overflows. Checking key -uniqueness is also a good way to ensure user data structures are as expected. +Users can use the ``validate`` argument to automatically check whether there +are unexpected duplicates in their merge keys. Key uniqueness is checked before +merge operations and so should protect against memory overflows. Checking key +uniqueness is also a good way to ensure user data structures are as expected. -In the following example, there are duplicate values of ``B`` in the right -``DataFrame``. As this is not a one-to-one merge -- as specified in the +In the following example, there are duplicate values of ``B`` in the right +``DataFrame``. As this is not a one-to-one merge -- as specified in the ``validate`` argument -- an exception will be raised. @@ -778,11 +778,11 @@ In the following example, there are duplicate values of ``B`` in the right In [53]: result = pd.merge(left, right, on='B', how='outer', validate="one_to_one") ... - MergeError: Merge keys are not unique in right dataset; not a one-to-one merge + MergeError: Merge keys are not unique in right dataset; not a one-to-one merge -If the user is aware of the duplicates in the right ``DataFrame`` but wants to -ensure there are no duplicates in the left DataFrame, one can use the -``validate='one_to_many'`` argument instead, which will not raise an exception. +If the user is aware of the duplicates in the right ``DataFrame`` but wants to +ensure there are no duplicates in the left DataFrame, one can use the +``validate='one_to_many'`` argument instead, which will not raise an exception. .. ipython:: python @@ -794,8 +794,8 @@ ensure there are no duplicates in the left DataFrame, one can use the The merge indicator ~~~~~~~~~~~~~~~~~~~ -:func:`~pandas.merge` accepts the argument ``indicator``. If ``True``, a -Categorical-type column called ``_merge`` will be added to the output object +:func:`~pandas.merge` accepts the argument ``indicator``. If ``True``, a +Categorical-type column called ``_merge`` will be added to the output object that takes on values: =================================== ================ @@ -903,7 +903,7 @@ Joining on index ~~~~~~~~~~~~~~~~ :meth:`DataFrame.join` is a convenient method for combining the columns of two -potentially differently-indexed ``DataFrames`` into a single result +potentially differently-indexed ``DataFrames`` into a single result ``DataFrame``. Here is a very basic example: .. ipython:: python @@ -983,9 +983,9 @@ indexes: Joining key columns on an index ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -:meth:`~DataFrame.join` takes an optional ``on`` argument which may be a column +:meth:`~DataFrame.join` takes an optional ``on`` argument which may be a column or multiple column names, which specifies that the passed ``DataFrame`` is to be -aligned on that column in the ``DataFrame``. These two function calls are +aligned on that column in the ``DataFrame``. These two function calls are completely equivalent: :: @@ -995,7 +995,7 @@ completely equivalent: how='left', sort=False) Obviously you can choose whichever form you find more convenient. For -many-to-one joins (where one of the ``DataFrame``'s is already indexed by the +many-to-one joins (where one of the ``DataFrame``'s is already indexed by the join key), using ``join`` may be more convenient. Here is a simple example: .. ipython:: python @@ -1133,17 +1133,42 @@ This is equivalent but less verbose and more memory efficient / faster than this Joining with two MultiIndexes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -This is not implemented via ``join`` at-the-moment, however it can be done using -the following code. +This is supported in a limited way, provided that the index for the right +argument is completely used in the join, and is a subset of the indices in +the left argument, as in this example: .. ipython:: python - index = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'), - ('K1', 'X2')], - names=['key', 'X']) + leftindex = pd.MultiIndex.from_product([list('abc'), list('xy'), [1, 2]], + names=['abc', 'xy', 'num']) + left = pd.DataFrame({'v1' : range(12)}, index=leftindex) + left + + rightindex = pd.MultiIndex.from_product([list('abc'), list('xy')], + names=['abc', 'xy']) + right = pd.DataFrame({'v2': [100*i for i in range(1, 7)]}, index=rightindex) + right + + left.join(right, on=['abc', 'xy'], how='inner') + +If that condition is not satisfied, a join with two multi-indexes can be +done using the following code. + +.. ipython:: python + + leftindex = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'), + ('K1', 'X2')], + names=['key', 'X']) left = pd.DataFrame({'A': ['A0', 'A1', 'A2'], 'B': ['B0', 'B1', 'B2']}, - index=index) + index=leftindex) + + rightindex = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'), + ('K2', 'Y2'), ('K2', 'Y3')], + names=['key', 'Y']) + right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'], + 'D': ['D0', 'D1', 'D2', 'D3']}, + index=rightindex) result = pd.merge(left.reset_index(), right.reset_index(), on=['key'], how='inner').set_index(['key','X','Y']) @@ -1161,7 +1186,7 @@ the following code. Merging on a combination of columns and index levels ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 0.22 +.. versionadded:: 0.23 Strings passed as the ``on``, ``left_on``, and ``right_on`` parameters may refer to either column names or index level names. This enables merging @@ -1200,6 +1225,12 @@ resetting indexes. frames, the index level is preserved as an index level in the resulting DataFrame. +.. note:: + When DataFrames are merged using only some of the levels of a `MultiIndex`, + the extra levels will be dropped from the resulting merge. In order to + preserve those levels, use ``reset_index`` on those level names to move + those levels to columns prior to doing the merge. + .. note:: If a string matches both a column name and an index level name, then a @@ -1262,7 +1293,7 @@ similarly. Joining multiple DataFrame or Panel objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -A list or tuple of ``DataFrames`` can also be passed to :meth:`~DataFrame.join` +A list or tuple of ``DataFrames`` can also be passed to :meth:`~DataFrame.join` to join them together on their indexes. .. ipython:: python @@ -1284,7 +1315,7 @@ Merging together values within Series or DataFrame columns ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Another fairly common situation is to have two like-indexed (or similarly -indexed) ``Series`` or ``DataFrame`` objects and wanting to "patch" values in +indexed) ``Series`` or ``DataFrame`` objects and wanting to "patch" values in one object from values for matching indices in the other. Here is an example: .. ipython:: python @@ -1309,7 +1340,7 @@ For this, use the :meth:`~DataFrame.combine_first` method: plt.close('all'); Note that this method only takes values from the right ``DataFrame`` if they are -missing in the left ``DataFrame``. A related method, :meth:`~DataFrame.update`, +missing in the left ``DataFrame``. A related method, :meth:`~DataFrame.update`, alters non-NA values in place: .. ipython:: python @@ -1361,15 +1392,15 @@ Merging AsOf .. versionadded:: 0.19.0 -A :func:`merge_asof` is similar to an ordered left-join except that we match on -nearest key rather than equal keys. For each row in the ``left`` ``DataFrame``, -we select the last row in the ``right`` ``DataFrame`` whose ``on`` key is less +A :func:`merge_asof` is similar to an ordered left-join except that we match on +nearest key rather than equal keys. For each row in the ``left`` ``DataFrame``, +we select the last row in the ``right`` ``DataFrame`` whose ``on`` key is less than the left's key. Both DataFrames must be sorted by the key. -Optionally an asof merge can perform a group-wise merge. This matches the +Optionally an asof merge can perform a group-wise merge. This matches the ``by`` key equally, in addition to the nearest match on the ``on`` key. -For example; we might have ``trades`` and ``quotes`` and we want to ``asof`` +For example; we might have ``trades`` and ``quotes`` and we want to ``asof`` merge them. .. ipython:: python @@ -1428,8 +1459,8 @@ We only asof within ``2ms`` between the quote time and the trade time. by='ticker', tolerance=pd.Timedelta('2ms')) -We only asof within ``10ms`` between the quote time and the trade time and we -exclude exact matches on time. Note that though we exclude the exact matches +We only asof within ``10ms`` between the quote time and the trade time and we +exclude exact matches on time. Note that though we exclude the exact matches (of the quotes), prior quotes **do** propagate to that point in time. .. ipython:: python diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 93ac9caa42e3e..cc37881de30ee 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -1541,6 +1541,7 @@ Reshaping - Bug in :meth:`DataFrame.append` with a :class:`Series` with a dateutil timezone would raise a ``TypeError`` (:issue:`23682`) - Bug in ``Series`` construction when passing no data and ``dtype=str`` (:issue:`22477`) - Bug in :func:`cut` with ``bins`` as an overlapping ``IntervalIndex`` where multiple bins were returned per item instead of raising a ``ValueError`` (:issue:`23980`) +- Bug in :meth:`DataFrame.join` when joining on partial MultiIndex would drop names (:issue:`20452`). .. _whatsnew_0240.bug_fixes.sparse: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index dfbee5656da7d..b078ff32f6944 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -715,6 +715,7 @@ def _maybe_add_join_keys(self, result, left_indexer, right_indexer): result[name] = key_col elif result._is_level_reference(name): if isinstance(result.index, MultiIndex): + key_col.name = name idx_list = [result.index.get_level_values(level_name) if level_name != name else key_col for level_name in result.index.names] diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 5387a1043e00e..99386e594ff3a 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -730,6 +730,31 @@ def test_panel_join_many(self): pytest.raises(ValueError, panels[0].join, panels[1:], how='right') + def test_join_multi_to_multi(self, join_type): + # GH 20475 + leftindex = MultiIndex.from_product([list('abc'), list('xy'), [1, 2]], + names=['abc', 'xy', 'num']) + left = DataFrame({'v1': range(12)}, index=leftindex) + + rightindex = MultiIndex.from_product([list('abc'), list('xy')], + names=['abc', 'xy']) + right = DataFrame({'v2': [100 * i for i in range(1, 7)]}, + index=rightindex) + + result = left.join(right, on=['abc', 'xy'], how=join_type) + expected = (left.reset_index() + .merge(right.reset_index(), + on=['abc', 'xy'], how=join_type) + .set_index(['abc', 'xy', 'num']) + ) + assert_frame_equal(expected, result) + + with pytest.raises(ValueError): + left.join(right, on='xy', how=join_type) + + with pytest.raises(ValueError): + right.join(left, on=['abc', 'xy'], how=join_type) + def _check_join(left, right, result, join_col, how='left', lsuffix='_x', rsuffix='_y'): diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 7ee88f223cd95..94e180f9328d6 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1397,16 +1397,16 @@ def test_merge_index_types(index): assert_frame_equal(result, expected) -@pytest.mark.parametrize("on,left_on,right_on,left_index,right_index,nms,nm", [ - (['outer', 'inner'], None, None, False, False, ['outer', 'inner'], 'B'), - (None, None, None, True, True, ['outer', 'inner'], 'B'), - (None, ['outer', 'inner'], None, False, True, None, 'B'), - (None, None, ['outer', 'inner'], True, False, None, 'B'), - (['outer', 'inner'], None, None, False, False, ['outer', 'inner'], None), - (None, None, None, True, True, ['outer', 'inner'], None), - (None, ['outer', 'inner'], None, False, True, None, None), - (None, None, ['outer', 'inner'], True, False, None, None)]) -def test_merge_series(on, left_on, right_on, left_index, right_index, nms, nm): +@pytest.mark.parametrize("on,left_on,right_on,left_index,right_index,nm", [ + (['outer', 'inner'], None, None, False, False, 'B'), + (None, None, None, True, True, 'B'), + (None, ['outer', 'inner'], None, False, True, 'B'), + (None, None, ['outer', 'inner'], True, False, 'B'), + (['outer', 'inner'], None, None, False, False, None), + (None, None, None, True, True, None), + (None, ['outer', 'inner'], None, False, True, None), + (None, None, ['outer', 'inner'], True, False, None)]) +def test_merge_series(on, left_on, right_on, left_index, right_index, nm): # GH 21220 a = pd.DataFrame({"A": [1, 2, 3, 4]}, index=pd.MultiIndex.from_product([['a', 'b'], [0, 1]], @@ -1416,7 +1416,7 @@ def test_merge_series(on, left_on, right_on, left_index, right_index, nms, nm): names=['outer', 'inner']), name=nm) expected = pd.DataFrame({"A": [2, 4], "B": [1, 3]}, index=pd.MultiIndex.from_product([['a', 'b'], [1]], - names=nms)) + names=['outer', 'inner'])) if nm is not None: result = pd.merge(a, b, on=on, left_on=left_on, right_on=right_on, left_index=left_index, right_index=right_index)
Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [x] closes #20452 - [x] tests added / passed - test_join.py - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry - added to v0.24 related to bug fix This PR adds some documentation about how `MultiLevel` index levels are dropped when doing a merge that includes levels and columns. It also fixes a small bug related to `join`.
https://api.github.com/repos/pandas-dev/pandas/pulls/20475
2018-03-23T22:20:56Z
2018-12-04T13:11:04Z
2018-12-04T13:11:04Z
2019-07-12T17:21:10Z
DOC: docstring to series.unique
diff --git a/pandas/core/base.py b/pandas/core/base.py index b3eb9a0ae7530..7c31ea32bfa19 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1020,30 +1020,6 @@ def value_counts(self, normalize=False, sort=True, ascending=False, normalize=normalize, bins=bins, dropna=dropna) return result - _shared_docs['unique'] = ( - """ - Return unique values in the object. Uniques are returned in order - of appearance, this does NOT sort. Hash table-based unique. - - Parameters - ---------- - values : 1d array-like - - Returns - ------- - unique values. - - If the input is an Index, the return is an Index - - If the input is a Categorical dtype, the return is a Categorical - - If the input is a Series/ndarray, the return will be an ndarray - - See Also - -------- - unique - Index.unique - Series.unique - """) - - @Appender(_shared_docs['unique'] % _indexops_doc_kwargs) def unique(self): values = self._values diff --git a/pandas/core/series.py b/pandas/core/series.py index da598259d272d..48e6453e36491 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1429,8 +1429,51 @@ def mode(self): # TODO: Add option for bins like value_counts() return algorithms.mode(self) - @Appender(base._shared_docs['unique'] % _shared_doc_kwargs) def unique(self): + """ + Return unique values of Series object. + + Uniques are returned in order of appearance. Hash table-based unique, + therefore does NOT sort. + + Returns + ------- + ndarray or Categorical + The unique values returned as a NumPy array. In case of categorical + data type, returned as a Categorical. + + See Also + -------- + pandas.unique : top-level unique method for any 1-d array-like object. + Index.unique : return Index with unique values from an Index object. + + Examples + -------- + >>> pd.Series([2, 1, 3, 3], name='A').unique() + array([2, 1, 3]) + + >>> pd.Series([pd.Timestamp('2016-01-01') for _ in range(3)]).unique() + array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]') + + >>> pd.Series([pd.Timestamp('2016-01-01', tz='US/Eastern') + ... for _ in range(3)]).unique() + array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], + dtype=object) + + An unordered Categorical will return categories in the order of + appearance. + + >>> pd.Series(pd.Categorical(list('baabc'))).unique() + [b, a, c] + Categories (3, object): [b, a, c] + + An ordered Categorical preserves the category ordering. + + >>> pd.Series(pd.Categorical(list('baabc'), categories=list('abc'), + ... ordered=True)).unique() + [b, a, c] + Categories (3, object): [a < b < c] + """ result = super(Series, self).unique() if is_datetime64tz_dtype(self.dtype):
- [x] closes #20075 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry seems that no one has picked this up. moving _shared_doc['unique'] used by Series.unique() only to Series.unique. ``` ################################################################################ ####################### Docstring (pandas.Series.unique) ####################### ################################################################################ Return unique values of Series object. Uniques are returned in order of appearance. Hash table-based unique, therefore does NOT sort. Returns ------- unique values. - If the input is an Index, the return is an Index - If the input is a Categorical dtype, the return is a Categorical - If the input is a Series/ndarray, the return will be an ndarray See Also -------- unique : return unique values of 1d array-like objects. Index.unique : return Index with unique values from an Index object. Examples -------- >>> pd.Series([2, 1, 3, 3], name='A').unique() array([2, 1, 3]) >>> pd.Series([2] + [1] * 5).unique() array([2, 1]) >>> pd.Series([pd.Timestamp('20160101') for _ in range(3)]).unique() array(['2016-01-01T00:00:00.000000000'], dtype='datetime64[ns]') >>> pd.Series([pd.Timestamp('20160101', tz='US/Eastern') for _ in range(3)]).unique() array([Timestamp('2016-01-01 00:00:00-0500', tz='US/Eastern')], dtype=object) An unordered Categorical will return categories in the order of appearance. >>> pd.Series(pd.Categorical(list('baabc'))).unique() [b, a, c] Categories (3, object): [b, a, c] An ordered Categorical preserves the category ordering. >>> pd.Series(pd.Categorical(list('baabc'), categories=list('abc'), ordered=True)).unique() [b, a, c] Categories (3, object): [a < b < c] ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Series.unique" correct. :) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20474
2018-03-23T22:08:19Z
2018-03-27T20:50:12Z
2018-03-27T20:50:12Z
2018-03-27T21:39:46Z
Parametrized NA sentinel for factorize
diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx index 07b4b80603e03..15d93374da3a9 100644 --- a/pandas/_libs/hashtable.pyx +++ b/pandas/_libs/hashtable.pyx @@ -70,7 +70,7 @@ cdef class Factorizer: return self.count def factorize(self, ndarray[object] values, sort=False, na_sentinel=-1, - check_null=True): + na_value=None): """ Factorize values with nans replaced by na_sentinel >>> factorize(np.array([1,2,np.nan], dtype='O'), na_sentinel=20) @@ -81,7 +81,7 @@ cdef class Factorizer: uniques.extend(self.uniques.to_array()) self.uniques = uniques labels = self.table.get_labels(values, self.uniques, - self.count, na_sentinel, check_null) + self.count, na_sentinel, na_value) mask = (labels == na_sentinel) # sort on if sort: @@ -114,7 +114,7 @@ cdef class Int64Factorizer: return self.count def factorize(self, int64_t[:] values, sort=False, - na_sentinel=-1, check_null=True): + na_sentinel=-1, na_value=None): """ Factorize values with nans replaced by na_sentinel >>> factorize(np.array([1,2,np.nan], dtype='O'), na_sentinel=20) @@ -126,7 +126,7 @@ cdef class Int64Factorizer: self.uniques = uniques labels = self.table.get_labels(values, self.uniques, self.count, na_sentinel, - check_null) + na_value=na_value) # sort on if sort: diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index bca4e388f3279..eca66f78499db 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -250,13 +250,13 @@ cdef class HashTable: {{py: -# name, dtype, null_condition, float_group -dtypes = [('Float64', 'float64', 'val != val', True), - ('UInt64', 'uint64', 'False', False), - ('Int64', 'int64', 'val == iNaT', False)] +# name, dtype, float_group, default_na_value +dtypes = [('Float64', 'float64', True, 'nan'), + ('UInt64', 'uint64', False, 0), + ('Int64', 'int64', False, 'iNaT')] def get_dispatch(dtypes): - for (name, dtype, null_condition, float_group) in dtypes: + for (name, dtype, float_group, default_na_value) in dtypes: unique_template = """\ cdef: Py_ssize_t i, n = len(values) @@ -298,13 +298,13 @@ def get_dispatch(dtypes): return uniques.to_array() """ - unique_template = unique_template.format(name=name, dtype=dtype, null_condition=null_condition, float_group=float_group) + unique_template = unique_template.format(name=name, dtype=dtype, float_group=float_group) - yield (name, dtype, null_condition, float_group, unique_template) + yield (name, dtype, float_group, default_na_value, unique_template) }} -{{for name, dtype, null_condition, float_group, unique_template in get_dispatch(dtypes)}} +{{for name, dtype, float_group, default_na_value, unique_template in get_dispatch(dtypes)}} cdef class {{name}}HashTable(HashTable): @@ -408,24 +408,36 @@ cdef class {{name}}HashTable(HashTable): @cython.boundscheck(False) def get_labels(self, {{dtype}}_t[:] values, {{name}}Vector uniques, Py_ssize_t count_prior, Py_ssize_t na_sentinel, - bint check_null=True): + object na_value=None): cdef: Py_ssize_t i, n = len(values) int64_t[:] labels Py_ssize_t idx, count = count_prior int ret = 0 - {{dtype}}_t val + {{dtype}}_t val, na_value2 khiter_t k {{name}}VectorData *ud + bint use_na_value labels = np.empty(n, dtype=np.int64) ud = uniques.data + use_na_value = na_value is not None + + if use_na_value: + # We need this na_value2 because we want to allow users + # to *optionally* specify an NA sentinel *of the correct* type. + # We use None, to make it optional, which requires `object` type + # for the parameter. To please the compiler, we use na_value2, + # which is only used if it's *specified*. + na_value2 = <{{dtype}}_t>na_value + else: + na_value2 = {{default_na_value}} with nogil: for i in range(n): val = values[i] - if check_null and {{null_condition}}: + if val != val or (use_na_value and val == na_value2): labels[i] = na_sentinel continue @@ -695,7 +707,7 @@ cdef class StringHashTable(HashTable): @cython.boundscheck(False) def get_labels(self, ndarray[object] values, ObjectVector uniques, Py_ssize_t count_prior, int64_t na_sentinel, - bint check_null=1): + object na_value=None): cdef: Py_ssize_t i, n = len(values) int64_t[:] labels @@ -706,10 +718,12 @@ cdef class StringHashTable(HashTable): char *v char **vecs khiter_t k + bint use_na_value # these by-definition *must* be strings labels = np.zeros(n, dtype=np.int64) uindexer = np.empty(n, dtype=np.int64) + use_na_value = na_value is not None # pre-filter out missing # and assign pointers @@ -717,7 +731,8 @@ cdef class StringHashTable(HashTable): for i in range(n): val = values[i] - if PyUnicode_Check(val) or PyString_Check(val): + if ((PyUnicode_Check(val) or PyString_Check(val)) and + not (use_na_value and val == na_value)): v = util.get_c_string(val) vecs[i] = v else: @@ -868,7 +883,7 @@ cdef class PyObjectHashTable(HashTable): def get_labels(self, ndarray[object] values, ObjectVector uniques, Py_ssize_t count_prior, int64_t na_sentinel, - bint check_null=True): + object na_value=None): cdef: Py_ssize_t i, n = len(values) int64_t[:] labels @@ -876,14 +891,17 @@ cdef class PyObjectHashTable(HashTable): int ret = 0 object val khiter_t k + bint use_na_value labels = np.empty(n, dtype=np.int64) + use_na_value = na_value is not None for i in range(n): val = values[i] hash(val) - if check_null and val != val or val is None: + if ((val != val or val is None) or + (use_na_value and val == na_value)): labels[i] = na_sentinel continue diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index de2e638265f1e..45f86f044a4b2 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -29,7 +29,7 @@ _ensure_float64, _ensure_uint64, _ensure_int64) from pandas.compat.numpy import _np_version_under1p10 -from pandas.core.dtypes.missing import isna +from pandas.core.dtypes.missing import isna, na_value_for_dtype from pandas.core import common as com from pandas._libs import algos, lib, hashtable as htable @@ -435,7 +435,8 @@ def isin(comps, values): return f(comps, values) -def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None): +def _factorize_array(values, na_sentinel=-1, size_hint=None, + na_value=None): """Factorize an array-like to labels and uniques. This doesn't do any coercion of types or unboxing before factorization. @@ -443,11 +444,14 @@ def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None): Parameters ---------- values : ndarray - check_nulls : bool - Whether to check for nulls in the hashtable's 'get_labels' method. na_sentinel : int, default -1 size_hint : int, optional Passsed through to the hashtable's 'get_labels' method + na_value : object, optional + A value in `values` to consider missing. Note: only use this + parameter when you know that you don't have any values pandas would + consider missing in the array (NaN for float data, iNaT for + datetimes, etc.). Returns ------- @@ -457,7 +461,8 @@ def _factorize_array(values, check_nulls, na_sentinel=-1, size_hint=None): table = hash_klass(size_hint or len(values)) uniques = vec_klass() - labels = table.get_labels(values, uniques, 0, na_sentinel, check_nulls) + labels = table.get_labels(values, uniques, 0, na_sentinel, + na_value=na_value) labels = _ensure_platform_int(labels) uniques = uniques.to_array() @@ -508,10 +513,18 @@ def factorize(values, sort=False, order=None, na_sentinel=-1, size_hint=None): dtype = original.dtype else: values, dtype, _ = _ensure_data(values) - check_nulls = not is_integer_dtype(original) - labels, uniques = _factorize_array(values, check_nulls, + + if (is_datetime64_any_dtype(original) or + is_timedelta64_dtype(original) or + is_period_dtype(original)): + na_value = na_value_for_dtype(original.dtype) + else: + na_value = None + + labels, uniques = _factorize_array(values, na_sentinel=na_sentinel, - size_hint=size_hint) + size_hint=size_hint, + na_value=na_value) if sort and len(uniques) > 0: from pandas.core.sorting import safe_sort diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 6eadef37da344..ac57660300be4 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -7,7 +7,6 @@ from pandas import compat from pandas.compat import u, lzip from pandas._libs import lib, algos as libalgos -from pandas._libs.tslib import iNaT from pandas.core.dtypes.generic import ( ABCSeries, ABCIndexClass, ABCCategoricalIndex) @@ -2163,11 +2162,10 @@ def factorize(self, na_sentinel=-1): from pandas.core.algorithms import _factorize_array codes = self.codes.astype('int64') - codes[codes == -1] = iNaT # We set missing codes, normally -1, to iNaT so that the # Int64HashTable treats them as missing values. - labels, uniques = _factorize_array(codes, check_nulls=True, - na_sentinel=na_sentinel) + labels, uniques = _factorize_array(codes, na_sentinel=na_sentinel, + na_value=-1) uniques = self._constructor(self.categories.take(uniques), categories=self.categories, ordered=self.ordered) diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 01c88c269e7e0..7be00cbfd567a 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -11,6 +11,7 @@ is_datetimelike_v_numeric, is_float_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_timedelta64_dtype, is_interval_dtype, + is_period_dtype, is_complex_dtype, is_string_like_dtype, is_bool_dtype, is_integer_dtype, is_dtype_equal, @@ -393,7 +394,7 @@ def na_value_for_dtype(dtype, compat=True): dtype = pandas_dtype(dtype) if (is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype) or - is_timedelta64_dtype(dtype)): + is_timedelta64_dtype(dtype) or is_period_dtype(dtype)): return NaT elif is_float_dtype(dtype): return np.nan diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 4f208bc352c70..365d8d762d673 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -15,7 +15,8 @@ from pandas import (NaT, Float64Index, Series, DatetimeIndex, TimedeltaIndex, date_range) from pandas.core.dtypes.common import is_scalar -from pandas.core.dtypes.dtypes import DatetimeTZDtype +from pandas.core.dtypes.dtypes import ( + DatetimeTZDtype, PeriodDtype, IntervalDtype) from pandas.core.dtypes.missing import ( array_equivalent, isna, notna, isnull, notnull, na_value_for_dtype) @@ -311,23 +312,27 @@ def test_array_equivalent_str(): np.array(['A', 'X'], dtype=dtype)) -def test_na_value_for_dtype(): - for dtype in [np.dtype('M8[ns]'), np.dtype('m8[ns]'), - DatetimeTZDtype('datetime64[ns, US/Eastern]')]: - assert na_value_for_dtype(dtype) is NaT - - for dtype in ['u1', 'u2', 'u4', 'u8', - 'i1', 'i2', 'i4', 'i8']: - assert na_value_for_dtype(np.dtype(dtype)) == 0 - - for dtype in ['bool']: - assert na_value_for_dtype(np.dtype(dtype)) is False - - for dtype in ['f2', 'f4', 'f8']: - assert np.isnan(na_value_for_dtype(np.dtype(dtype))) - - for dtype in ['O']: - assert np.isnan(na_value_for_dtype(np.dtype(dtype))) +@pytest.mark.parametrize('dtype, na_value', [ + # Datetime-like + (np.dtype("M8[ns]"), NaT), + (np.dtype("m8[ns]"), NaT), + (DatetimeTZDtype('datetime64[ns, US/Eastern]'), NaT), + (PeriodDtype("M"), NaT), + # Integer + ('u1', 0), ('u2', 0), ('u4', 0), ('u8', 0), + ('i1', 0), ('i2', 0), ('i4', 0), ('i8', 0), + # Bool + ('bool', False), + # Float + ('f2', np.nan), ('f4', np.nan), ('f8', np.nan), + # Object + ('O', np.nan), + # Interval + (IntervalDtype(), np.nan), +]) +def test_na_value_for_dtype(dtype, na_value): + result = na_value_for_dtype(dtype) + assert result is na_value class TestNAObj(object): diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 884b1eb7342c6..ada4f880e92a4 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -257,6 +257,36 @@ def test_deprecate_order(self): with tm.assert_produces_warning(False): algos.factorize(data) + @pytest.mark.parametrize('data', [ + np.array([0, 1, 0], dtype='u8'), + np.array([-2**63, 1, -2**63], dtype='i8'), + np.array(['__nan__', 'foo', '__nan__'], dtype='object'), + ]) + def test_parametrized_factorize_na_value_default(self, data): + # arrays that include the NA default for that type, but isn't used. + l, u = algos.factorize(data) + expected_uniques = data[[0, 1]] + expected_labels = np.array([0, 1, 0], dtype='i8') + tm.assert_numpy_array_equal(l, expected_labels) + tm.assert_numpy_array_equal(u, expected_uniques) + + @pytest.mark.parametrize('data, na_value', [ + (np.array([0, 1, 0, 2], dtype='u8'), 0), + (np.array([1, 0, 1, 2], dtype='u8'), 1), + (np.array([-2**63, 1, -2**63, 0], dtype='i8'), -2**63), + (np.array([1, -2**63, 1, 0], dtype='i8'), 1), + (np.array(['a', '', 'a', 'b'], dtype=object), 'a'), + (np.array([(), ('a', 1), (), ('a', 2)], dtype=object), ()), + (np.array([('a', 1), (), ('a', 1), ('a', 2)], dtype=object), + ('a', 1)), + ]) + def test_parametrized_factorize_na_value(self, data, na_value): + l, u = algos._factorize_array(data, na_value=na_value) + expected_uniques = data[[1, 3]] + expected_labels = np.array([-1, 0, -1, 1], dtype='i8') + tm.assert_numpy_array_equal(l, expected_labels) + tm.assert_numpy_array_equal(u, expected_uniques) + class TestUnique(object):
Adds a new keyword `na_value` to control the NA sentinel inside the factorize routine. ```python In [3]: arr = np.array([0, 1, 0, 2], dtype='u8') In [4]: pd.factorize(arr) Out[4]: (array([0, 1, 0, 2]), array([0, 1, 2], dtype=uint64)) In [5]: pd.factorize(arr, na_value=0) Out[5]: (array([-1, 0, -1, 1]), array([1, 2], dtype=uint64)) ``` The basic idea is that our hashtables now have two "modes" for detecting NA values 1. The previous way, based on the templated na_condition 2. Equality to a user-specified NA value. Note: specifying NA value does not "turn off" the old way of checking NAs. ```python In [2]: pd.factorize(np.array([0.0, np.nan, 1.0]), na_value=0.0) Out[2]: (array([-1, -1, 0]), array([1.])) ``` I'm sure the implementation can be cleaned up, but I wanted to put this up for feedback. Hopefully someone can tell me how to avoid the `use_default_na` nonsense :) cc @WillAyd closes https://github.com/pandas-dev/pandas/issues/20328
https://api.github.com/repos/pandas-dev/pandas/pulls/20473
2018-03-23T19:12:53Z
2018-03-27T10:28:11Z
2018-03-27T10:28:10Z
2018-05-02T13:10:07Z
DOC: update the pandas.Series.shift docstring
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6ca8f6731bbb8..096abd4255779 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8361,32 +8361,59 @@ def mask(self, cond, other=np.nan, inplace=False, axis=None, level=None, errors=errors) _shared_docs['shift'] = (""" - Shift index by desired number of periods with an optional time freq + Shift index by desired number of periods with an optional time `freq`. + + When `freq` is not passed, shift the index without realigning the data. + If `freq` is passed (in this case, the index must be date or datetime, + or it will raise a `NotImplementedError`), the index will be + increased using the periods and the `freq`. Parameters ---------- periods : int - Number of periods to move, can be positive or negative. - freq : DateOffset, timedelta, or time rule string, optional - Increment to use from the tseries module or time rule (e.g. 'EOM'). - See Notes. - axis : %(axes_single_arg)s + Number of periods to shift. Can be positive or negative. + freq : DateOffset, tseries.offsets, timedelta, or str, optional + Offset to use from the tseries module or time rule (e.g. 'EOM'). + If `freq` is specified then the index values are shifted but the + data is not realigned. That is, use `freq` if you would like to + extend the index when shifting and preserve the original data. + axis : {0 or 'index', 1 or 'columns', None}, default None + Shift direction. + + Returns + ------- + %(klass)s + Copy of input object, shifted. See Also -------- Index.shift : Shift values of Index. DatetimeIndex.shift : Shift values of DatetimeIndex. PeriodIndex.shift : Shift values of PeriodIndex. + tshift : Shift the time index, using the index's frequency if + available. - Notes - ----- - If freq is specified then the index values are shifted but the data - is not realigned. That is, use freq if you would like to extend the - index when shifting and preserve the original data. - - Returns - ------- - shifted : %(klass)s + Examples + -------- + >>> df = pd.DataFrame({'Col1': [10, 20, 15, 30, 45], + ... 'Col2': [13, 23, 18, 33, 48], + ... 'Col3': [17, 27, 22, 37, 52]}) + + >>> df.shift(periods=3) + Col1 Col2 Col3 + 0 NaN NaN NaN + 1 NaN NaN NaN + 2 NaN NaN NaN + 3 10.0 13.0 17.0 + 4 20.0 23.0 27.0 + + >>> df.shift(periods=1, axis='columns') + Col1 Col2 Col3 + 0 NaN 10.0 13.0 + 1 NaN 20.0 23.0 + 2 NaN 15.0 18.0 + 3 NaN 30.0 33.0 + 4 NaN 45.0 48.0 """) @Appender(_shared_docs['shift'] % _shared_doc_kwargs)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ####################### Docstring (pandas.Series.shift) ####################### ################################################################################ Shift index by desired number of periods with an optional time freq. When freq is not passed, shift the index without realign the data. If freq is passed (in this case, the index must be date or datetime), the index will be increased using the periods and the freq. Parameters ---------- periods : int Number of periods to move, can be positive or negative. freq : DateOffset, timedelta, or time rule string, optional Increment to use from the tseries module or time rule (e.g. 'EOM'). See Notes. axis : int or str Shift direction. {0, 'index'}. Notes ----- If freq is specified then the index values are shifted but the data is not realigned. That is, use freq if you would like to extend the index when shifting and preserve the original data. Returns ------- shifted : Series Examples -------- >>> df = pd.DataFrame({'Col1': [10, 20, 30, 20, 15, 30, 45], ... 'Col2': [13, 23, 33, 23, 18, 33, 48], ... 'Col3': [17, 27, 37, 27, 22, 37, 52]}) >>> print(df) Col1 Col2 Col3 0 10 13 17 1 20 23 27 2 30 33 37 3 20 23 27 4 15 18 22 5 30 33 37 6 45 48 52 >>> df.shift(periods=3) Col1 Col2 Col3 0 NaN NaN NaN 1 NaN NaN NaN 2 NaN NaN NaN 3 10.0 13.0 17.0 4 20.0 23.0 27.0 5 30.0 33.0 37.0 6 20.0 23.0 27.0 >>> df.shift(periods=1, axis=1) Col1 Col2 Col3 0 NaN 10.0 13.0 1 NaN 20.0 23.0 2 NaN 30.0 33.0 3 NaN 20.0 23.0 4 NaN 15.0 18.0 5 NaN 30.0 33.0 6 NaN 45.0 48.0 >>> import datetime >>> names = ['João', 'Maria', 'Emanuel', 'Jussara', 'José'] >>> dates = [datetime.datetime(2018, 3, 1, 11, 15), ... datetime.datetime(2018, 3, 5, 11, 15), ... datetime.datetime(2018, 3, 10, 11, 15), ... datetime.datetime(2018, 3, 15, 11, 15), ... datetime.datetime(2018, 3, 20, 11, 15)] >>> df = pd.DataFrame(data={'names': names}, index=dates) >>> print(df) names 2018-03-01 11:15:00 João 2018-03-05 11:15:00 Maria 2018-03-10 11:15:00 Emanuel 2018-03-15 11:15:00 Jussara 2018-03-20 11:15:00 José >>> df.shift(periods=2, freq='D') names 2018-03-03 11:15:00 João 2018-03-07 11:15:00 Maria 2018-03-12 11:15:00 Emanuel 2018-03-17 11:15:00 Jussara 2018-03-22 11:15:00 José >>> df.shift(periods=75, freq='min') names 2018-03-01 12:30:00 João 2018-03-05 12:30:00 Maria 2018-03-10 12:30:00 Emanuel 2018-03-15 12:30:00 Jussara 2018-03-20 12:30:00 José See Also -------- slice_shift: Equivalent to shift without copying data. tshift: Shift the time index, using the index’s frequency if available. ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Series.shift" correct. :) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/20472
2018-03-23T18:54:42Z
2018-11-04T15:24:10Z
2018-11-04T15:24:10Z
2018-11-04T15:24:23Z
DOC: Fix broken dependency links
diff --git a/doc/source/install.rst b/doc/source/install.rst index 7d741c6c2c75a..c96d4fbeb4ad2 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -212,7 +212,7 @@ Recommended Dependencies ``numexpr`` uses multiple cores as well as smart chunking and caching to achieve large speedups. If installed, must be Version 2.4.6 or higher. -* `bottleneck <http://berkeleyanalytics.com/bottleneck>`__: for accelerating certain types of ``nan`` +* `bottleneck <https://github.com/kwgoodman/bottleneck>`__: for accelerating certain types of ``nan`` evaluations. ``bottleneck`` uses specialized cython routines to achieve large speedups. If installed, must be Version 1.0.0 or higher. @@ -233,7 +233,7 @@ Optional Dependencies * `xarray <http://xarray.pydata.org>`__: pandas like handling for > 2 dims, needed for converting Panels to xarray objects. Version 0.7.0 or higher is recommended. * `PyTables <http://www.pytables.org>`__: necessary for HDF5-based storage. Version 3.0.0 or higher required, Version 3.2.1 or higher highly recommended. * `Feather Format <https://github.com/wesm/feather>`__: necessary for feather-based storage, version 0.3.1 or higher. -* `Apache Parquet <https://parquet.apache.org/>`__, either `pyarrow <http://arrow.apache.org/docs/python/>`__ (>= 0.4.1) or `fastparquet <https://fastparquet.readthedocs.io/en/latest/necessary>`__ (>= 0.0.6) for parquet-based storage. The `snappy <https://pypi.python.org/pypi/python-snappy>`__ and `brotli <https://pypi.python.org/pypi/brotlipy>`__ are available for compression support. +* `Apache Parquet <https://parquet.apache.org/>`__, either `pyarrow <http://arrow.apache.org/docs/python/>`__ (>= 0.4.1) or `fastparquet <https://fastparquet.readthedocs.io/en/latest>`__ (>= 0.0.6) for parquet-based storage. The `snappy <https://pypi.python.org/pypi/python-snappy>`__ and `brotli <https://pypi.python.org/pypi/brotlipy>`__ are available for compression support. * `SQLAlchemy <http://www.sqlalchemy.org>`__: for SQL database support. Version 0.8.1 or higher recommended. Besides SQLAlchemy, you also need a database specific driver. You can find an overview of supported drivers for each SQL dialect in the `SQLAlchemy docs <http://docs.sqlalchemy.org/en/latest/dialects/index.html>`__. Some common drivers are: * `psycopg2 <http://initd.org/psycopg/>`__: for PostgreSQL
- Change bottleneck link to github repository page. - Fix link to fastparquet documentation.
https://api.github.com/repos/pandas-dev/pandas/pulls/20471
2018-03-23T13:39:39Z
2018-03-25T14:32:14Z
2018-03-25T14:32:14Z
2018-03-25T14:32:16Z
TST: Fixed version comparison
diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index aec561ece8573..8083a1ce69092 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -1,15 +1,14 @@ import operator -import sys import pytest +from pandas.compat import PY2, PY36 from pandas.tests.extension import base from .array import JSONArray, JSONDtype, make_data -pytestmark = pytest.mark.skipif(sys.version_info[0] == 2, - reason="Py2 doesn't have a UserDict") +pytestmark = pytest.mark.skipif(PY2, reason="Py2 doesn't have a UserDict") @pytest.fixture @@ -81,7 +80,7 @@ def test_fillna_frame(self): class TestMethods(base.BaseMethodsTests): unhashable = pytest.mark.skip(reason="Unhashable") - unstable = pytest.mark.skipif(sys.version_info <= (3, 5), + unstable = pytest.mark.skipif(not PY36, # 3.6 or higher reason="Dictionary order unstable") @unhashable
This failed to skip for 3.5.x because the micro component made it False. closes https://github.com/pandas-dev/pandas/issues/20468
https://api.github.com/repos/pandas-dev/pandas/pulls/20469
2018-03-23T11:11:38Z
2018-03-24T01:14:11Z
2018-03-24T01:14:11Z
2018-03-24T01:14:14Z
TST: clean deprecation warnings & some parametrizing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8ff2b6c85eeed..9b09c87689762 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2153,7 +2153,7 @@ def _verbose_repr(): lines.append(_put_str(col, space) + tmpl % (count, dtype)) def _non_verbose_repr(): - lines.append(self.columns.summary(name='Columns')) + lines.append(self.columns._summary(name='Columns')) def _sizeof_fmt(num, size_qualifier): # returns size in human readable format diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index 9f7b06ed2d61c..c4c02c0bf6f17 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -647,83 +647,83 @@ def test_value_counts_bins(self): assert s.nunique() == 0 - def test_value_counts_datetime64(self): - klasses = [Index, Series] - for klass in klasses: - # GH 3002, datetime64[ns] - # don't test names though - txt = "\n".join(['xxyyzz20100101PIE', 'xxyyzz20100101GUM', - 'xxyyzz20100101EGG', 'xxyyww20090101EGG', - 'foofoo20080909PIE', 'foofoo20080909GUM']) - f = StringIO(txt) - df = pd.read_fwf(f, widths=[6, 8, 3], - names=["person_id", "dt", "food"], - parse_dates=["dt"]) - - s = klass(df['dt'].copy()) - s.name = None - - idx = pd.to_datetime(['2010-01-01 00:00:00Z', - '2008-09-09 00:00:00Z', - '2009-01-01 00:00:00X']) - expected_s = Series([3, 2, 1], index=idx) - tm.assert_series_equal(s.value_counts(), expected_s) - - expected = np_array_datetime64_compat(['2010-01-01 00:00:00Z', - '2009-01-01 00:00:00Z', - '2008-09-09 00:00:00Z'], - dtype='datetime64[ns]') - if isinstance(s, Index): - tm.assert_index_equal(s.unique(), DatetimeIndex(expected)) - else: - tm.assert_numpy_array_equal(s.unique(), expected) - - assert s.nunique() == 3 - - # with NaT - s = df['dt'].copy() - s = klass([v for v in s.values] + [pd.NaT]) - - result = s.value_counts() - assert result.index.dtype == 'datetime64[ns]' - tm.assert_series_equal(result, expected_s) - - result = s.value_counts(dropna=False) - expected_s[pd.NaT] = 1 - tm.assert_series_equal(result, expected_s) - - unique = s.unique() - assert unique.dtype == 'datetime64[ns]' - - # numpy_array_equal cannot compare pd.NaT - if isinstance(s, Index): - exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT]) - tm.assert_index_equal(unique, exp_idx) - else: - tm.assert_numpy_array_equal(unique[:3], expected) - assert pd.isna(unique[3]) - - assert s.nunique() == 3 - assert s.nunique(dropna=False) == 4 - - # timedelta64[ns] - td = df.dt - df.dt + timedelta(1) - td = klass(td, name='dt') - - result = td.value_counts() - expected_s = Series([6], index=[Timedelta('1day')], name='dt') - tm.assert_series_equal(result, expected_s) - - expected = TimedeltaIndex(['1 days'], name='dt') - if isinstance(td, Index): - tm.assert_index_equal(td.unique(), expected) - else: - tm.assert_numpy_array_equal(td.unique(), expected.values) - - td2 = timedelta(1) + (df.dt - df.dt) - td2 = klass(td2, name='dt') - result2 = td2.value_counts() - tm.assert_series_equal(result2, expected_s) + @pytest.mark.parametrize('klass', [Index, Series]) + def test_value_counts_datetime64(self, klass): + + # GH 3002, datetime64[ns] + # don't test names though + txt = "\n".join(['xxyyzz20100101PIE', 'xxyyzz20100101GUM', + 'xxyyzz20100101EGG', 'xxyyww20090101EGG', + 'foofoo20080909PIE', 'foofoo20080909GUM']) + f = StringIO(txt) + df = pd.read_fwf(f, widths=[6, 8, 3], + names=["person_id", "dt", "food"], + parse_dates=["dt"]) + + s = klass(df['dt'].copy()) + s.name = None + + idx = pd.to_datetime(['2010-01-01 00:00:00Z', + '2008-09-09 00:00:00Z', + '2009-01-01 00:00:00Z']) + expected_s = Series([3, 2, 1], index=idx) + tm.assert_series_equal(s.value_counts(), expected_s) + + expected = np_array_datetime64_compat(['2010-01-01 00:00:00Z', + '2009-01-01 00:00:00Z', + '2008-09-09 00:00:00Z'], + dtype='datetime64[ns]') + if isinstance(s, Index): + tm.assert_index_equal(s.unique(), DatetimeIndex(expected)) + else: + tm.assert_numpy_array_equal(s.unique(), expected) + + assert s.nunique() == 3 + + # with NaT + s = df['dt'].copy() + s = klass([v for v in s.values] + [pd.NaT]) + + result = s.value_counts() + assert result.index.dtype == 'datetime64[ns]' + tm.assert_series_equal(result, expected_s) + + result = s.value_counts(dropna=False) + expected_s[pd.NaT] = 1 + tm.assert_series_equal(result, expected_s) + + unique = s.unique() + assert unique.dtype == 'datetime64[ns]' + + # numpy_array_equal cannot compare pd.NaT + if isinstance(s, Index): + exp_idx = DatetimeIndex(expected.tolist() + [pd.NaT]) + tm.assert_index_equal(unique, exp_idx) + else: + tm.assert_numpy_array_equal(unique[:3], expected) + assert pd.isna(unique[3]) + + assert s.nunique() == 3 + assert s.nunique(dropna=False) == 4 + + # timedelta64[ns] + td = df.dt - df.dt + timedelta(1) + td = klass(td, name='dt') + + result = td.value_counts() + expected_s = Series([6], index=[Timedelta('1day')], name='dt') + tm.assert_series_equal(result, expected_s) + + expected = TimedeltaIndex(['1 days'], name='dt') + if isinstance(td, Index): + tm.assert_index_equal(td.unique(), expected) + else: + tm.assert_numpy_array_equal(td.unique(), expected.values) + + td2 = timedelta(1) + (df.dt - df.dt) + td2 = klass(td2, name='dt') + result2 = td2.value_counts() + tm.assert_series_equal(result2, expected_s) def test_factorize(self): for orig in self.objs:
https://api.github.com/repos/pandas-dev/pandas/pulls/20467
2018-03-23T10:18:52Z
2018-03-23T14:48:19Z
2018-03-23T14:48:19Z
2018-03-23T14:48:57Z
DOC: update the Series.str.join docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index b98fa106336fc..6796c14a18eaa 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -941,17 +941,59 @@ def str_get_dummies(arr, sep='|'): def str_join(arr, sep): """ - Join lists contained as elements in the Series/Index with - passed delimiter. Equivalent to :meth:`str.join`. + Join lists contained as elements in the Series/Index with passed delimiter. + + If the elements of a Series are lists themselves, join the content of these + lists using the delimiter passed to the function. + This function is an equivalent to :meth:`str.join`. Parameters ---------- - sep : string - Delimiter + sep : str + Delimiter to use between list entries. Returns ------- - joined : Series/Index of objects + Series/Index: object + + Notes + ----- + If any of the lists does not contain string objects the result of the join + will be `NaN`. + + See Also + -------- + str.join : Standard library version of this method. + Series.str.split : Split strings around given separator/delimiter. + + Examples + -------- + + Example with a list that contains non-string elements. + + >>> s = pd.Series([['lion', 'elephant', 'zebra'], + ... [1.1, 2.2, 3.3], + ... ['cat', np.nan, 'dog'], + ... ['cow', 4.5, 'goat'] + ... ['duck', ['swan', 'fish'], 'guppy']]) + >>> s + 0 [lion, elephant, zebra] + 1 [1.1, 2.2, 3.3] + 2 [cat, nan, dog] + 3 [cow, 4.5, goat] + 4 [duck, [swan, fish], guppy] + dtype: object + + Join all lists using an '-', the lists containing object(s) of types other + than str will become a NaN. + + >>> s.str.join('-') + 0 lion-elephant-zebra + 1 NaN + 2 NaN + 3 NaN + 4 NaN + dtype: object """ return _na_map(sep.join, arr)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ###################### Docstring (pandas.Series.str.join) ###################### ################################################################################ Join lists contained as elements in the Series/Index with passed delimiter. If the elements of a Series are lists themselves, join the content of these lists using the delimiter passed to the function. This function is an equivalent to :meth:`str.join`. Parameters ---------- sep : str Delimiter to use between list entries. Returns ------- Series/Index of objects Notes ----- If any of the lists does not contain string objects the result of the join will be `NaN`. See Also -------- str.join : Standard library version of this method. Series.str.split : Split strings around given separator/delimiter. Examples -------- Example with a list that contains non-string elements. >>> s = pd.Series([['lion', 'elephant', 'zebra'], ... [1.1, 2.2, 3.3], ... ["cat", np.nan, "dog"], ... ["cow", 4.5, "goat"]]) >>> s 0 [lion, elephant, zebra] 1 [1.1, 2.2, 3.3] 2 [cat, nan, dog] 3 [cow, 4.5, goat] dtype: object Join all lists using an '-', the list of floats will become a NaN. >>> s.str.join('-') 0 lion-elephant-zebra 1 NaN 2 NaN 3 NaN dtype: object ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Series.str.join" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20463
2018-03-22T21:57:36Z
2018-03-27T12:10:37Z
2018-03-27T12:10:37Z
2018-03-27T12:10:49Z
DOC: Improving the docstring of Series.str.upper and related
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index b98fa106336fc..09eed94b36c6b 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2145,11 +2145,68 @@ def rindex(self, sub, start=0, end=None): _shared_docs['casemethods'] = (""" Convert strings in the Series/Index to %(type)s. + Equivalent to :meth:`str.%(method)s`. Returns ------- - converted : Series/Index of objects + Series/Index of objects + + See Also + -------- + Series.str.lower : Converts all characters to lowercase. + Series.str.upper : Converts all characters to uppercase. + Series.str.title : Converts first character of each word to uppercase and + remaining to lowercase. + Series.str.capitalize : Converts first character to uppercase and + remaining to lowercase. + Series.str.swapcase : Converts uppercase to lowercase and lowercase to + uppercase. + + Examples + -------- + >>> s = pd.Series(['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe']) + >>> s + 0 lower + 1 CAPITALS + 2 this is a sentence + 3 SwApCaSe + dtype: object + + >>> s.str.lower() + 0 lower + 1 capitals + 2 this is a sentence + 3 swapcase + dtype: object + + >>> s.str.upper() + 0 LOWER + 1 CAPITALS + 2 THIS IS A SENTENCE + 3 SWAPCASE + dtype: object + + >>> s.str.title() + 0 Lower + 1 Capitals + 2 This Is A Sentence + 3 Swapcase + dtype: object + + >>> s.str.capitalize() + 0 Lower + 1 Capitals + 2 This is a sentence + 3 Swapcase + dtype: object + + >>> s.str.swapcase() + 0 LOWER + 1 capitals + 2 THIS IS A SENTENCE + 3 sWaPcAsE + dtype: object """) _shared_docs['lower'] = dict(type='lowercase', method='lower') _shared_docs['upper'] = dict(type='uppercase', method='upper')
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ##################### Docstring (pandas.Series.str.upper) ##################### ################################################################################ Convert strings in the Series/Index to uppercase. Equivalent to :meth:`str.upper`. Returns ------- Series/Index of objects See Also -------- Series.str.lower : Converts all characters to lower case. Series.str.upper : Converts all characters to upper case. Series.str.title : Converts first character of each word to upper case and remaining to lower case. Series.str.capitalize : Converts first character to upper case and remaining to lower case. Series.str.swapcase : Converts upper case to lower case and lower case to upper case. Examples -------- >>> s = pd.Series(['lower', 'CAPITALS', 'this is a sentence', 'SwApCaSe']) >>> s.str.lower() 0 lower 1 capitals 2 this is a sentence 3 swapcase dtype: object >>> s.str.upper() 0 LOWER 1 CAPITALS 2 THIS IS A SENTENCE 3 SWAPCASE dtype: object >>> s.str.title() 0 Lower 1 Capitals 2 This Is A Sentence 3 Swapcase dtype: object >>> s.str.capitalize() 0 Lower 1 Capitals 2 This is a sentence 3 Swapcase dtype: object >>> s.str.swapcase() 0 LOWER 1 capitals 2 THIS IS A SENTENCE 3 sWaPcAsE dtype: object ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Series.str.upper" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20462
2018-03-22T21:53:54Z
2018-03-28T16:22:12Z
2018-03-28T16:22:12Z
2018-03-28T16:22:13Z
CLN: Replacing %s with .format in pandas/core/frame.py
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f476bff4df2cd..a71ade3da87de 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -411,7 +411,7 @@ def __init__(self, data=None, index=None, columns=None, dtype=None, arr = np.array(data, dtype=dtype, copy=copy) except (ValueError, TypeError) as e: exc = TypeError('DataFrame constructor called with ' - 'incompatible data and dtype: %s' % e) + 'incompatible data and dtype: {e}'.format(e=e)) raise_with_traceback(exc) if arr.ndim == 0 and index is not None and columns is not None: @@ -520,8 +520,9 @@ def _get_axes(N, K, index=index, columns=columns): try: values = values.astype(dtype) except Exception as orig: - e = ValueError("failed to cast to '%s' (Exception was: %s)" - % (dtype, orig)) + e = ValueError("failed to cast to '{dtype}' (Exception " + "was: {orig})".format(dtype=dtype, + orig=orig)) raise_with_traceback(e) index, columns = _get_axes(*values.shape) @@ -873,8 +874,9 @@ def dot(self, other): lvals = self.values rvals = np.asarray(other) if lvals.shape[1] != rvals.shape[0]: - raise ValueError('Dot product shape mismatch, %s vs %s' % - (lvals.shape, rvals.shape)) + raise ValueError('Dot product shape mismatch, ' + '{l} vs {r}'.format(l=lvals.shape, + r=rvals.shape)) if isinstance(other, DataFrame): return self._constructor(np.dot(lvals, rvals), index=left.index, @@ -888,7 +890,7 @@ def dot(self, other): else: return Series(result, index=left.index) else: # pragma: no cover - raise TypeError('unsupported type: %s' % type(other)) + raise TypeError('unsupported type: {oth}'.format(oth=type(other))) def __matmul__(self, other): """ Matrix multiplication using binary `@` operator in Python>=3.5 """ @@ -1098,7 +1100,7 @@ def to_dict(self, orient='dict', into=dict): return into_c((t[0], dict(zip(self.columns, t[1:]))) for t in self.itertuples()) else: - raise ValueError("orient '%s' not understood" % orient) + raise ValueError("orient '{o}' not understood".format(o=orient)) def to_gbq(self, destination_table, project_id, chunksize=None, verbose=None, reauth=False, if_exists='fail', private_key=None, @@ -2140,7 +2142,7 @@ def info(self, verbose=None, buf=None, max_cols=None, memory_usage=None, lines.append(self.index._summary()) if len(self.columns) == 0: - lines.append('Empty %s' % type(self).__name__) + lines.append('Empty {name}'.format(name=type(self).__name__)) fmt.buffer_put_lines(buf, lines) return @@ -2166,13 +2168,15 @@ def _verbose_repr(): space = max(len(pprint_thing(k)) for k in self.columns) + 4 counts = None - tmpl = "%s%s" + tmpl = "{count}{dtype}" if show_counts: counts = self.count() if len(cols) != len(counts): # pragma: no cover - raise AssertionError('Columns must equal counts (%d != %d)' - % (len(cols), len(counts))) - tmpl = "%s non-null %s" + raise AssertionError( + 'Columns must equal counts ' + '({cols:d} != {counts:d})'.format( + cols=len(cols), counts=len(counts))) + tmpl = "{count} non-null {dtype}" dtypes = self.dtypes for i, col in enumerate(self.columns): @@ -2183,7 +2187,8 @@ def _verbose_repr(): if show_counts: count = counts.iloc[i] - lines.append(_put_str(col, space) + tmpl % (count, dtype)) + lines.append(_put_str(col, space) + tmpl.format(count=count, + dtype=dtype)) def _non_verbose_repr(): lines.append(self.columns._summary(name='Columns')) @@ -2192,9 +2197,12 @@ def _sizeof_fmt(num, size_qualifier): # returns size in human readable format for x in ['bytes', 'KB', 'MB', 'GB', 'TB']: if num < 1024.0: - return "%3.1f%s %s" % (num, size_qualifier, x) + return ("{num:3.1f}{size_q}" + "{x}".format(num=num, size_q=size_qualifier, x=x)) num /= 1024.0 - return "%3.1f%s %s" % (num, size_qualifier, 'PB') + return "{num:3.1f}{size_q} {pb}".format(num=num, + size_q=size_qualifier, + pb='PB') if verbose: _verbose_repr() @@ -2207,8 +2215,9 @@ def _sizeof_fmt(num, size_qualifier): _verbose_repr() counts = self.get_dtype_counts() - dtypes = ['%s(%d)' % k for k in sorted(compat.iteritems(counts))] - lines.append('dtypes: %s' % ', '.join(dtypes)) + dtypes = ['{k}({kk:d})'.format(k=k[0], kk=k[1]) for k + in sorted(compat.iteritems(counts))] + lines.append('dtypes: {types}'.format(types=', '.join(dtypes))) if memory_usage is None: memory_usage = get_option('display.memory_usage') @@ -2226,8 +2235,9 @@ def _sizeof_fmt(num, size_qualifier): self.index._is_memory_usage_qualified()): size_qualifier = '+' mem_usage = self.memory_usage(index=True, deep=deep).sum() - lines.append("memory usage: %s\n" % - _sizeof_fmt(mem_usage, size_qualifier)) + lines.append("memory usage: {mem}\n".format( + mem=_sizeof_fmt(mem_usage, size_qualifier))) + fmt.buffer_put_lines(buf, lines) def memory_usage(self, index=True, deep=False): @@ -3013,8 +3023,8 @@ def select_dtypes(self, include=None, exclude=None): # can't both include AND exclude! if not include.isdisjoint(exclude): - raise ValueError('include and exclude overlap on %s' % - (include & exclude)) + raise ValueError('include and exclude overlap on {inc_ex}'.format( + inc_ex=(include & exclude))) # empty include/exclude -> defaults to True # three cases (we've already raised if both are empty) @@ -3869,7 +3879,8 @@ def set_index(self, keys, drop=True, append=False, inplace=False, if verify_integrity and not index.is_unique: duplicates = index.get_duplicates() - raise ValueError('Index has duplicate keys: %s' % duplicates) + raise ValueError('Index has duplicate keys: {dup}'.format( + dup=duplicates)) for c in to_remove: del frame[c] @@ -4241,7 +4252,7 @@ def dropna(self, axis=0, how='any', thresh=None, subset=None, mask = count > 0 else: if how is not None: - raise ValueError('invalid how option: %s' % how) + raise ValueError('invalid how option: {h}'.format(h=how)) else: raise TypeError('must specify how or thresh') @@ -6750,8 +6761,8 @@ def _count_level(self, level, axis=0, numeric_only=False): agg_axis = frame._get_agg_axis(axis) if not isinstance(count_axis, MultiIndex): - raise TypeError("Can only count levels on hierarchical %s." % - self._get_axis_name(axis)) + raise TypeError("Can only count levels on hierarchical " + "{ax}.".format(ax=self._get_axis_name(axis))) if frame._is_mixed_type: # Since we have mixed types, calling notna(frame.values) might @@ -6829,9 +6840,9 @@ def f(x): elif filter_type == 'bool': data = self._get_bool_data() else: # pragma: no cover - e = NotImplementedError("Handling exception with filter_" - "type %s not implemented." % - filter_type) + e = NotImplementedError( + "Handling exception with filter_type {f} not" + "implemented.".format(f=filter_type)) raise_with_traceback(e) with np.errstate(all='ignore'): result = f(data.values) @@ -6843,8 +6854,8 @@ def f(x): elif filter_type == 'bool': data = self._get_bool_data() else: # pragma: no cover - msg = ("Generating numeric_only data with filter_type %s" - "not supported." % filter_type) + msg = ("Generating numeric_only data with filter_type {f}" + "not supported.".format(f=filter_type)) raise NotImplementedError(msg) values = data.values labels = data._get_agg_axis(axis) @@ -7119,7 +7130,8 @@ def to_timestamp(self, freq=None, how='start', axis=0, copy=True): elif axis == 1: new_data.set_axis(0, self.columns.to_timestamp(freq=freq, how=how)) else: # pragma: no cover - raise AssertionError('Axis must be 0 or 1. Got %s' % str(axis)) + raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format( + ax=axis)) return self._constructor(new_data) @@ -7150,7 +7162,8 @@ def to_period(self, freq=None, axis=0, copy=True): elif axis == 1: new_data.set_axis(0, self.columns.to_period(freq=freq)) else: # pragma: no cover - raise AssertionError('Axis must be 0 or 1. Got %s' % str(axis)) + raise AssertionError('Axis must be 0 or 1. Got {ax!s}'.format( + ax=axis)) return self._constructor(new_data) @@ -7509,8 +7522,9 @@ def _convert_object_array(content, columns, coerce_float=False, dtype=None): else: if len(columns) != len(content): # pragma: no cover # caller's responsibility to check for this... - raise AssertionError('%d columns passed, passed data had %s ' - 'columns' % (len(columns), len(content))) + raise AssertionError('{col:d} columns passed, passed data had ' + '{con} columns'.format(col=len(columns), + con=len(content))) # provide soft conversion of object dtypes def convert(arr): @@ -7585,4 +7599,4 @@ def _from_nested_dict(data): def _put_str(s, space): - return ('%s' % s)[:space].ljust(space) + return u'{s}'.format(s=s)[:space].ljust(space)
- [x] Progress towards #16130 - [x] tests added / passed - [x] passes git diff upstream/master -u -- "*.py" | flake8 --diff
https://api.github.com/repos/pandas-dev/pandas/pulls/20461
2018-03-22T21:49:32Z
2018-04-17T10:31:43Z
2018-04-17T10:31:43Z
2018-04-17T10:48:55Z
DOC: update the isna, isnull, notna and notnull docstring
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 01c88c269e7e0..2c8d229f9b0cb 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -29,23 +29,78 @@ def isna(obj): - """Detect missing values (NaN in numeric arrays, None/NaN in object arrays) + """ + Detect missing values for an array-like object. + + This function takes a scalar or array-like object and indictates + whether values are missing (``NaN`` in numeric arrays, ``None`` or ``NaN`` + in object arrays, ``NaT`` in datetimelike). Parameters ---------- - arr : ndarray or object value - Object to check for null-ness + obj : scalar or array-like + Object to check for null or missing values. Returns ------- - isna : array-like of bool or bool - Array or bool indicating whether an object is null or if an array is - given which of the element is null. + bool or array-like of bool + For scalar input, returns a scalar boolean. + For array input, returns an array of boolean indicating whether each + corresponding element is missing. - See also + See Also + -------- + notna : boolean inverse of pandas.isna. + Series.isna : Detetct missing values in a Series. + DataFrame.isna : Detect missing values in a DataFrame. + Index.isna : Detect missing values in an Index. + + Examples -------- - pandas.notna: boolean inverse of pandas.isna - pandas.isnull: alias of isna + Scalar arguments (including strings) result in a scalar boolean. + + >>> pd.isna('dog') + False + + >>> pd.isna(np.nan) + True + + ndarrays result in an ndarray of booleans. + + >>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]]) + >>> array + array([[ 1., nan, 3.], + [ 4., 5., nan]]) + >>> pd.isna(array) + array([[False, True, False], + [False, False, True]]) + + For indexes, an ndarray of booleans is returned. + + >>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None, + ... "2017-07-08"]) + >>> index + DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'], + dtype='datetime64[ns]', freq=None) + >>> pd.isna(index) + array([False, False, True, False]) + + For Series and DataFrame, the same type is returned, containing booleans. + + >>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']]) + >>> df + 0 1 2 + 0 ant bee cat + 1 dog None fly + >>> pd.isna(df) + 0 1 2 + 0 False False False + 1 False True False + + >>> pd.isna(df[1]) + 0 False + 1 True + Name: 1, dtype: bool """ return _isna(obj) @@ -197,24 +252,78 @@ def _isna_ndarraylike_old(obj): def notna(obj): - """Replacement for numpy.isfinite / -numpy.isnan which is suitable for use - on object arrays. + """ + Detect non-missing values for an array-like object. + + This function takes a scalar or array-like object and indictates + whether values are valid (not missing, which is ``NaN`` in numeric + arrays, ``None`` or ``NaN`` in object arrays, ``NaT`` in datetimelike). Parameters ---------- - arr : ndarray or object value - Object to check for *not*-null-ness + obj : array-like or object value + Object to check for *not* null or *non*-missing values. Returns ------- - notisna : array-like of bool or bool - Array or bool indicating whether an object is *not* null or if an array - is given which of the element is *not* null. + bool or array-like of bool + For scalar input, returns a scalar boolean. + For array input, returns an array of boolean indicating whether each + corresponding element is valid. - See also + See Also + -------- + isna : boolean inverse of pandas.notna. + Series.notna : Detetct valid values in a Series. + DataFrame.notna : Detect valid values in a DataFrame. + Index.notna : Detect valid values in an Index. + + Examples -------- - pandas.isna : boolean inverse of pandas.notna - pandas.notnull : alias of notna + Scalar arguments (including strings) result in a scalar boolean. + + >>> pd.notna('dog') + True + + >>> pd.notna(np.nan) + False + + ndarrays result in an ndarray of booleans. + + >>> array = np.array([[1, np.nan, 3], [4, 5, np.nan]]) + >>> array + array([[ 1., nan, 3.], + [ 4., 5., nan]]) + >>> pd.notna(array) + array([[ True, False, True], + [ True, True, False]]) + + For indexes, an ndarray of booleans is returned. + + >>> index = pd.DatetimeIndex(["2017-07-05", "2017-07-06", None, + ... "2017-07-08"]) + >>> index + DatetimeIndex(['2017-07-05', '2017-07-06', 'NaT', '2017-07-08'], + dtype='datetime64[ns]', freq=None) + >>> pd.notna(index) + array([ True, True, False, True]) + + For Series and DataFrame, the same type is returned, containing booleans. + + >>> df = pd.DataFrame([['ant', 'bee', 'cat'], ['dog', None, 'fly']]) + >>> df + 0 1 2 + 0 ant bee cat + 1 dog None fly + >>> pd.notna(df) + 0 1 2 + 0 True True True + 1 True False True + + >>> pd.notna(df[1]) + 0 True + 1 False + Name: 1, dtype: bool """ res = isna(obj) if is_scalar(res):
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [ ] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` The validation script did not work on this docstring ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. The validation script did not work on this docstring
https://api.github.com/repos/pandas-dev/pandas/pulls/20459
2018-03-22T21:27:35Z
2018-03-26T20:12:21Z
2018-03-26T20:12:21Z
2018-03-26T20:12:24Z
DOC: update the pandas.Series.str.startswith docstring
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index b98fa106336fc..d6a67435aeb09 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -328,19 +328,54 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): def str_startswith(arr, pat, na=np.nan): """ - Return boolean Series/``array`` indicating whether each string in the - Series/Index starts with passed pattern. Equivalent to - :meth:`str.startswith`. + Test if the start of each string element matches a pattern. + + Equivalent to :meth:`str.startswith`. Parameters ---------- - pat : string - Character sequence - na : bool, default NaN + pat : str + Character sequence. Regular expressions are not accepted. + na : object, default NaN + Object shown if element tested is not a string. Returns ------- - startswith : Series/array of boolean values + Series or Index of bool + A Series of booleans indicating whether the given pattern matches + the start of each string element. + + See Also + -------- + str.startswith : Python standard library string method. + Series.str.endswith : Same as startswith, but tests the end of string. + Series.str.contains : Tests if string element contains a pattern. + + Examples + -------- + >>> s = pd.Series(['bat', 'Bear', 'cat', np.nan]) + >>> s + 0 bat + 1 Bear + 2 cat + 3 NaN + dtype: object + + >>> s.str.startswith('b') + 0 True + 1 False + 2 False + 3 NaN + dtype: object + + Specifying `na` to be `False` instead of `NaN`. + + >>> s.str.startswith('b', na=False) + 0 True + 1 False + 2 False + 3 False + dtype: bool """ f = lambda x: x.startswith(pat) return _na_map(f, arr, na, dtype=bool)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [X] PR title is "DOC: update the <your-function-or-method> docstring" - [X] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [X] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [X] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ################### Docstring (pandas.Series.str.startswith) ################### ################################################################################ Test if the start of each string element matches a pattern. Return a Series of booleans indicating whether the given pattern matches the start of each string element. Equivalent to :meth: `str.startswith`. Parameters ---------- pat : string Character sequence. na : object, default NaN Character sequence shown if element tested is not a string. Returns ------- startswith : Series/array of boolean values Examples -------- >>> s = pd.Series(['bat', 'bear', 'cat']) >>> s.str.startswith('b') 0 True 1 True 2 False dtype: bool >>> s = pd.Series(['bat', 'bear', 'cat', np.nan]) >>> s.str.startswith('b', na='not_a_string') 0 True 1 True 2 False 3 not_a_string dtype: object See Also -------- endswith : same as startswith, but tests the end of string ################################################################################ ################################## Validation ################################## ################################################################################ ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly.
https://api.github.com/repos/pandas-dev/pandas/pulls/20458
2018-03-22T21:21:21Z
2018-03-25T22:49:17Z
2018-03-25T22:49:17Z
2018-03-26T06:26:16Z
CLN: Removed dead GroupBy code
diff --git a/pandas/core/groupby.py b/pandas/core/groupby.py index 4352a001aa989..7b68ad67675ff 100644 --- a/pandas/core/groupby.py +++ b/pandas/core/groupby.py @@ -944,23 +944,6 @@ def _cumcount_array(self, ascending=True): rev[sorter] = np.arange(count, dtype=np.intp) return out[rev].astype(np.int64, copy=False) - def _index_with_as_index(self, b): - """ - Take boolean mask of index to be returned from apply, if as_index=True - - """ - # TODO perf, it feels like this should already be somewhere... - from itertools import chain - original = self._selected_obj.index - gp = self.grouper - levels = chain((gp.levels[i][gp.labels[i][b]] - for i in range(len(gp.groupings))), - (original._get_level_values(i)[b] - for i in range(original.nlevels))) - new = MultiIndex.from_arrays(list(levels)) - new.names = gp.names + original.names - return new - def _try_cast(self, result, obj, numeric_only=False): """ try to cast the result to our obj original type, @@ -2295,18 +2278,6 @@ def size(self): index=self.result_index, dtype='int64') - @cache_readonly - def _max_groupsize(self): - """ - Compute size of largest group - """ - # For many items in each group this is much faster than - # self.size().max(), in worst case marginally slower - if self.indices: - return max(len(v) for v in self.indices.values()) - else: - return 0 - @cache_readonly def groups(self): """ dict {group name -> group labels} """ @@ -2941,9 +2912,6 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None, if isinstance(grouper, MultiIndex): self.grouper = grouper.values - # pre-computed - self._should_compress = True - # we have a single grouper which may be a myriad of things, # some of which are dependent on the passing in level @@ -4964,10 +4932,6 @@ def _wrap_aggregated_output(self, output, names=None): raise com.AbstractMethodError(self) -class NDArrayGroupBy(GroupBy): - pass - - # ---------------------------------------------------------------------- # Splitting / application @@ -5020,10 +4984,6 @@ def apply(self, f): raise com.AbstractMethodError(self) -class ArraySplitter(DataSplitter): - pass - - class SeriesSplitter(DataSplitter): def _chop(self, sdata, slice_obj):
- [X] closes #20456 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20457
2018-03-22T18:45:18Z
2018-03-22T22:48:48Z
2018-03-22T22:48:47Z
2018-12-25T06:12:49Z
DOC: update the pandas.Series.map docstring
diff --git a/pandas/core/series.py b/pandas/core/series.py index df0fa1c6c0659..2e6270e8739ae 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2951,74 +2951,25 @@ def unstack(self, level=-1, fill_value=None): def map(self, arg, na_action=None): """ - Map values of Series using input correspondence (a dict, Series, or - function). + Map values of Series according to input correspondence. + + Used for substituting each value in a Series with another value, + that may be derived from a function, a ``dict`` or + a :class:`Series`. Parameters ---------- arg : function, dict, or Series Mapping correspondence. - na_action : {None, 'ignore'} - If 'ignore', propagate NA values, without passing them to the + na_action : {None, 'ignore'}, default None + If 'ignore', propagate NaN values, without passing them to the mapping correspondence. Returns ------- - y : Series + Series Same index as caller. - Examples - -------- - - Map inputs to outputs (both of type `Series`): - - >>> x = pd.Series([1,2,3], index=['one', 'two', 'three']) - >>> x - one 1 - two 2 - three 3 - dtype: int64 - - >>> y = pd.Series(['foo', 'bar', 'baz'], index=[1,2,3]) - >>> y - 1 foo - 2 bar - 3 baz - - >>> x.map(y) - one foo - two bar - three baz - - If `arg` is a dictionary, return a new Series with values converted - according to the dictionary's mapping: - - >>> z = {1: 'A', 2: 'B', 3: 'C'} - - >>> x.map(z) - one A - two B - three C - - Use na_action to control whether NA values are affected by the mapping - function. - - >>> s = pd.Series([1, 2, 3, np.nan]) - - >>> s2 = s.map('this is a string {}'.format, na_action=None) - 0 this is a string 1.0 - 1 this is a string 2.0 - 2 this is a string 3.0 - 3 this is a string nan - dtype: object - - >>> s3 = s.map('this is a string {}'.format, na_action='ignore') - 0 this is a string 1.0 - 1 this is a string 2.0 - 2 this is a string 3.0 - 3 NaN - dtype: object - See Also -------- Series.apply : For applying more complex functions on a Series. @@ -3027,20 +2978,51 @@ def map(self, arg, na_action=None): Notes ----- - When `arg` is a dictionary, values in Series that are not in the + When ``arg`` is a dictionary, values in Series that are not in the dictionary (as keys) are converted to ``NaN``. However, if the dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e. provides a method for default values), then this default is used - rather than ``NaN``: - - >>> from collections import Counter - >>> counter = Counter() - >>> counter['bar'] += 1 - >>> y.map(counter) - 1 0 - 2 1 - 3 0 - dtype: int64 + rather than ``NaN``. + + Examples + -------- + >>> s = pd.Series(['cat', 'dog', np.nan, 'rabbit']) + >>> s + 0 cat + 1 dog + 2 NaN + 3 rabbit + dtype: object + + ``map`` accepts a ``dict`` or a ``Series``. Values that are not found + in the ``dict`` are converted to ``NaN``, unless the dict has a default + value (e.g. ``defaultdict``): + + >>> s.map({'cat': 'kitten', 'dog': 'puppy'}) + 0 kitten + 1 puppy + 2 NaN + 3 NaN + dtype: object + + It also accepts a function: + + >>> s.map('I am a {}'.format) + 0 I am a cat + 1 I am a dog + 2 I am a nan + 3 I am a rabbit + dtype: object + + To avoid applying the function to missing values (and keep them as + ``NaN``) ``na_action='ignore'`` can be used: + + >>> s.map('I am a {}'.format, na_action='ignore') + 0 I am a cat + 1 I am a dog + 2 NaN + 3 I am a rabbit + dtype: object """ new_values = super(Series, self)._map_values( arg, na_action=na_action)
Checklist for the pandas documentation sprint (ignore this if you are doing an unrelated PR): - [x] PR title is "DOC: update the <your-function-or-method> docstring" - [x] The validation script passes: `scripts/validate_docstrings.py <your-function-or-method>` - [x] The PEP8 style check passes: `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] The html version looks good: `python doc/make.py --single <your-function-or-method>` - [x] It has been proofread on language by another sprint participant Please include the output of the validation script below between the "```" ticks: ``` ################################################################################ ######################## Docstring (pandas.Series.map) ######################## ################################################################################ Map values of Series according to input correspondence. Used for substituting each value in a Series with another value, that may be derived from a function, a ``dict`` or a :class:`pandas.Series`. Parameters ---------- arg : function, dict, or Seriess Mapping correspondence. na_action : {None, 'ignore'} If 'ignore', propagate NA values, without passing them to the mapping correspondence. Returns ------- y : Series Same index as caller. Examples -------- Map inputs to outputs (both of type :class:`pandas.Series`): >>> x = pd.Series([1,2,3], index=['one', 'two', 'three']) >>> x one 1 two 2 three 3 dtype: int64 >>> y = pd.Series(['foo', 'bar', 'baz'], index=[1,2,3]) >>> y 1 foo 2 bar 3 baz dtype: object >>> x.map(y) one foo two bar three baz dtype: object Map a function to a :class:`pandas.Series`. >>> x.map(lambda x: x**2) one 1 two 4 three 9 dtype: int64 If ``arg`` is a dictionary, return a new :class:`pandas.Series` with values converted according to the dictionary's mapping: >>> z = {1: 'A', 2: 'B', 3: 'C'} >>> x.map(z) one A two B three C dtype: object Use ``na_action`` to control whether NA values are affected by the mapping function. >>> s = pd.Series([1, 2, 3, np.nan]) >>> s.map('this is a string {}'.format, na_action=None) 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 this is a string nan dtype: object >>> s.map('this is a string {}'.format, na_action='ignore') 0 this is a string 1.0 1 this is a string 2.0 2 this is a string 3.0 3 NaN dtype: object See Also -------- Series.apply : For applying more complex functions on a Series. DataFrame.apply : Apply a function row-/column-wise. DataFrame.applymap : Apply a function elementwise on a whole DataFrame. Notes ----- When `arg` is a dictionary, values in Series that are not in the dictionary (as keys) are converted to ``NaN``. However, if the dictionary is a ``dict`` subclass that defines ``__missing__`` (i.e. provides a method for default values), then this default is used rather than ``NaN``: >>> from collections import Counter >>> counter = Counter() >>> counter['bar'] += 1 >>> y.map(counter) 1 0 2 1 3 0 dtype: int64 ################################################################################ ################################## Validation ################################## ################################################################################ Docstring for "pandas.Series.map" correct. :) ``` If the validation script still gives errors, but you think there is a good reason to deviate in this case (and there are certainly such cases), please state this explicitly. Checklist for other PRs (remove this part if you are doing a PR for the pandas documentation sprint): - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20450
2018-03-22T12:40:32Z
2018-08-18T22:22:28Z
2018-08-18T22:22:28Z
2018-08-19T10:50:51Z
DOC: general docstring formatting fixes
diff --git a/pandas/core/base.py b/pandas/core/base.py index f686975366419..b3eb9a0ae7530 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -855,6 +855,7 @@ def min(self): 'a' For a MultiIndex, the minimum is determined lexicographically. + >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)]) >>> idx.min() ('a', 1) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 081a8b39a3849..cf41737a04ba6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5465,8 +5465,6 @@ def _gotitem(self, key, ndim, subset=None): return self[key] _agg_doc = dedent(""" - Notes - ----- The aggregation operations are always performed over an axis, either the index (default) or the column axis. This behavior is different from `numpy` aggregation functions (`mean`, `median`, `prod`, `sum`, `std`, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 74b760fa4e3c4..bd1a2371315a0 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1910,20 +1910,20 @@ def to_hdf(self, path_or_buf, key, **kwargs): Identifier for the group in the store. mode : {'a', 'w', 'r+'}, default 'a' Mode to open file: - + - 'w': write, a new file is created (an existing file with - the same name would be deleted). + the same name would be deleted). - 'a': append, an existing file is opened for reading and - writing, and if the file does not exist it is created. + writing, and if the file does not exist it is created. - 'r+': similar to 'a', but the file must already exist. format : {'fixed', 'table'}, default 'fixed' Possible values: - + - 'fixed': Fixed format. Fast writing/reading. Not-appendable, - nor searchable. + nor searchable. - 'table': Table format. Write as a PyTables Table structure - which may perform worse but allow more flexible operations - like searching / selecting subsets of the data. + which may perform worse but allow more flexible operations + like searching / selecting subsets of the data. append : bool, default False For Table formats, append the input data to the existing. data_columns : list of columns or True, optional @@ -5795,10 +5795,11 @@ def replace(self, to_replace=None, value=None, inplace=False, limit=None, * None: (default) no fill restriction * 'inside' Only fill NaNs surrounded by valid values (interpolate). * 'outside' Only fill NaNs outside valid values (extrapolate). - .. versionadded:: 0.21.0 If limit is specified, consecutive NaNs will be filled in this direction. + + .. versionadded:: 0.21.0 inplace : bool, default False Update the NDFrame in place if possible. downcast : optional, 'infer' or None, defaults to None @@ -7717,6 +7718,7 @@ def truncate(self, before=None, after=None, axis=None, copy=True): The index values in ``truncate`` can be datetimes or string dates. + >>> dates = pd.date_range('2016-01-01', '2016-02-01', freq='s') >>> df = pd.DataFrame(index=dates, data={'A': 1}) >>> df.tail() @@ -7960,7 +7962,7 @@ def abs(self): 0 1 days dtype: timedelta64[ns] - Select rows with data closest to certian value using argsort (from + Select rows with data closest to certain value using argsort (from `StackOverflow <https://stackoverflow.com/a/17758115>`__). >>> df = pd.DataFrame({ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 95bfc8bfcb5c5..40f543e211f0c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1,6 +1,7 @@ from datetime import datetime, timedelta import warnings import operator +from textwrap import dedent import numpy as np from pandas._libs import (lib, index as libindex, tslib as libts, @@ -2183,7 +2184,7 @@ def isna(self): mapped to ``True`` values. Everything else get mapped to ``False`` values. Characters such as empty strings `''` or :attr:`numpy.inf` are not considered NA values - (unless you set :attr:`pandas.options.mode.use_inf_as_na` `= True`). + (unless you set ``pandas.options.mode.use_inf_as_na = True``). .. versionadded:: 0.20.0 @@ -4700,7 +4701,7 @@ def _add_logical_methods(cls): %(outname)s : bool or array_like (if axis is specified) A single element array_like may be converted to bool.""" - _index_shared_docs['index_all'] = """ + _index_shared_docs['index_all'] = dedent(""" See Also -------- @@ -4738,9 +4739,9 @@ def _add_logical_methods(cls): >>> pd.Index([0, 0, 0]).any() False - """ + """) - _index_shared_docs['index_any'] = """ + _index_shared_docs['index_any'] = dedent(""" See Also -------- @@ -4761,7 +4762,7 @@ def _add_logical_methods(cls): >>> index = pd.Index([0, 0, 0]) >>> index.any() False - """ + """) def _make_logical_function(name, desc, f): @Substitution(outname=name, desc=desc) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index e9011a3eb912c..b906ea0f4784c 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -86,16 +86,12 @@ def strftime(self, date_format): Examples -------- - >>> import datetime - >>> data = pd.date_range(datetime.datetime(2018,3,10,19,27,52), - ... periods=4, freq='B') - >>> df = pd.DataFrame(data, columns=['date']) - >>> df.date[1] - Timestamp('2018-03-13 19:27:52') - >>> df.date[1].strftime('%d-%m-%Y') - '13-03-2018' - >>> df.date[1].strftime('%B %d, %Y, %r') - 'March 13, 2018, 07:27:52 PM' + >>> rng = pd.date_range(pd.Timestamp("2018-03-10 09:00"), + ... periods=3, freq='s') + >>> rng.strftime('%B %d, %Y, %r') + Index(['March 10, 2018, 09:00:00 AM', 'March 10, 2018, 09:00:01 AM', + 'March 10, 2018, 09:00:02 AM'], + dtype='object') """.format("https://docs.python.org/3/library/datetime.html" "#strftime-and-strptime-behavior") diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index be28f7091712f..118198ea0320d 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -51,7 +51,7 @@ def cut(x, bins, right=True, labels=None, retbins=False, precision=3, right : bool, default True Indicates whether `bins` includes the rightmost edge or not. If ``right == True`` (the default), then the `bins` ``[1, 2, 3, 4]`` - indicate (1,2], (2,3], (3,4]. This argument is ignored when + indicate (1,2], (2,3], (3,4]. This argument is ignored when `bins` is an IntervalIndex. labels : array or bool, optional Specifies the labels for the returned bins. Must be the same length as
Some general formatting fixes (+ fix example in DatetimeIndex.strftime to actually use that method and not Timestamp.strftime). Merging directly as it contains some PEP8 issues I merged in master.
https://api.github.com/repos/pandas-dev/pandas/pulls/20449
2018-03-22T10:32:17Z
2018-03-22T10:34:27Z
2018-03-22T10:34:27Z
2018-03-22T10:34:30Z
scatter plot and hexbin plot lose x-axis when colorbar is included.
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 0ca5b9cdf1d57..68f634bd5f85f 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -304,7 +304,7 @@ I/O Plotting ^^^^^^^^ -- +- Bug in :func:'DataFrame.plot.scatter' and :func:'DataFrame.plot.hexbin' caused x-axis label and ticklabels to disappear when colorbar was on in IPython inline backend (:issue:`10611` and :issue:`10678`) - - diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 8c713548d1ede..8c2ee90014302 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -833,6 +833,32 @@ def _post_plot_logic(self, ax, data): ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) + def _plot_colorbar(self, ax, **kwds): + # Addresses issues #10611 and #10678: + # When plotting scatterplots and hexbinplots in IPython + # inline backend the colorbar axis height tends not to + # exactly match the parent axis height. + # The difference is due to small fractional differences + # in floating points with similar representation. + # To deal with this, this method forces the colorbar + # height to take the height of the parent axes. + # For a more detailed description of the issue + # see the following link: + # https://github.com/ipython/ipython/issues/11215 + + img = ax.collections[0] + cbar = self.fig.colorbar(img, **kwds) + points = ax.get_position().get_points() + cbar_points = cbar.ax.get_position().get_points() + cbar.ax.set_position([cbar_points[0, 0], + points[0, 1], + cbar_points[1, 0] - cbar_points[0, 0], + points[1, 1] - points[0, 1]]) + # To see the discrepancy in axis heights uncomment + # the following two lines: + # print(points[1, 1] - points[0, 1]) + # print(cbar_points[1, 1] - cbar_points[0, 1]) + class ScatterPlot(PlanePlot): _kind = 'scatter' @@ -878,11 +904,9 @@ def _make_plot(self): scatter = ax.scatter(data[x].values, data[y].values, c=c_values, label=label, cmap=cmap, **self.kwds) if cb: - img = ax.collections[0] - kws = dict(ax=ax) if self.mpl_ge_1_3_1(): - kws['label'] = c if c_is_column else '' - self.fig.colorbar(img, **kws) + cbar_label = c if c_is_column else '' + self._plot_colorbar(ax, label=cbar_label) if label is not None: self._add_legend_handle(scatter, label) @@ -923,8 +947,7 @@ def _make_plot(self): ax.hexbin(data[x].values, data[y].values, C=c_values, cmap=cmap, **self.kwds) if cb: - img = ax.collections[0] - self.fig.colorbar(img, ax=ax) + self._plot_colorbar(ax) def _make_legend(self): pass diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 101713b06df8c..8ef0cf7154b88 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1089,6 +1089,49 @@ def test_plot_scatter(self): axes = df.plot(x='x', y='y', kind='scatter', subplots=True) self._check_axes_shape(axes, axes_num=1, layout=(1, 1)) + @pytest.mark.slow + def test_if_scatterplot_colorbar_affects_xaxis_visibility(self): + # addressing issue #10611, to ensure colobar does not + # interfere with x-axis label and ticklabels with + # ipython inline backend. + random_array = np.random.random((1000, 3)) + df = pd.DataFrame(random_array, + columns=['A label', 'B label', 'C label']) + + ax1 = df.plot.scatter(x='A label', y='B label') + ax2 = df.plot.scatter(x='A label', y='B label', c='C label') + + vis1 = [vis.get_visible() for vis in + ax1.xaxis.get_minorticklabels()] + vis2 = [vis.get_visible() for vis in + ax2.xaxis.get_minorticklabels()] + assert vis1 == vis2 + + vis1 = [vis.get_visible() for vis in + ax1.xaxis.get_majorticklabels()] + vis2 = [vis.get_visible() for vis in + ax2.xaxis.get_majorticklabels()] + assert vis1 == vis2 + + assert (ax1.xaxis.get_label().get_visible() == + ax2.xaxis.get_label().get_visible()) + + @pytest.mark.slow + def test_if_hexbin_xaxis_label_is_visible(self): + # addressing issue #10678, to ensure colobar does not + # interfere with x-axis label and ticklabels with + # ipython inline backend. + random_array = np.random.random((1000, 3)) + df = pd.DataFrame(random_array, + columns=['A label', 'B label', 'C label']) + + ax = df.plot.hexbin('A label', 'B label', gridsize=12) + assert all([vis.get_visible() for vis in + ax.xaxis.get_minorticklabels()]) + assert all([vis.get_visible() for vis in + ax.xaxis.get_majorticklabels()]) + assert ax.xaxis.get_label().get_visible() + @pytest.mark.slow def test_plot_scatter_with_categorical_data(self): # GH 16199
closes https://github.com/pandas-dev/pandas/issues/10611 closes https://github.com/pandas-dev/pandas/issues/10678. The x-axis for scatter plot and hexbin plot disappears when colorbar is included. This seems to be because colorbar axis is looped through in `_handle_shared_axes`: https://github.com/pandas-dev/pandas/blob/8a5830305d2d9a087fbe46bd968218104ffdfc49/pandas/plotting/_core.py#L426 after discussing with @TomAugspurger (issue https://github.com/pandas-dev/pandas/issues/10611), we decided to try adding the attribute `__is_pandas_colorbar` to colorbar axis object and skipping it during handling of shared axes. I've done some tests that seem to fix the issue. But we may need more tests: ``` %matplotlib inline import matplotlib.pylab as pl from mypandas import pandas as pd import numpy as np random_array = np.random.random((1000,3)) df = pd.DataFrame(random_array,columns=['A label','B label','C label']) df.plot.scatter('A label','B label',c='C label', PATCH_MODE_FLAG = False);pl.title('pandas current version'); df.plot.scatter('A label','B label',c='C label', PATCH_MODE_FLAG = True);pl.title('patch fixing x-axis'); df.plot.hexbin('A label','B label', gridsize=25, PATCH_MODE_FLAG = False);pl.title('pandas current version'); df.plot.hexbin('A label','B label', gridsize=25, PATCH_MODE_FLAG = True);pl.title('patch fixing x-axis'); ``` ![image](https://user-images.githubusercontent.com/26352146/37747996-49642266-2d58-11e8-8c6f-c382267e79db.png) ![image](https://user-images.githubusercontent.com/26352146/37747999-4d88d986-2d58-11e8-8445-f1348c35d892.png) ![image](https://user-images.githubusercontent.com/26352146/37748001-5109d93e-2d58-11e8-9f6f-73a68329f731.png) ![image](https://user-images.githubusercontent.com/26352146/37748005-54beb590-2d58-11e8-8233-4e26b135fdad.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/20446
2018-03-22T02:47:27Z
2018-07-04T12:59:42Z
2018-07-04T12:59:41Z
2018-07-04T13:01:54Z
API: Preserve int columns in to_dict('index')
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 1d60febe29b4a..c9653f3b7a3bd 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -715,6 +715,7 @@ Other API Changes - :func:`Series.str.replace` now takes an optional `regex` keyword which, when set to ``False``, uses literal string replacement rather than regex replacement (:issue:`16808`) - :func:`DatetimeIndex.strftime` and :func:`PeriodIndex.strftime` now return an ``Index`` instead of a numpy array to be consistent with similar accessors (:issue:`20127`) - Constructing a Series from a list of length 1 no longer broadcasts this list when a longer index is specified (:issue:`19714`, :issue:`20391`). +- :func:`DataFrame.to_dict` with ``orient='index'`` no longer casts int columns to float for a DataFrame with only int and float columns (:issue:`18580`) .. _whatsnew_0230.deprecations: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cf41737a04ba6..d3eda29eceac8 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1102,7 +1102,8 @@ def to_dict(self, orient='dict', into=dict): for k, v in zip(self.columns, np.atleast_1d(row))) for row in self.values] elif orient.lower().startswith('i'): - return into_c((k, v.to_dict(into)) for k, v in self.iterrows()) + return into_c((t[0], dict(zip(self.columns, t[1:]))) + for t in self.itertuples()) else: raise ValueError("orient '%s' not understood" % orient) diff --git a/pandas/tests/frame/test_convert_to.py b/pandas/tests/frame/test_convert_to.py index 024de8bc13f72..82dadacd5b1ac 100644 --- a/pandas/tests/frame/test_convert_to.py +++ b/pandas/tests/frame/test_convert_to.py @@ -5,6 +5,7 @@ import pytest import pytz import collections +from collections import OrderedDict, defaultdict import numpy as np from pandas import compat @@ -288,3 +289,29 @@ def test_frame_to_dict_tz(self): ] tm.assert_dict_equal(result[0], expected[0]) tm.assert_dict_equal(result[1], expected[1]) + + @pytest.mark.parametrize('into, expected', [ + (dict, {0: {'int_col': 1, 'float_col': 1.0}, + 1: {'int_col': 2, 'float_col': 2.0}, + 2: {'int_col': 3, 'float_col': 3.0}}), + (OrderedDict, OrderedDict([(0, {'int_col': 1, 'float_col': 1.0}), + (1, {'int_col': 2, 'float_col': 2.0}), + (2, {'int_col': 3, 'float_col': 3.0})])), + (defaultdict(list), defaultdict(list, + {0: {'int_col': 1, 'float_col': 1.0}, + 1: {'int_col': 2, 'float_col': 2.0}, + 2: {'int_col': 3, 'float_col': 3.0}})) + ]) + def test_to_dict_index_dtypes(self, into, expected): + # GH 18580 + # When using to_dict(orient='index') on a dataframe with int + # and float columns only the int columns were cast to float + + df = DataFrame({'int_col': [1, 2, 3], + 'float_col': [1.0, 2.0, 3.0]}) + + result = df.to_dict(orient='index', into=into) + cols = ['int_col', 'float_col'] + result = DataFrame.from_dict(result, orient='index')[cols] + expected = DataFrame.from_dict(expected, orient='index')[cols] + tm.assert_frame_equal(result, expected)
- [x] closes #18580 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/20444
2018-03-21T22:58:59Z
2018-03-25T14:10:27Z
2018-03-25T14:10:27Z
2018-03-25T16:09:09Z
BUG: safe_sort losing MultiIndex dtypes
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 2e6737b2e61aa..77de1636a92eb 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -14,6 +14,7 @@ Sequence, cast, final, + overload, ) import warnings @@ -101,6 +102,7 @@ Categorical, DataFrame, Index, + MultiIndex, Series, ) from pandas.core.arrays import ( @@ -1780,7 +1782,7 @@ def safe_sort( na_sentinel: int = -1, assume_unique: bool = False, verify: bool = True, -) -> np.ndarray | tuple[np.ndarray, np.ndarray]: +) -> np.ndarray | MultiIndex | tuple[np.ndarray | MultiIndex, np.ndarray]: """ Sort ``values`` and reorder corresponding ``codes``. @@ -1809,7 +1811,7 @@ def safe_sort( Returns ------- - ordered : ndarray + ordered : ndarray or MultiIndex Sorted ``values`` new_codes : ndarray Reordered ``codes``; returned when ``codes`` is not None. @@ -1827,6 +1829,7 @@ def safe_sort( raise TypeError( "Only list-like objects are allowed to be passed to safe_sort as values" ) + original_values = values if not isinstance(values, (np.ndarray, ABCExtensionArray)): # don't convert to string types @@ -1838,6 +1841,7 @@ def safe_sort( values = np.asarray(values, dtype=dtype) # type: ignore[arg-type] sorter = None + ordered: np.ndarray | MultiIndex if ( not is_extension_array_dtype(values) @@ -1853,7 +1857,7 @@ def safe_sort( # which would work, but which fails for special case of 1d arrays # with tuples. if values.size and isinstance(values[0], tuple): - ordered = _sort_tuples(values) + ordered = _sort_tuples(values, original_values) else: ordered = _sort_mixed(values) @@ -1915,19 +1919,33 @@ def _sort_mixed(values) -> np.ndarray: ) -def _sort_tuples(values: np.ndarray) -> np.ndarray: +@overload +def _sort_tuples(values: np.ndarray, original_values: np.ndarray) -> np.ndarray: + ... + + +@overload +def _sort_tuples(values: np.ndarray, original_values: MultiIndex) -> MultiIndex: + ... + + +def _sort_tuples( + values: np.ndarray, original_values: np.ndarray | MultiIndex +) -> np.ndarray | MultiIndex: """ Convert array of tuples (1d) to array or array (2d). We need to keep the columns separately as they contain different types and nans (can't use `np.sort` as it may fail when str and nan are mixed in a column as types cannot be compared). + We have to apply the indexer to the original values to keep the dtypes in + case of MultiIndexes """ from pandas.core.internals.construction import to_arrays from pandas.core.sorting import lexsort_indexer arrays, _ = to_arrays(values, None) indexer = lexsort_indexer(arrays, orders=True) - return values[indexer] + return original_values[indexer] def union_with_duplicates(lvals: ArrayLike, rvals: ArrayLike) -> ArrayLike: diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py index 396c4d82d01fc..537792ea8263c 100644 --- a/pandas/tests/test_sorting.py +++ b/pandas/tests/test_sorting.py @@ -11,6 +11,7 @@ ) from pandas import ( + NA, DataFrame, MultiIndex, Series, @@ -510,3 +511,15 @@ def test_mixed_str_nan(): result = safe_sort(values) expected = np.array([np.nan, "a", "b", "b"], dtype=object) tm.assert_numpy_array_equal(result, expected) + + +def test_safe_sort_multiindex(): + # GH#48412 + arr1 = Series([2, 1, NA, NA], dtype="Int64") + arr2 = [2, 1, 3, 3] + midx = MultiIndex.from_arrays([arr1, arr2]) + result = safe_sort(midx) + expected = MultiIndex.from_arrays( + [Series([1, 2, NA, NA], dtype="Int64"), [1, 2, 3, 3]] + ) + tm.assert_index_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. I don't think that this is user visible. This is a precursor for improving ea support in MultiIndex operations
https://api.github.com/repos/pandas-dev/pandas/pulls/48412
2022-09-06T13:36:20Z
2022-09-06T19:27:51Z
2022-09-06T19:27:51Z
2022-10-07T21:13:07Z
REGR: get_loc for ExtensionEngine not returning bool indexer for na
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 0cf7c4d45c634..617760c2981c4 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -1061,7 +1061,7 @@ cdef class ExtensionEngine(SharedEngine): cdef ndarray _get_bool_indexer(self, val): if checknull(val): - return self.values.isna().view("uint8") + return self.values.isna() try: return self.values == val diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py index 739039241a31d..ab934df992d61 100644 --- a/pandas/tests/indexes/test_indexing.py +++ b/pandas/tests/indexes/test_indexing.py @@ -20,6 +20,7 @@ from pandas.errors import InvalidIndexError from pandas import ( + NA, DatetimeIndex, Index, IntervalIndex, @@ -221,6 +222,13 @@ def test_get_loc_generator(self, index): # MultiIndex specifically checks for generator; others for scalar index.get_loc(x for x in range(5)) + def test_get_loc_masked_duplicated_na(self): + # GH#48411 + idx = Index([1, 2, NA, NA], dtype="Int64") + result = idx.get_loc(NA) + expected = np.array([False, False, True, True]) + tm.assert_numpy_array_equal(result, expected) + class TestGetIndexer: def test_get_indexer_base(self, index): @@ -253,6 +261,13 @@ def test_get_indexer_consistency(self, index): assert isinstance(indexer, np.ndarray) assert indexer.dtype == np.intp + def test_get_indexer_masked_duplicated_na(self): + # GH#48411 + idx = Index([1, 2, NA, NA], dtype="Int64") + result = idx.get_indexer_for(Index([1, NA], dtype="Int64")) + expected = np.array([0, 2, 3], dtype=result.dtype) + tm.assert_numpy_array_equal(result, expected) + class TestConvertSliceIndexer: def test_convert_almost_null_slice(self, index):
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Stumbled across this when working on something else. ExtensionEngine was new in 1.5, so no whatsnew. But should backport to 1.5
https://api.github.com/repos/pandas-dev/pandas/pulls/48411
2022-09-06T11:21:50Z
2022-09-07T07:12:37Z
2022-09-07T07:12:37Z
2022-09-08T19:19:14Z
Docs: Added 'cross' option to one part of DataFrame.join() docstring where it was missing
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b20decab26928..4cdd62b038485 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9862,7 +9862,7 @@ def join( values given, the `other` DataFrame must have a MultiIndex. Can pass an array as the join key if it is not already contained in the calling DataFrame. Like an Excel VLOOKUP operation. - how : {'left', 'right', 'outer', 'inner'}, default 'left' + how : {'left', 'right', 'outer', 'inner', 'cross'}, default 'left' How to handle the operation of the two objects. * left: use calling frame's index (or column if on is specified)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48407
2022-09-06T01:09:27Z
2022-09-06T09:10:02Z
2022-09-06T09:10:02Z
2022-10-13T17:00:48Z
PERF: MultiIndex.argsort / MultiIndex.sort_values
diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py index ca1d71f50bd5f..89d74e784b64c 100644 --- a/asv_bench/benchmarks/multiindex_object.py +++ b/asv_bench/benchmarks/multiindex_object.py @@ -8,6 +8,7 @@ MultiIndex, RangeIndex, Series, + array, date_range, ) @@ -176,6 +177,20 @@ def time_sortlevel_one(self): self.mi.sortlevel(1) +class SortValues: + + params = ["int64", "Int64"] + param_names = ["dtype"] + + def setup(self, dtype): + a = array(np.tile(np.arange(100), 1000), dtype=dtype) + b = array(np.tile(np.arange(1000), 100), dtype=dtype) + self.mi = MultiIndex.from_arrays([a, b]) + + def time_sort_values(self, dtype): + self.mi.sort_values() + + class Values: def setup_cache(self): diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index c393b8a57f805..59c27560c4e1e 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -101,6 +101,7 @@ Deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Performance improvement in :meth:`.GroupBy.median` for nullable dtypes (:issue:`37493`) +- Performance improvement in :meth:`MultiIndex.argsort` and :meth:`MultiIndex.sort_values` (:issue:`48406`) - Performance improvement in :meth:`.GroupBy.mean` and :meth:`.GroupBy.var` for extension array dtypes (:issue:`37493`) - Performance improvement for :meth:`MultiIndex.unique` (:issue:`48335`) - diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 6bf00bc5bc366..0ebd1a3d718d8 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2225,6 +2225,10 @@ def append(self, other): return Index._with_infer(new_tuples) def argsort(self, *args, **kwargs) -> npt.NDArray[np.intp]: + if len(args) == 0 and len(kwargs) == 0: + # np.lexsort is significantly faster than self._values.argsort() + values = [self._get_level_values(i) for i in reversed(range(self.nlevels))] + return np.lexsort(values) return self._values.argsort(*args, **kwargs) @Appender(_index_shared_docs["repeat"] % _index_doc_kwargs) diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index d29abc1bc6a9f..e15809a751b73 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -530,11 +530,6 @@ def test_union_duplicates(index, request): if index.empty or isinstance(index, (IntervalIndex, CategoricalIndex)): # No duplicates in empty indexes return - if index.dtype.kind == "c": - mark = pytest.mark.xfail( - reason="sort_values() call raises bc complex objects are not comparable" - ) - request.node.add_marker(mark) values = index.unique().values.tolist() mi1 = MultiIndex.from_arrays([values, [1] * len(values)])
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v1.6.0.rst` file if fixing a bug or adding a new feature. Perf improvement in `MultiIndex.argsort` and `MultiIndex.sort_values` for the vast majority of cases (where `MultiIndex.argsort` is called without additional passthrough numpy parameters). Also, an xfail was removed because np.lexsort does not complain about complex dtype arrays whereas np.argsort will complain about an object array of tuples containing complex and non-complex dtypes. ASV added: ``` before after ratio [fa211d47] [b2fea756] <main> <perf-multiindex-argsort> - 81.0±0.9ms 27.9±0.7ms 0.34 multiindex_object.SortValues.time_sort_values('Int64') - 96.9±2ms 2.00±0.2ms 0.02 multiindex_object.SortValues.time_sort_values('int64') ```
https://api.github.com/repos/pandas-dev/pandas/pulls/48406
2022-09-06T01:08:11Z
2022-09-09T17:40:46Z
2022-09-09T17:40:46Z
2022-10-13T17:00:47Z
ENH: Add use_nullable_dtypes in csv internals
diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index e8b7160af9b2c..07bf7f69ec907 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -15,6 +15,13 @@ import warnings from pandas.util._exceptions import find_stack_level +from pandas import StringDtype +from pandas.core.arrays import ( + BooleanArray, + FloatingArray, + IntegerArray, +) + cimport cython from cpython.bytes cimport ( PyBytes_AsString, @@ -1378,18 +1385,53 @@ STR_NA_VALUES = { _NA_VALUES = _ensure_encoded(list(STR_NA_VALUES)) -def _maybe_upcast(arr): - """ +def _maybe_upcast(arr, use_nullable_dtypes: bool = False): + """Sets nullable dtypes or upcasts if nans are present. + Upcast, if use_nullable_dtypes is false and nans are present so that the + current dtype can not hold the na value. We use nullable dtypes if the + flag is true for every array. + + Parameters + ---------- + arr: ndarray + Numpy array that is potentially being upcast. + + use_nullable_dtypes: bool, default False + If true, we cast to the associated nullable dtypes. + + Returns + ------- + The casted array. """ + na_value = na_values[arr.dtype] + if issubclass(arr.dtype.type, np.integer): - na_value = na_values[arr.dtype] - arr = arr.astype(float) - np.putmask(arr, arr == na_value, np.nan) + mask = arr == na_value + + if use_nullable_dtypes: + arr = IntegerArray(arr, mask) + else: + arr = arr.astype(float) + np.putmask(arr, mask, np.nan) + elif arr.dtype == np.bool_: - mask = arr.view(np.uint8) == na_values[np.uint8] - arr = arr.astype(object) - np.putmask(arr, mask, np.nan) + mask = arr.view(np.uint8) == na_value + + if use_nullable_dtypes: + arr = BooleanArray(arr, mask) + else: + arr = arr.astype(object) + np.putmask(arr, mask, np.nan) + + elif issubclass(arr.dtype.type, float) or arr.dtype.type == np.float32: + if use_nullable_dtypes: + mask = np.isnan(arr) + arr = FloatingArray(arr, mask) + + elif arr.dtype == np.object_: + if use_nullable_dtypes: + arr = StringDtype().construct_array_type()._from_sequence(arr) return arr @@ -1985,6 +2027,7 @@ def _compute_na_values(): uint16info = np.iinfo(np.uint16) uint8info = np.iinfo(np.uint8) na_values = { + np.float32: np.nan, np.float64: np.nan, np.int64: int64info.min, np.int32: int32info.min, diff --git a/pandas/tests/io/parser/test_upcast.py b/pandas/tests/io/parser/test_upcast.py new file mode 100644 index 0000000000000..428050ac01b58 --- /dev/null +++ b/pandas/tests/io/parser/test_upcast.py @@ -0,0 +1,108 @@ +import numpy as np +import pytest + +from pandas._libs.parsers import ( # type: ignore[attr-defined] + _maybe_upcast, + na_values, +) +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import NA +import pandas._testing as tm +from pandas.core.arrays import ( + ArrowStringArray, + BooleanArray, + FloatingArray, + IntegerArray, + StringArray, +) + + +def test_maybe_upcast(any_real_numpy_dtype): + # GH#36712 + + dtype = np.dtype(any_real_numpy_dtype) + na_value = na_values[dtype] + arr = np.array([1, 2, na_value], dtype=dtype) + result = _maybe_upcast(arr, use_nullable_dtypes=True) + + expected_mask = np.array([False, False, True]) + if issubclass(dtype.type, np.integer): + expected = IntegerArray(arr, mask=expected_mask) + else: + expected = FloatingArray(arr, mask=expected_mask) + + tm.assert_extension_array_equal(result, expected) + + +def test_maybe_upcast_no_na(any_real_numpy_dtype): + # GH#36712 + if any_real_numpy_dtype == "float32": + pytest.skip() + + arr = np.array([1, 2, 3], dtype=any_real_numpy_dtype) + result = _maybe_upcast(arr, use_nullable_dtypes=True) + + expected_mask = np.array([False, False, False]) + if issubclass(np.dtype(any_real_numpy_dtype).type, np.integer): + expected = IntegerArray(arr, mask=expected_mask) + else: + expected = FloatingArray(arr, mask=expected_mask) + + tm.assert_extension_array_equal(result, expected) + + +def test_maybe_upcaste_bool(): + # GH#36712 + dtype = np.bool_ + na_value = na_values[dtype] + arr = np.array([True, False, na_value], dtype="uint8").view(dtype) + result = _maybe_upcast(arr, use_nullable_dtypes=True) + + expected_mask = np.array([False, False, True]) + expected = BooleanArray(arr, mask=expected_mask) + tm.assert_extension_array_equal(result, expected) + + +def test_maybe_upcaste_bool_no_nan(): + # GH#36712 + dtype = np.bool_ + arr = np.array([True, False, False], dtype="uint8").view(dtype) + result = _maybe_upcast(arr, use_nullable_dtypes=True) + + expected_mask = np.array([False, False, False]) + expected = BooleanArray(arr, mask=expected_mask) + tm.assert_extension_array_equal(result, expected) + + +def test_maybe_upcaste_all_nan(): + # GH#36712 + dtype = np.int64 + na_value = na_values[dtype] + arr = np.array([na_value, na_value], dtype=dtype) + result = _maybe_upcast(arr, use_nullable_dtypes=True) + + expected_mask = np.array([True, True]) + expected = IntegerArray(arr, mask=expected_mask) + tm.assert_extension_array_equal(result, expected) + + +@td.skip_if_no("pyarrow") +@pytest.mark.parametrize("storage", ["pyarrow", "python"]) +@pytest.mark.parametrize("val", [na_values[np.object_], "c"]) +def test_maybe_upcast_object(val, storage): + # GH#36712 + import pyarrow as pa + + with pd.option_context("mode.string_storage", storage): + arr = np.array(["a", "b", val], dtype=np.object_) + result = _maybe_upcast(arr, use_nullable_dtypes=True) + + if storage == "python": + exp_val = "c" if val == "c" else NA + expected = StringArray(np.array(["a", "b", exp_val], dtype=np.object_)) + else: + exp_val = "c" if val == "c" else None + expected = ArrowStringArray(pa.array(["a", "b", exp_val])) + tm.assert_extension_array_equal(result, expected)
- [x] xref #36712 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This adds the required casting logic for extension array dtypes. Want to get this done as a first step before adding a public option to read_csv. The unit tests can be used as a guideline for the required behaviour. This always casts to ea dtypes, even when no missing values are present. From a users perspective this makes the most sense imo. You don't want to do a follow up operation and end up with float in a pipeline, when you set nullable dtypes (reindexing, enlargement in indexing ops, ...). That said, if there are concerns about this, we could also do something like ``use_nullable_dtypes=False | always | when necessary`` cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/48403
2022-09-05T18:57:54Z
2022-09-19T23:13:54Z
2022-09-19T23:13:54Z
2022-10-13T17:00:46Z
Backport PR #48381 on branch 1.5.x (CI: Pin mambaforge image)
diff --git a/Dockerfile b/Dockerfile index 0bfb0e15d63fe..02c360d2f3d49 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM quay.io/condaforge/mambaforge +FROM quay.io/condaforge/mambaforge:4.13.0-1 # if you forked pandas, you can pass in your own GitHub username to use your fork # i.e. gh_username=myname
Backport PR #48381: CI: Pin mambaforge image
https://api.github.com/repos/pandas-dev/pandas/pulls/48401
2022-09-05T17:07:48Z
2022-09-05T19:42:10Z
2022-09-05T19:42:10Z
2022-09-05T19:42:11Z
CLN: Refactor groupby._make_wrapper
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 7a7050ea8bad7..48822d9d01ddb 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -550,10 +550,12 @@ def apply_str(self) -> DataFrame | Series: func = getattr(obj, f, None) if callable(func): sig = inspect.getfullargspec(func) - if "axis" in sig.args: - self.kwargs["axis"] = self.axis - elif self.axis != 0: + if self.axis != 0 and ( + "axis" not in sig.args or f in ("corrwith", "mad", "skew") + ): raise ValueError(f"Operation {f} does not support axis=1") + elif "axis" in sig.args: + self.kwargs["axis"] = self.axis return self._try_aggregate_string_function(obj, f, *self.args, **self.kwargs) def apply_multiple(self) -> DataFrame | Series: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 32d4ac24a1d53..7a201c1d9202f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11657,10 +11657,8 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): setattr(cls, "all", all) - # error: Argument 1 to "doc" has incompatible type "Optional[str]"; expected - # "Union[str, Callable[..., Any]]" @doc( - NDFrame.mad.__doc__, # type: ignore[arg-type] + NDFrame.mad.__doc__, desc="Return the mean absolute deviation of the values " "over the requested axis.", name1=name1, diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index ad1f36e0cddd8..953fc4673a38e 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -1,7 +1,5 @@ """ -Provide basic components for groupby. These definitions -hold the allowlist of methods that are exposed on the -SeriesGroupBy and the DataFrameGroupBy objects. +Provide basic components for groupby. """ from __future__ import annotations @@ -22,36 +20,6 @@ class OutputKey: # forwarding methods from NDFrames plotting_methods = frozenset(["plot", "hist"]) -common_apply_allowlist = ( - frozenset( - [ - "quantile", - "fillna", - "mad", - "take", - "idxmax", - "idxmin", - "tshift", - "skew", - "corr", - "cov", - "diff", - ] - ) - | plotting_methods -) - -series_apply_allowlist: frozenset[str] = ( - common_apply_allowlist - | frozenset( - {"nlargest", "nsmallest", "is_monotonic_increasing", "is_monotonic_decreasing"} - ) -) | frozenset(["dtype", "unique"]) - -dataframe_apply_allowlist: frozenset[str] = common_apply_allowlist | frozenset( - ["dtypes", "corrwith"] -) - # cythonized transformations or canned "agg+broadcast", which do not # require postprocessing of the result by transform. cythonized_kernels = frozenset(["cumprod", "cumsum", "shift", "cummin", "cummax"]) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 7fe1d55ba55be..c06042915cbc2 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -17,6 +17,7 @@ Callable, Hashable, Iterable, + Literal, Mapping, NamedTuple, Sequence, @@ -35,9 +36,14 @@ ) from pandas._typing import ( ArrayLike, + Axis, + FillnaOptions, + IndexLabel, + Level, Manager, Manager2D, SingleManager, + TakeIndexer, ) from pandas.errors import SpecificationError from pandas.util._decorators import ( @@ -78,6 +84,7 @@ from pandas.core.groupby import base from pandas.core.groupby.groupby import ( GroupBy, + GroupByPlot, _agg_template, _apply_docs, _transform_template, @@ -135,48 +142,7 @@ def prop(self): return property(prop) -def pin_allowlisted_properties( - klass: type[DataFrame | Series], allowlist: frozenset[str] -): - """ - Create GroupBy member defs for DataFrame/Series names in a allowlist. - - Parameters - ---------- - klass : DataFrame or Series class - class where members are defined. - allowlist : frozenset[str] - Set of names of klass methods to be constructed - - Returns - ------- - class decorator - - Notes - ----- - Since we don't want to override methods explicitly defined in the - base class, any such name is skipped. - """ - - def pinner(cls): - for name in allowlist: - if hasattr(cls, name): - # don't override anything that was explicitly defined - # in the base class - continue - - prop = generate_property(name, klass) - setattr(cls, name, prop) - - return cls - - return pinner - - -@pin_allowlisted_properties(Series, base.series_apply_allowlist) class SeriesGroupBy(GroupBy[Series]): - _apply_allowlist = base.series_apply_allowlist - def _wrap_agged_manager(self, mgr: Manager) -> Series: if mgr.ndim == 1: mgr = cast(SingleManager, mgr) @@ -754,8 +720,82 @@ def build_codes(lev_codes: np.ndarray) -> np.ndarray: out = ensure_int64(out) return self.obj._constructor(out, index=mi, name=self.obj.name) - @doc(Series.nlargest) - def nlargest(self, n: int = 5, keep: str = "first") -> Series: + @doc(Series.fillna.__doc__) + def fillna( + self, + value: object | ArrayLike | None = None, + method: FillnaOptions | None = None, + axis: Axis | None = None, + inplace: bool = False, + limit: int | None = None, + downcast: dict | None = None, + ) -> Series | None: + result = self._op_via_apply( + "fillna", + value=value, + method=method, + axis=axis, + inplace=inplace, + limit=limit, + downcast=downcast, + ) + return result + + @doc(Series.take.__doc__) + def take( + self, + indices: TakeIndexer, + axis: Axis = 0, + is_copy: bool | None = None, + **kwargs, + ) -> Series: + result = self._op_via_apply( + "take", indices=indices, axis=axis, is_copy=is_copy, **kwargs + ) + return result + + @doc(Series.skew.__doc__) + def skew( + self, + axis: Axis | lib.NoDefault = lib.no_default, + skipna: bool = True, + level: Level | None = None, + numeric_only: bool | None = None, + **kwargs, + ) -> Series: + result = self._op_via_apply( + "skew", + axis=axis, + skipna=skipna, + level=level, + numeric_only=numeric_only, + **kwargs, + ) + return result + + @doc(Series.mad.__doc__) + def mad( + self, axis: Axis | None = None, skipna: bool = True, level: Level | None = None + ) -> Series: + result = self._op_via_apply("mad", axis=axis, skipna=skipna, level=level) + return result + + @doc(Series.tshift.__doc__) + def tshift(self, periods: int = 1, freq=None) -> Series: + result = self._op_via_apply("tshift", periods=periods, freq=freq) + return result + + # Decorated property not supported - https://github.com/python/mypy/issues/1362 + @property # type: ignore[misc] + @doc(Series.plot.__doc__) + def plot(self): + result = GroupByPlot(self) + return result + + @doc(Series.nlargest.__doc__) + def nlargest( + self, n: int = 5, keep: Literal["first", "last", "all"] = "first" + ) -> Series: f = partial(Series.nlargest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. @@ -763,8 +803,10 @@ def nlargest(self, n: int = 5, keep: str = "first") -> Series: result = self._python_apply_general(f, data, not_indexed_same=True) return result - @doc(Series.nsmallest) - def nsmallest(self, n: int = 5, keep: str = "first") -> Series: + @doc(Series.nsmallest.__doc__) + def nsmallest( + self, n: int = 5, keep: Literal["first", "last", "all"] = "first" + ) -> Series: f = partial(Series.nsmallest, n=n, keep=keep) data = self._obj_with_exclusions # Don't change behavior if result index happens to be the same, i.e. @@ -772,11 +814,99 @@ def nsmallest(self, n: int = 5, keep: str = "first") -> Series: result = self._python_apply_general(f, data, not_indexed_same=True) return result + @doc(Series.idxmin.__doc__) + def idxmin(self, axis: Axis = 0, skipna: bool = True) -> Series: + result = self._op_via_apply("idxmin", axis=axis, skipna=skipna) + return result -@pin_allowlisted_properties(DataFrame, base.dataframe_apply_allowlist) -class DataFrameGroupBy(GroupBy[DataFrame]): + @doc(Series.idxmax.__doc__) + def idxmax(self, axis: Axis = 0, skipna: bool = True) -> Series: + result = self._op_via_apply("idxmax", axis=axis, skipna=skipna) + return result + + @doc(Series.corr.__doc__) + def corr( + self, + other: Series, + method: Literal["pearson", "kendall", "spearman"] + | Callable[[np.ndarray, np.ndarray], float] = "pearson", + min_periods: int | None = None, + ) -> Series: + result = self._op_via_apply( + "corr", other=other, method=method, min_periods=min_periods + ) + return result + + @doc(Series.cov.__doc__) + def cov( + self, other: Series, min_periods: int | None = None, ddof: int | None = 1 + ) -> Series: + result = self._op_via_apply( + "cov", other=other, min_periods=min_periods, ddof=ddof + ) + return result + + # Decorated property not supported - https://github.com/python/mypy/issues/1362 + @property # type: ignore[misc] + @doc(Series.is_monotonic_increasing.__doc__) + def is_monotonic_increasing(self) -> Series: + result = self._op_via_apply("is_monotonic_increasing") + return result + + # Decorated property not supported - https://github.com/python/mypy/issues/1362 + @property # type: ignore[misc] + @doc(Series.is_monotonic_decreasing.__doc__) + def is_monotonic_decreasing(self) -> Series: + result = self._op_via_apply("is_monotonic_decreasing") + return result + + @doc(Series.hist.__doc__) + def hist( + self, + by=None, + ax=None, + grid: bool = True, + xlabelsize: int | None = None, + xrot: float | None = None, + ylabelsize: int | None = None, + yrot: float | None = None, + figsize: tuple[int, int] | None = None, + bins: int | Sequence[int] = 10, + backend: str | None = None, + legend: bool = False, + **kwargs, + ): + result = self._op_via_apply( + "hist", + by=by, + ax=ax, + grid=grid, + xlabelsize=xlabelsize, + xrot=xrot, + ylabelsize=ylabelsize, + yrot=yrot, + figsize=figsize, + bins=bins, + backend=backend, + legend=legend, + **kwargs, + ) + return result + + # Decorated property not supported - https://github.com/python/mypy/issues/1362 + @property # type: ignore[misc] + @doc(Series.dtype.__doc__) + def dtype(self) -> Series: + result = self._op_via_apply("dtype") + return result + + @doc(Series.unique.__doc__) + def unique(self) -> Series: + result = self._op_via_apply("unique") + return result - _apply_allowlist = base.dataframe_apply_allowlist + +class DataFrameGroupBy(GroupBy[DataFrame]): _agg_examples_doc = dedent( """ @@ -1911,6 +2041,169 @@ def value_counts( result = result_frame return result.__finalize__(self.obj, method="value_counts") + @doc(DataFrame.fillna.__doc__) + def fillna( + self, + value: Hashable | Mapping | Series | DataFrame = None, + method: FillnaOptions | None = None, + axis: Axis | None = None, + inplace: bool = False, + limit=None, + downcast=None, + ) -> DataFrame | None: + result = self._op_via_apply( + "fillna", + value=value, + method=method, + axis=axis, + inplace=inplace, + limit=limit, + downcast=downcast, + ) + return result + + @doc(DataFrame.take.__doc__) + def take( + self, + indices: TakeIndexer, + axis: Axis | None = 0, + is_copy: bool | None = None, + **kwargs, + ) -> DataFrame: + result = self._op_via_apply( + "take", indices=indices, axis=axis, is_copy=is_copy, **kwargs + ) + return result + + @doc(DataFrame.skew.__doc__) + def skew( + self, + axis: Axis | None | lib.NoDefault = lib.no_default, + skipna: bool = True, + level: Level | None = None, + numeric_only: bool | lib.NoDefault = lib.no_default, + **kwargs, + ) -> DataFrame: + result = self._op_via_apply( + "skew", + axis=axis, + skipna=skipna, + level=level, + numeric_only=numeric_only, + **kwargs, + ) + return result + + @doc(DataFrame.mad.__doc__) + def mad( + self, axis: Axis | None = None, skipna: bool = True, level: Level | None = None + ) -> DataFrame: + result = self._op_via_apply("mad", axis=axis, skipna=skipna, level=level) + return result + + @doc(DataFrame.tshift.__doc__) + def tshift(self, periods: int = 1, freq=None, axis: Axis = 0) -> DataFrame: + result = self._op_via_apply("tshift", periods=periods, freq=freq, axis=axis) + return result + + @property # type: ignore[misc] + @doc(DataFrame.plot.__doc__) + def plot(self) -> GroupByPlot: + result = GroupByPlot(self) + return result + + @doc(DataFrame.corr.__doc__) + def corr( + self, + method: str | Callable[[np.ndarray, np.ndarray], float] = "pearson", + min_periods: int = 1, + numeric_only: bool | lib.NoDefault = lib.no_default, + ) -> DataFrame: + result = self._op_via_apply( + "corr", method=method, min_periods=min_periods, numeric_only=numeric_only + ) + return result + + @doc(DataFrame.cov.__doc__) + def cov( + self, + min_periods: int | None = None, + ddof: int | None = 1, + numeric_only: bool | lib.NoDefault = lib.no_default, + ) -> DataFrame: + result = self._op_via_apply( + "cov", min_periods=min_periods, ddof=ddof, numeric_only=numeric_only + ) + return result + + @doc(DataFrame.hist.__doc__) + def hist( + self, + column: IndexLabel = None, + by=None, + grid: bool = True, + xlabelsize: int | None = None, + xrot: float | None = None, + ylabelsize: int | None = None, + yrot: float | None = None, + ax=None, + sharex: bool = False, + sharey: bool = False, + figsize: tuple[int, int] | None = None, + layout: tuple[int, int] | None = None, + bins: int | Sequence[int] = 10, + backend: str | None = None, + legend: bool = False, + **kwargs, + ): + result = self._op_via_apply( + "hist", + column=column, + by=by, + grid=grid, + xlabelsize=xlabelsize, + xrot=xrot, + ylabelsize=ylabelsize, + yrot=yrot, + ax=ax, + sharex=sharex, + sharey=sharey, + figsize=figsize, + layout=layout, + bins=bins, + backend=backend, + legend=legend, + **kwargs, + ) + return result + + # Decorated property not supported - https://github.com/python/mypy/issues/1362 + @property # type: ignore[misc] + @doc(DataFrame.dtypes.__doc__) + def dtypes(self) -> Series: + result = self._op_via_apply("dtypes") + return result + + @doc(DataFrame.corrwith.__doc__) + def corrwith( + self, + other: DataFrame | Series, + axis: Axis = 0, + drop: bool = False, + method: Literal["pearson", "kendall", "spearman"] + | Callable[[np.ndarray, np.ndarray], float] = "pearson", + numeric_only: bool | lib.NoDefault = lib.no_default, + ) -> DataFrame: + result = self._op_via_apply( + "corrwith", + other=other, + axis=axis, + drop=drop, + method=method, + numeric_only=numeric_only, + ) + return result + def _wrap_transform_general_frame( obj: DataFrame, group: DataFrame, res: DataFrame | Series diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 89c9f3701a424..a22774f8a2232 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -16,7 +16,6 @@ class providing the base-class of operations. ) import inspect from textwrap import dedent -import types from typing import ( TYPE_CHECKING, Callable, @@ -626,7 +625,6 @@ def f(self): class BaseGroupBy(PandasObject, SelectionMixin[NDFrameT], GroupByIndexingMixin): _group_selection: IndexLabel | None = None - _apply_allowlist: frozenset[str] = frozenset() _hidden_attrs = PandasObject._hidden_attrs | { "as_index", "axis", @@ -750,7 +748,7 @@ def _selected_obj(self): @final def _dir_additions(self) -> set[str]: - return self.obj._dir_additions() | self._apply_allowlist + return self.obj._dir_additions() @Substitution( klass="GroupBy", @@ -783,8 +781,6 @@ def pipe( ) -> T: return com.pipe(self, func, *args, **kwargs) - plot = property(GroupByPlot) - @final def get_group(self, name, obj=None) -> DataFrame | Series: """ @@ -992,75 +988,66 @@ def __getattribute__(self, attr: str): return super().__getattribute__(attr) @final - def _make_wrapper(self, name: str) -> Callable: - assert name in self._apply_allowlist - + def _op_via_apply(self, name: str, *args, **kwargs): + """Compute the result of an operation by using GroupBy's apply.""" + f = getattr(type(self._obj_with_exclusions), name) with self._group_selection_context(): # need to setup the selection # as are not passed directly but in the grouper - f = getattr(self._obj_with_exclusions, name) - if not isinstance(f, types.MethodType): - # error: Incompatible return value type - # (got "NDFrameT", expected "Callable[..., Any]") [return-value] - return cast(Callable, self.apply(lambda self: getattr(self, name))) + f = getattr(type(self._obj_with_exclusions), name) + if not callable(f): + return self.apply(lambda self: getattr(self, name)) - f = getattr(type(self._obj_with_exclusions), name) sig = inspect.signature(f) - def wrapper(*args, **kwargs): - # a little trickery for aggregation functions that need an axis - # argument - if "axis" in sig.parameters: - if kwargs.get("axis", None) is None: - kwargs["axis"] = self.axis - - numeric_only = kwargs.get("numeric_only", lib.no_default) + # a little trickery for aggregation functions that need an axis + # argument + if "axis" in sig.parameters: + if kwargs.get("axis", None) is None or kwargs.get("axis") is lib.no_default: + kwargs["axis"] = self.axis - def curried(x): - with warnings.catch_warnings(): - # Catch any warnings from dispatch to DataFrame; we'll emit - # a warning for groupby below - match = "The default value of numeric_only " - warnings.filterwarnings("ignore", match, FutureWarning) - return f(x, *args, **kwargs) + numeric_only = kwargs.get("numeric_only", lib.no_default) - # preserve the name so we can detect it when calling plot methods, - # to avoid duplicates - curried.__name__ = name - - # special case otherwise extra plots are created when catching the - # exception below - if name in base.plotting_methods: - return self.apply(curried) - - is_transform = name in base.transformation_kernels - - # Transform needs to keep the same schema, including when empty - if is_transform and self._obj_with_exclusions.empty: - return self._obj_with_exclusions - - result = self._python_apply_general( - curried, - self._obj_with_exclusions, - is_transform=is_transform, - not_indexed_same=not is_transform, - ) - - if self._selected_obj.ndim != 1 and self.axis != 1 and result.ndim != 1: - missing = self._obj_with_exclusions.columns.difference(result.columns) - if len(missing) > 0: - warn_dropping_nuisance_columns_deprecated( - type(self), name, numeric_only - ) + def curried(x): + with warnings.catch_warnings(): + # Catch any warnings from dispatch to DataFrame; we'll emit + # a warning for groupby below + match = "The default value of numeric_only " + warnings.filterwarnings("ignore", match, FutureWarning) + return f(x, *args, **kwargs) + + # preserve the name so we can detect it when calling plot methods, + # to avoid duplicates + curried.__name__ = name + + # special case otherwise extra plots are created when catching the + # exception below + if name in base.plotting_methods: + return self.apply(curried) + + is_transform = name in base.transformation_kernels + # Transform needs to keep the same schema, including when empty + if is_transform and self._obj_with_exclusions.empty: + return self._obj_with_exclusions + result = self._python_apply_general( + curried, + self._obj_with_exclusions, + is_transform=is_transform, + not_indexed_same=not is_transform, + ) - if self.grouper.has_dropped_na and is_transform: - # result will have dropped rows due to nans, fill with null - # and ensure index is ordered same as the input - result = self._set_result_index_ordered(result) - return result + if self._selected_obj.ndim != 1 and self.axis != 1 and result.ndim != 1: + missing = self._obj_with_exclusions.columns.difference(result.columns) + if len(missing) > 0: + warn_dropping_nuisance_columns_deprecated( + type(self), name, numeric_only + ) - wrapper.__name__ = name - return wrapper + if self.grouper.has_dropped_na and is_transform: + # result will have dropped rows due to nans, fill with null + # and ensure index is ordered same as the input + result = self._set_result_index_ordered(result) + return result # ----------------------------------------------------------------- # Selection diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index e541abb368a02..b9a7bb271e948 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -35,57 +35,6 @@ ] AGG_FUNCTIONS_WITH_SKIPNA = ["skew", "mad"] -df_allowlist = [ - "quantile", - "fillna", - "mad", - "take", - "idxmax", - "idxmin", - "tshift", - "skew", - "plot", - "hist", - "dtypes", - "corrwith", - "corr", - "cov", - "diff", -] - - -@pytest.fixture(params=df_allowlist) -def df_allowlist_fixture(request): - return request.param - - -s_allowlist = [ - "quantile", - "fillna", - "mad", - "take", - "idxmax", - "idxmin", - "tshift", - "skew", - "plot", - "hist", - "dtype", - "corr", - "cov", - "diff", - "unique", - "nlargest", - "nsmallest", - "is_monotonic_increasing", - "is_monotonic_decreasing", -] - - -@pytest.fixture(params=s_allowlist) -def s_allowlist_fixture(request): - return request.param - @pytest.fixture def df(): @@ -113,54 +62,6 @@ def df_letters(): return df -@pytest.mark.parametrize("allowlist", [df_allowlist, s_allowlist]) -def test_groupby_allowlist(df_letters, allowlist): - df = df_letters - if allowlist == df_allowlist: - # dataframe - obj = df_letters - else: - obj = df_letters["floats"] - - gb = obj.groupby(df.letters) - - assert set(allowlist) == set(gb._apply_allowlist) - - -def check_allowlist(obj, df, m): - # check the obj for a particular allowlist m - - gb = obj.groupby(df.letters) - - f = getattr(type(gb), m) - - # name - try: - n = f.__name__ - except AttributeError: - return - assert n == m - - # qualname - try: - n = f.__qualname__ - except AttributeError: - return - assert n.endswith(m) - - -def test_groupby_series_allowlist(df_letters, s_allowlist_fixture): - m = s_allowlist_fixture - df = df_letters - check_allowlist(df.letters, df, m) - - -def test_groupby_frame_allowlist(df_letters, df_allowlist_fixture): - m = df_allowlist_fixture - df = df_letters - check_allowlist(df, df, m) - - @pytest.fixture def raw_frame(multiindex_dataframe_random_data): df = multiindex_dataframe_random_data diff --git a/pandas/tests/groupby/test_api_consistency.py b/pandas/tests/groupby/test_api_consistency.py new file mode 100644 index 0000000000000..1e82c2b6ac6e2 --- /dev/null +++ b/pandas/tests/groupby/test_api_consistency.py @@ -0,0 +1,136 @@ +""" +Test the consistency of the groupby API, both internally and with other pandas objects. +""" + +import inspect + +import pytest + +from pandas import ( + DataFrame, + Series, +) +from pandas.core.groupby.generic import ( + DataFrameGroupBy, + SeriesGroupBy, +) + + +def test_frame_consistency(request, groupby_func): + # GH#48028 + if groupby_func in ("first", "last"): + msg = "first and last are entirely different between frame and groupby" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + if groupby_func in ("nth", "cumcount", "ngroup"): + msg = "DataFrame has no such method" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + if groupby_func in ("size",): + msg = "Method is a property" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + + frame_method = getattr(DataFrame, groupby_func) + gb_method = getattr(DataFrameGroupBy, groupby_func) + result = set(inspect.signature(gb_method).parameters) + expected = set(inspect.signature(frame_method).parameters) + + # Exclude certain arguments from result and expected depending on the operation + # Some of these may be purposeful inconsistencies between the APIs + exclude_expected, exclude_result = set(), set() + if groupby_func in ("any", "all"): + exclude_expected = {"kwargs", "bool_only", "level", "axis"} + elif groupby_func in ("count",): + exclude_expected = {"numeric_only", "level", "axis"} + elif groupby_func in ("nunique",): + exclude_expected = {"axis"} + elif groupby_func in ("max", "min"): + exclude_expected = {"axis", "kwargs", "level", "skipna"} + exclude_result = {"min_count", "engine", "engine_kwargs"} + elif groupby_func in ("mean", "std", "sum", "var"): + exclude_expected = {"axis", "kwargs", "level", "skipna"} + exclude_result = {"engine", "engine_kwargs"} + elif groupby_func in ("median", "prod", "sem"): + exclude_expected = {"axis", "kwargs", "level", "skipna"} + elif groupby_func in ("backfill", "bfill", "ffill", "pad"): + exclude_expected = {"downcast", "inplace", "axis"} + elif groupby_func in ("cummax", "cummin"): + exclude_expected = {"skipna", "args"} + exclude_result = {"numeric_only"} + elif groupby_func in ("cumprod", "cumsum"): + exclude_expected = {"skipna"} + elif groupby_func in ("pct_change",): + exclude_expected = {"kwargs"} + exclude_result = {"axis"} + elif groupby_func in ("rank",): + exclude_expected = {"numeric_only"} + elif groupby_func in ("quantile",): + exclude_expected = {"method", "axis"} + + # Ensure excluded arguments are actually in the signatures + assert result & exclude_result == exclude_result + assert expected & exclude_expected == exclude_expected + + result -= exclude_result + expected -= exclude_expected + assert result == expected + + +def test_series_consistency(request, groupby_func): + # GH#48028 + if groupby_func in ("first", "last"): + msg = "first and last are entirely different between Series and groupby" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + if groupby_func in ("nth", "cumcount", "ngroup", "corrwith"): + msg = "Series has no such method" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + if groupby_func in ("size",): + msg = "Method is a property" + request.node.add_marker(pytest.mark.xfail(reason=msg)) + + series_method = getattr(Series, groupby_func) + gb_method = getattr(SeriesGroupBy, groupby_func) + result = set(inspect.signature(gb_method).parameters) + expected = set(inspect.signature(series_method).parameters) + + # Exclude certain arguments from result and expected depending on the operation + # Some of these may be purposeful inconsistencies between the APIs + exclude_expected, exclude_result = set(), set() + if groupby_func in ("any", "all"): + exclude_expected = {"kwargs", "bool_only", "level", "axis"} + elif groupby_func in ("count",): + exclude_expected = {"level"} + elif groupby_func in ("tshift",): + exclude_expected = {"axis"} + elif groupby_func in ("diff",): + exclude_result = {"axis"} + elif groupby_func in ("max", "min"): + exclude_expected = {"axis", "kwargs", "level", "skipna"} + exclude_result = {"min_count", "engine", "engine_kwargs"} + elif groupby_func in ("mean", "std", "sum", "var"): + exclude_expected = {"axis", "kwargs", "level", "skipna"} + exclude_result = {"engine", "engine_kwargs"} + elif groupby_func in ("median", "prod", "sem"): + exclude_expected = {"axis", "kwargs", "level", "skipna"} + elif groupby_func in ("backfill", "bfill", "ffill", "pad"): + exclude_expected = {"downcast", "inplace", "axis"} + elif groupby_func in ("cummax", "cummin"): + exclude_expected = {"skipna", "args"} + exclude_result = {"numeric_only"} + elif groupby_func in ("cumprod", "cumsum"): + exclude_expected = {"skipna"} + elif groupby_func in ("pct_change",): + exclude_expected = {"kwargs"} + exclude_result = {"axis"} + elif groupby_func in ("rank",): + exclude_expected = {"numeric_only"} + elif groupby_func in ("idxmin", "idxmax"): + exclude_expected = {"args", "kwargs"} + elif groupby_func in ("quantile",): + exclude_result = {"numeric_only"} + + # Ensure excluded arguments are actually in the signatures + assert result & exclude_result == exclude_result + assert expected & exclude_expected == exclude_expected + + result -= exclude_result + expected -= exclude_expected + assert result == expected diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index 86c945f1321f5..5a9a109d43bf4 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -351,7 +351,7 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]: return decorate -def doc(*docstrings: str | Callable, **params) -> Callable[[F], F]: +def doc(*docstrings: None | str | Callable, **params) -> Callable[[F], F]: """ A decorator take docstring templates, concatenate them and perform string substitution on it. @@ -364,7 +364,7 @@ def doc(*docstrings: str | Callable, **params) -> Callable[[F], F]: Parameters ---------- - *docstrings : str or callable + *docstrings : None, str, or callable The string / docstring / docstring template to be appended in order after default docstring under callable. **params @@ -378,6 +378,8 @@ def decorator(decorated: F) -> F: docstring_components.append(dedent(decorated.__doc__)) for docstring in docstrings: + if docstring is None: + continue if hasattr(docstring, "_docstring_components"): # error: Item "str" of "Union[str, Callable[..., Any]]" has no attribute # "_docstring_components" @@ -389,13 +391,19 @@ def decorator(decorated: F) -> F: elif isinstance(docstring, str) or docstring.__doc__: docstring_components.append(docstring) - # formatting templates and concatenating docstring + params_applied = [ + component.format(**params) + if isinstance(component, str) and len(params) > 0 + else component + for component in docstring_components + ] + decorated.__doc__ = "".join( [ - component.format(**params) + component if isinstance(component, str) else dedent(component.__doc__ or "") - for component in docstring_components + for component in params_applied ] )
- [x] closes #48028 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Currently keeping the docs the same, plan to make groupby-specific docstrings in the future. Note that most of the SeriesGroupBy docs don't make it into the documentation, I've opened #48399. The only change from a user-perspective here should be that Jupyter / IDEs can now get the correct signature (instead of `*args, **kwargs`). ![image](https://user-images.githubusercontent.com/45562402/188480390-ec9f26c3-ec3d-456d-961b-1843713b8679.png) ![image](https://user-images.githubusercontent.com/45562402/188480951-4e679091-0c7a-402b-8c9e-7e8293f793d1.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/48400
2022-09-05T15:48:52Z
2022-09-12T18:21:52Z
2022-09-12T18:21:52Z
2022-10-13T17:00:45Z
WARN: Avoid FutureWarnings in tests
diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 4cf6706707569..3d7e5c6823e9d 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -777,6 +777,6 @@ def test_fillna_nonconsolidated_frame(): ], columns=["i1", "i2", "i3", "f1"], ) - df_nonconsol = df.pivot("i1", "i2") + df_nonconsol = df.pivot(index="i1", columns="i2") result = df_nonconsol.fillna(0) assert result.isna().sum().sum() == 0 diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index a35530100a425..af7a13f6adb5a 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -136,7 +136,8 @@ def test_update_from_non_df(self): def test_update_datetime_tz(self): # GH 25807 result = DataFrame([pd.Timestamp("2019", tz="UTC")]) - result.update(result) + with tm.assert_produces_warning(FutureWarning): + result.update(result) expected = DataFrame([pd.Timestamp("2019", tz="UTC")]) tm.assert_frame_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Would like to backport, otherwise we have to deal with this on the 1.5.x branch
https://api.github.com/repos/pandas-dev/pandas/pulls/48398
2022-09-05T14:50:59Z
2022-09-06T19:47:31Z
2022-09-06T19:47:31Z
2022-09-08T16:28:46Z
WARN: Remove false positive warning for iloc inplaceness
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 1035fd08a1a36..c15e597558221 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -459,7 +459,8 @@ def all_timeseries_index_generator(k: int = 10) -> Iterable[Index]: def make_rand_series(name=None, dtype=np.float64) -> Series: index = makeStringIndex(_N) data = np.random.randn(_N) - data = data.astype(dtype, copy=False) + with np.errstate(invalid="ignore"): + data = data.astype(dtype, copy=False) return Series(data, index=index, name=name) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index f543efe20bf3c..21e04bc1badf3 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1975,7 +1975,10 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: if tipo.kind not in ["i", "u"]: if isinstance(element, np.ndarray) and element.dtype.kind == "f": # If all can be losslessly cast to integers, then we can hold them - casted = element.astype(dtype) + with np.errstate(invalid="ignore"): + # We check afterwards if cast was losslessly, so no need to show + # the warning + casted = element.astype(dtype) comp = casted == element if comp.all(): # Return the casted values bc they can be passed to diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index d415cbd035cd1..09737901cbbc6 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1990,21 +1990,17 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None: self.obj._clear_item_cache() return + self.obj._iset_item(loc, value) + # We will not operate in-place, but will attempt to in the future. # To determine whether we need to issue a FutureWarning, see if the # setting in-place would work, i.e. behavior will change. - if isinstance(value, ABCSeries): - warn = can_hold_element(orig_values, value._values) - else: - warn = can_hold_element(orig_values, value) - # Don't issue the warning yet, as we can still trim a few cases where - # behavior will not change. - - self.obj._iset_item(loc, value) + new_values = self.obj._get_column_array(loc) - if warn: - new_values = self.obj._get_column_array(loc) + if can_hold_element(orig_values, new_values): + # Don't issue the warning yet, as we can still trim a few cases where + # behavior will not change. if ( isinstance(new_values, np.ndarray) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 65ac5e2c2bd1e..7f84d8a367eac 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1326,7 +1326,8 @@ def test_loc_expand_empty_frame_keep_midx_names(self): def test_loc_setitem_rhs_frame(self, idxr, val): # GH#47578 df = DataFrame({"a": [1, 2]}) - df.loc[:, "a"] = DataFrame({"a": [val, 11]}, index=[1, 2]) + with tm.assert_produces_warning(None): + df.loc[:, idxr] = DataFrame({"a": [val, 11]}, index=[1, 2]) expected = DataFrame({"a": [np.nan, val]}) tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py index fc804836f9a9b..9a9fea3462752 100644 --- a/pandas/tests/frame/methods/test_diff.py +++ b/pandas/tests/frame/methods/test_diff.py @@ -82,7 +82,7 @@ def test_diff_datetime_axis0_with_nat(self, tz): expected = Series(ex_index).to_frame() tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize("tz", [None, "UTC"]) + @pytest.mark.parametrize("tz", [pytest.param(None, marks=pytest.mark.xfail), "UTC"]) def test_diff_datetime_with_nat_zero_periods(self, tz): # diff on NaT values should give NaT, not timedelta64(0) dti = date_range("2016-01-01", periods=4, tz=tz) @@ -91,8 +91,7 @@ def test_diff_datetime_with_nat_zero_periods(self, tz): df[1] = ser.copy() - msg = "will attempt to set the values inplace instead" - with tm.assert_produces_warning(FutureWarning, match=msg): + with tm.assert_produces_warning(None): df.iloc[:, 0] = pd.NaT expected = df - df diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index cd6397b053803..2c28800fb181f 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_windows + import pandas as pd from pandas import ( DataFrame, @@ -320,7 +322,9 @@ def test_dup_columns_across_dtype(self): def test_set_value_by_index(self, using_array_manager): # See gh-12344 - warn = FutureWarning if using_array_manager else None + warn = ( + FutureWarning if using_array_manager and not is_platform_windows() else None + ) msg = "will attempt to set the values inplace" df = DataFrame(np.arange(9).reshape(3, 3).T)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This won't be able to set inplace, so should not warn
https://api.github.com/repos/pandas-dev/pandas/pulls/48397
2022-09-05T14:46:29Z
2022-09-16T17:18:43Z
2022-09-16T17:18:43Z
2022-09-16T22:00:10Z
ENH: mask support for hastable functions for indexing
diff --git a/pandas/_libs/hashtable.pxd b/pandas/_libs/hashtable.pxd index 80d7ab58dc559..b32bd4880588d 100644 --- a/pandas/_libs/hashtable.pxd +++ b/pandas/_libs/hashtable.pxd @@ -41,75 +41,123 @@ cdef class HashTable: cdef class UInt64HashTable(HashTable): cdef kh_uint64_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, uint64_t val) cpdef set_item(self, uint64_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Int64HashTable(HashTable): cdef kh_int64_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, int64_t val) cpdef set_item(self, int64_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class UInt32HashTable(HashTable): cdef kh_uint32_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, uint32_t val) cpdef set_item(self, uint32_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Int32HashTable(HashTable): cdef kh_int32_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, int32_t val) cpdef set_item(self, int32_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class UInt16HashTable(HashTable): cdef kh_uint16_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, uint16_t val) cpdef set_item(self, uint16_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Int16HashTable(HashTable): cdef kh_int16_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, int16_t val) cpdef set_item(self, int16_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class UInt8HashTable(HashTable): cdef kh_uint8_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, uint8_t val) cpdef set_item(self, uint8_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Int8HashTable(HashTable): cdef kh_int8_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, int8_t val) cpdef set_item(self, int8_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Float64HashTable(HashTable): cdef kh_float64_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, float64_t val) cpdef set_item(self, float64_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Float32HashTable(HashTable): cdef kh_float32_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, float32_t val) cpdef set_item(self, float32_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Complex64HashTable(HashTable): cdef kh_complex64_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, complex64_t val) cpdef set_item(self, complex64_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class Complex128HashTable(HashTable): cdef kh_complex128_t *table + cdef int64_t na_position + cdef bint uses_mask cpdef get_item(self, complex128_t val) cpdef set_item(self, complex128_t key, Py_ssize_t val) + cpdef get_na(self) + cpdef set_na(self, Py_ssize_t val) cdef class PyObjectHashTable(HashTable): cdef kh_pymap_t *table diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi index 06ff1041d3cf7..e60ccdb29c6b2 100644 --- a/pandas/_libs/hashtable.pyi +++ b/pandas/_libs/hashtable.pyi @@ -110,16 +110,18 @@ class ObjectVector: class HashTable: # NB: The base HashTable class does _not_ actually have these methods; - # we are putting the here for the sake of mypy to avoid + # we are putting them here for the sake of mypy to avoid # reproducing them in each subclass below. - def __init__(self, size_hint: int = ...) -> None: ... + def __init__(self, size_hint: int = ..., uses_mask: bool = ...) -> None: ... def __len__(self) -> int: ... def __contains__(self, key: Hashable) -> bool: ... def sizeof(self, deep: bool = ...) -> int: ... def get_state(self) -> dict[str, int]: ... # TODO: `item` type is subclass-specific def get_item(self, item): ... # TODO: return type? - def set_item(self, item) -> None: ... + def set_item(self, item, val) -> None: ... + def get_na(self): ... # TODO: return type? + def set_na(self, val) -> None: ... def map_locations( self, values: np.ndarray, # np.ndarray[subclass-specific] diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index 54260a9a90964..c6d8783d6f115 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -396,13 +396,16 @@ dtypes = [('Complex128', 'complex128', 'khcomplex128_t', 'to_khcomplex128_t'), cdef class {{name}}HashTable(HashTable): - def __cinit__(self, int64_t size_hint=1): + def __cinit__(self, int64_t size_hint=1, bint uses_mask=False): self.table = kh_init_{{dtype}}() size_hint = min(kh_needed_n_buckets(size_hint), SIZE_HINT_LIMIT) kh_resize_{{dtype}}(self.table, size_hint) + self.uses_mask = uses_mask + self.na_position = -1 + def __len__(self) -> int: - return self.table.size + return self.table.size + (0 if self.na_position == -1 else 1) def __dealloc__(self): if self.table is not NULL: @@ -410,9 +413,15 @@ cdef class {{name}}HashTable(HashTable): self.table = NULL def __contains__(self, object key) -> bool: + # The caller is responsible to check for compatible NA values in case + # of masked arrays. cdef: khiter_t k {{c_type}} ckey + + if self.uses_mask and checknull(key): + return -1 != self.na_position + ckey = {{to_c_type}}(key) k = kh_get_{{dtype}}(self.table, ckey) return k != self.table.n_buckets @@ -435,10 +444,24 @@ cdef class {{name}}HashTable(HashTable): } cpdef get_item(self, {{dtype}}_t val): + """Extracts the position of val from the hashtable. + + Parameters + ---------- + val : Scalar + The value that is looked up in the hashtable + + Returns + ------- + The position of the requested integer. + """ + # Used in core.sorting, IndexEngine.get_loc + # Caller is responsible for checking for pd.NA cdef: khiter_t k {{c_type}} cval + cval = {{to_c_type}}(val) k = kh_get_{{dtype}}(self.table, cval) if k != self.table.n_buckets: @@ -446,12 +469,29 @@ cdef class {{name}}HashTable(HashTable): else: raise KeyError(val) + cpdef get_na(self): + """Extracts the position of na_value from the hashtable. + + Returns + ------- + The position of the last na value. + """ + + if not self.uses_mask: + raise NotImplementedError + + if self.na_position == -1: + raise KeyError("NA") + return self.na_position + cpdef set_item(self, {{dtype}}_t key, Py_ssize_t val): # Used in libjoin + # Caller is responsible for checking for pd.NA cdef: khiter_t k int ret = 0 {{c_type}} ckey + ckey = {{to_c_type}}(key) k = kh_put_{{dtype}}(self.table, ckey, &ret) if kh_exist_{{dtype}}(self.table, k): @@ -459,6 +499,18 @@ cdef class {{name}}HashTable(HashTable): else: raise KeyError(key) + cpdef set_na(self, Py_ssize_t val): + # Caller is responsible for checking for pd.NA + cdef: + khiter_t k + int ret = 0 + {{c_type}} ckey + + if not self.uses_mask: + raise NotImplementedError + + self.na_position = val + {{if dtype == "int64" }} # We only use this for int64, can reduce build size and make .pyi # more accurate by only implementing it for int64 @@ -480,22 +532,36 @@ cdef class {{name}}HashTable(HashTable): {{endif}} @cython.boundscheck(False) - def map_locations(self, const {{dtype}}_t[:] values) -> None: + def map_locations(self, const {{dtype}}_t[:] values, const uint8_t[:] mask = None) -> None: # Used in libindex, safe_sort cdef: Py_ssize_t i, n = len(values) int ret = 0 {{c_type}} val khiter_t k + int8_t na_position = self.na_position + + if self.uses_mask and mask is None: + raise NotImplementedError # pragma: no cover with nogil: - for i in range(n): - val= {{to_c_type}}(values[i]) - k = kh_put_{{dtype}}(self.table, val, &ret) - self.table.vals[k] = i + if self.uses_mask: + for i in range(n): + if mask[i]: + na_position = i + else: + val= {{to_c_type}}(values[i]) + k = kh_put_{{dtype}}(self.table, val, &ret) + self.table.vals[k] = i + else: + for i in range(n): + val= {{to_c_type}}(values[i]) + k = kh_put_{{dtype}}(self.table, val, &ret) + self.table.vals[k] = i + self.na_position = na_position @cython.boundscheck(False) - def lookup(self, const {{dtype}}_t[:] values) -> ndarray: + def lookup(self, const {{dtype}}_t[:] values, const uint8_t[:] mask = None) -> ndarray: # -> np.ndarray[np.intp] # Used in safe_sort, IndexEngine.get_indexer cdef: @@ -504,15 +570,22 @@ cdef class {{name}}HashTable(HashTable): {{c_type}} val khiter_t k intp_t[::1] locs = np.empty(n, dtype=np.intp) + int8_t na_position = self.na_position + + if self.uses_mask and mask is None: + raise NotImplementedError # pragma: no cover with nogil: for i in range(n): - val = {{to_c_type}}(values[i]) - k = kh_get_{{dtype}}(self.table, val) - if k != self.table.n_buckets: - locs[i] = self.table.vals[k] + if self.uses_mask and mask[i]: + locs[i] = na_position else: - locs[i] = -1 + val = {{to_c_type}}(values[i]) + k = kh_get_{{dtype}}(self.table, val) + if k != self.table.n_buckets: + locs[i] = self.table.vals[k] + else: + locs[i] = -1 return np.asarray(locs) diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py index 0cd340ab80897..d9d281a0759da 100644 --- a/pandas/tests/libs/test_hashtable.py +++ b/pandas/tests/libs/test_hashtable.py @@ -1,4 +1,5 @@ from contextlib import contextmanager +import re import struct import tracemalloc from typing import Generator @@ -76,6 +77,49 @@ def test_get_set_contains_len(self, table_type, dtype): assert table.get_item(index + 1) == 41 assert index + 2 not in table + table.set_item(index + 1, 21) + assert index in table + assert index + 1 in table + assert len(table) == 2 + assert table.get_item(index) == 21 + assert table.get_item(index + 1) == 21 + + with pytest.raises(KeyError, match=str(index + 2)): + table.get_item(index + 2) + + def test_get_set_contains_len_mask(self, table_type, dtype): + if table_type == ht.PyObjectHashTable: + pytest.skip("Mask not supported for object") + index = 5 + table = table_type(55, uses_mask=True) + assert len(table) == 0 + assert index not in table + + table.set_item(index, 42) + assert len(table) == 1 + assert index in table + assert table.get_item(index) == 42 + with pytest.raises(KeyError, match="NA"): + table.get_na() + + table.set_item(index + 1, 41) + table.set_na(41) + assert pd.NA in table + assert index in table + assert index + 1 in table + assert len(table) == 3 + assert table.get_item(index) == 42 + assert table.get_item(index + 1) == 41 + assert table.get_na() == 41 + + table.set_na(21) + assert index in table + assert index + 1 in table + assert len(table) == 3 + assert table.get_item(index + 1) == 41 + assert table.get_na() == 21 + assert index + 2 not in table + with pytest.raises(KeyError, match=str(index + 2)): table.get_item(index + 2) @@ -101,6 +145,22 @@ def test_map_locations(self, table_type, dtype, writable): for i in range(N): assert table.get_item(keys[i]) == i + def test_map_locations_mask(self, table_type, dtype, writable): + if table_type == ht.PyObjectHashTable: + pytest.skip("Mask not supported for object") + N = 3 + table = table_type(uses_mask=True) + keys = (np.arange(N) + N).astype(dtype) + keys.flags.writeable = writable + table.map_locations(keys, np.array([False, False, True])) + for i in range(N - 1): + assert table.get_item(keys[i]) == i + + with pytest.raises(KeyError, match=re.escape(str(keys[N - 1]))): + table.get_item(keys[N - 1]) + + assert table.get_na() == 2 + def test_lookup(self, table_type, dtype, writable): N = 3 table = table_type() @@ -123,6 +183,24 @@ def test_lookup_wrong(self, table_type, dtype): result = table.lookup(wrong_keys) assert np.all(result == -1) + def test_lookup_mask(self, table_type, dtype, writable): + if table_type == ht.PyObjectHashTable: + pytest.skip("Mask not supported for object") + N = 3 + table = table_type(uses_mask=True) + keys = (np.arange(N) + N).astype(dtype) + mask = np.array([False, True, False]) + keys.flags.writeable = writable + table.map_locations(keys, mask) + result = table.lookup(keys, mask) + expected = np.arange(N) + tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64)) + + result = table.lookup(np.array([1 + N]).astype(dtype), np.array([False])) + tm.assert_numpy_array_equal( + result.astype(np.int64), np.array([-1], dtype=np.int64) + ) + def test_unique(self, table_type, dtype, writable): if dtype in (np.int8, np.uint8): N = 88 diff --git a/scripts/run_stubtest.py b/scripts/run_stubtest.py index d90f8575234e8..db7a327f231b5 100644 --- a/scripts/run_stubtest.py +++ b/scripts/run_stubtest.py @@ -36,10 +36,12 @@ "pandas._libs.hashtable.HashTable.factorize", "pandas._libs.hashtable.HashTable.get_item", "pandas._libs.hashtable.HashTable.get_labels", + "pandas._libs.hashtable.HashTable.get_na", "pandas._libs.hashtable.HashTable.get_state", "pandas._libs.hashtable.HashTable.lookup", "pandas._libs.hashtable.HashTable.map_locations", "pandas._libs.hashtable.HashTable.set_item", + "pandas._libs.hashtable.HashTable.set_na", "pandas._libs.hashtable.HashTable.sizeof", "pandas._libs.hashtable.HashTable.unique", # stubtest might be too sensitive
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This is a first step towards creating a MaskedEngine to optimise performance in these cases. This supports masks in the HashTable. Did not impact performance of non masked cases. cc @jorisvandenbossche As a precursor to a MaskedEngine we have to adjust the HashTable methods to support masked na values. They keep track of seen na values separately. I think this makes more sense than keeping track of the NAs on the Engine level ``map_locations`` and ``lookup`` are normally called when the values are unique or used to check if the values are unique. Nevertheless, if they have duplicate values, they always return the index of the last occurrence of a specific value. This is the same in ``get_item`` and ``set_item``. We have to adjust the length of the HashTable, because the length is used to check if the values were unique.
https://api.github.com/repos/pandas-dev/pandas/pulls/48396
2022-09-05T14:30:30Z
2022-10-20T16:32:49Z
2022-10-20T16:32:49Z
2022-10-25T16:25:48Z
ENH: raise_assert_detail shows the difference between the columns
diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index ee5085fd9ad89..5c4de03cb8a10 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -29,6 +29,7 @@ enhancement2 Other enhancements ^^^^^^^^^^^^^^^^^^ - :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support an ``axis`` argument. If ``axis`` is set, the default behaviour of which axis to consider can be overwritten (:issue:`47819`) +- :func:`assert_frame_equal` now shows the first element where the DataFrames differ, analogously to ``pytest``'s output (:issue:`47910`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/testing.pyx b/pandas/_libs/testing.pyx index cfe9f40f12452..e710a6fb6b24e 100644 --- a/pandas/_libs/testing.pyx +++ b/pandas/_libs/testing.pyx @@ -91,6 +91,7 @@ cpdef assert_almost_equal(a, b, Py_ssize_t i, na, nb double fa, fb bint is_unequal = False, a_is_ndarray, b_is_ndarray + str first_diff = '' if lobj is None: lobj = a @@ -159,12 +160,14 @@ cpdef assert_almost_equal(a, b, except AssertionError: is_unequal = True diff += 1 + if not first_diff: + first_diff = f"At positional index {i}, first diff: {a[i]} != {b[i]}" if is_unequal: from pandas._testing import raise_assert_detail msg = (f"{obj} values are different " f"({np.round(diff * 100.0 / na, 5)} %)") - raise_assert_detail(obj, msg, lobj, robj, index_values=index_values) + raise_assert_detail(obj, msg, lobj, robj, first_diff=first_diff, index_values=index_values) return True diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 945639ef4b00a..3858670850074 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -639,7 +639,9 @@ def assert_timedelta_array_equal( assert_attr_equal("freq", left, right, obj=obj) -def raise_assert_detail(obj, message, left, right, diff=None, index_values=None): +def raise_assert_detail( + obj, message, left, right, diff=None, first_diff=None, index_values=None +): __tracebackhide__ = True msg = f"""{obj} are different @@ -674,6 +676,9 @@ def raise_assert_detail(obj, message, left, right, diff=None, index_values=None) if diff is not None: msg += f"\n[diff]: {diff}" + if first_diff is not None: + msg += f"\n{first_diff}" + raise AssertionError(msg) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 6ff1a1c17b179..8139ffed78f7f 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -151,7 +151,8 @@ def test_frame_equal_index_mismatch(check_like, obj_fixture): {obj_fixture}\\.index values are different \\(33\\.33333 %\\) \\[left\\]: Index\\(\\['a', 'b', 'c'\\], dtype='object'\\) -\\[right\\]: Index\\(\\['a', 'b', 'd'\\], dtype='object'\\)""" +\\[right\\]: Index\\(\\['a', 'b', 'd'\\], dtype='object'\\) +At positional index 2, first diff: c != d""" df1 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "c"]) df2 = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=["a", "b", "d"])
- [x] xref https://github.com/pandas-dev/pandas/pull/48033 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This idea came out of https://github.com/pandas-dev/pandas/pull/48033 , so I'm opening a PR to see if anyone else would like to see this --- Adding an extra `At index {idx}, diff: {left} != {right}`, analougously to pytest's output Demo: ```python import pandas as pd import numpy as np a = np.random.randint(0, 10, size=200) b = np.random.randint(0, 10, size=200) df1 = pd.DataFrame({'a': a, 'b': b}) df2 = pd.DataFrame({'a': a, 'b': b}) df2.loc[97, 'b'] = 42 pd.testing.assert_frame_equal(df1, df2) ``` outputs ``` AssertionError: DataFrame.iloc[:, 1] (column name="b") are different DataFrame.iloc[:, 1] (column name="b") values are different (0.5 %) [index]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, ...] [left]: [1, 4, 3, 6, 4, 7, 2, 5, 3, 6, 6, 9, 8, 4, 4, 4, 7, 8, 4, 0, 3, 1, 4, 5, 7, 0, 3, 0, 9, 9, 6, 1, 7, 7, 4, 7, 6, 2, 3, 9, 1, 5, 1, 7, 2, 3, 8, 9, 5, 3, 6, 3, 7, 3, 4, 1, 7, 3, 6, 9, 0, 0, 7, 3, 6, 4, 4, 1, 0, 8, 0, 1, 8, 2, 8, 1, 8, 8, 8, 3, 8, 3, 8, 5, 7, 0, 0, 2, 8, 5, 3, 4, 7, 1, 6, 3, 5, 9, 7, 8, ...] [right]: [1, 4, 3, 6, 4, 7, 2, 5, 3, 6, 6, 9, 8, 4, 4, 4, 7, 8, 4, 0, 3, 1, 4, 5, 7, 0, 3, 0, 9, 9, 6, 1, 7, 7, 4, 7, 6, 2, 3, 9, 1, 5, 1, 7, 2, 3, 8, 9, 5, 3, 6, 3, 7, 3, 4, 1, 7, 3, 6, 9, 0, 0, 7, 3, 6, 4, 4, 1, 0, 8, 0, 1, 8, 2, 8, 1, 8, 8, 8, 3, 8, 3, 8, 5, 7, 0, 0, 2, 8, 5, 3, 4, 7, 1, 6, 3, 5, 42, 7, 8, ...] At positional index 97 diff: 9 != 42 ``` This is analogous to how `pytest` shows diffs between lists: ``` def test_me(): a = [1, 2, 3] b = [4, 5, 6] > assert a == b E assert [1, 2, 3] == [4, 5, 6] E At index 0 diff: 1 != 4 E Use -v to get more diff ```
https://api.github.com/repos/pandas-dev/pandas/pulls/48390
2022-09-04T21:23:53Z
2022-09-12T16:56:20Z
2022-09-12T16:56:20Z
2022-10-13T17:00:44Z
TST: add tests for parser functions being pickle-able.
diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index e9e99f6dd0ad7..3f95dd616a09c 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -12,6 +12,7 @@ import mmap import os from pathlib import Path +import pickle import tempfile import pytest @@ -604,3 +605,23 @@ def close(self): with BytesIO() as buffer: with icom.get_handle(buffer, "rb") as handles: handles.created_handles.append(TestError()) + + +@pytest.mark.parametrize( + "reader", + [ + pd.read_csv, + pd.read_fwf, + pd.read_excel, + pd.read_feather, + pd.read_hdf, + pd.read_stata, + pd.read_sas, + pd.read_json, + pd.read_pickle, + ], +) +def test_pickle_reader(reader): + # GH 22265 + with BytesIO() as buffer: + pickle.dump(reader, buffer)
- [x] closes #22265 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/48389
2022-09-04T19:09:59Z
2022-09-06T17:44:13Z
2022-09-06T17:44:13Z
2022-10-13T17:00:43Z
ENH: Suppport masks in median groupby algo
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 90cb31577a1b4..3007d2d1e126c 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -5,6 +5,7 @@ import numpy as np from pandas import ( + NA, Categorical, DataFrame, Index, @@ -592,6 +593,7 @@ def setup(self, dtype, method): columns=list("abcdefghij"), dtype=dtype, ) + df.loc[list(range(1, N, 5)), list("abcdefghij")] = NA df["key"] = np.random.randint(0, 100, size=N) self.df = df diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index 848e87f0bc029..1a159ce7670c8 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -100,6 +100,7 @@ Deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ +- Performance improvement in :meth:`.GroupBy.median` for nullable dtypes (:issue:`37493`) - Performance improvement in :meth:`.GroupBy.mean` and :meth:`.GroupBy.var` for extension array dtypes (:issue:`37493`) - Performance improvement for :meth:`MultiIndex.unique` (:issue:`48335`) - diff --git a/pandas/_libs/groupby.pyi b/pandas/_libs/groupby.pyi index 8722092809ed9..93f861eef1baf 100644 --- a/pandas/_libs/groupby.pyi +++ b/pandas/_libs/groupby.pyi @@ -10,6 +10,8 @@ def group_median_float64( values: np.ndarray, # ndarray[float64_t, ndim=2] labels: npt.NDArray[np.int64], min_count: int = ..., # Py_ssize_t + mask: np.ndarray | None = ..., + result_mask: np.ndarray | None = ..., ) -> None: ... def group_cumprod_float64( out: np.ndarray, # float64_t[:, ::1] diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 0c368f9421932..5ba8fba4543d6 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -41,6 +41,7 @@ from pandas._libs.algos import ( ensure_platform_int, groupsort_indexer, rank_1d, + take_2d_axis1_bool_bool, take_2d_axis1_float64_float64, ) @@ -64,11 +65,48 @@ cdef enum InterpolationEnumType: INTERPOLATION_MIDPOINT -cdef inline float64_t median_linear(float64_t* a, int n) nogil: +cdef inline float64_t median_linear_mask(float64_t* a, int n, uint8_t* mask) nogil: cdef: int i, j, na_count = 0 + float64_t* tmp float64_t result + + if n == 0: + return NaN + + # count NAs + for i in range(n): + if mask[i]: + na_count += 1 + + if na_count: + if na_count == n: + return NaN + + tmp = <float64_t*>malloc((n - na_count) * sizeof(float64_t)) + + j = 0 + for i in range(n): + if not mask[i]: + tmp[j] = a[i] + j += 1 + + a = tmp + n -= na_count + + result = calc_median_linear(a, n, na_count) + + if na_count: + free(a) + + return result + + +cdef inline float64_t median_linear(float64_t* a, int n) nogil: + cdef: + int i, j, na_count = 0 float64_t* tmp + float64_t result if n == 0: return NaN @@ -93,18 +131,34 @@ cdef inline float64_t median_linear(float64_t* a, int n) nogil: a = tmp n -= na_count + result = calc_median_linear(a, n, na_count) + + if na_count: + free(a) + + return result + + +cdef inline float64_t calc_median_linear(float64_t* a, int n, int na_count) nogil: + cdef: + float64_t result + if n % 2: result = kth_smallest_c(a, n // 2, n) else: result = (kth_smallest_c(a, n // 2, n) + kth_smallest_c(a, n // 2 - 1, n)) / 2 - if na_count: - free(a) - return result +ctypedef fused int64float_t: + int64_t + uint64_t + float32_t + float64_t + + @cython.boundscheck(False) @cython.wraparound(False) def group_median_float64( @@ -113,6 +167,8 @@ def group_median_float64( ndarray[float64_t, ndim=2] values, ndarray[intp_t] labels, Py_ssize_t min_count=-1, + const uint8_t[:, :] mask=None, + uint8_t[:, ::1] result_mask=None, ) -> None: """ Only aggregates on axis=0 @@ -121,8 +177,12 @@ def group_median_float64( Py_ssize_t i, j, N, K, ngroups, size ndarray[intp_t] _counts ndarray[float64_t, ndim=2] data + ndarray[uint8_t, ndim=2] data_mask ndarray[intp_t] indexer float64_t* ptr + uint8_t* ptr_mask + float64_t result + bint uses_mask = mask is not None assert min_count == -1, "'min_count' only used in sum and prod" @@ -137,15 +197,38 @@ def group_median_float64( take_2d_axis1_float64_float64(values.T, indexer, out=data) - with nogil: + if uses_mask: + data_mask = np.empty((K, N), dtype=np.uint8) + ptr_mask = <uint8_t *>cnp.PyArray_DATA(data_mask) + + take_2d_axis1_bool_bool(mask.T, indexer, out=data_mask, fill_value=1) - for i in range(K): - # exclude NA group - ptr += _counts[0] - for j in range(ngroups): - size = _counts[j + 1] - out[j, i] = median_linear(ptr, size) - ptr += size + with nogil: + + for i in range(K): + # exclude NA group + ptr += _counts[0] + ptr_mask += _counts[0] + + for j in range(ngroups): + size = _counts[j + 1] + result = median_linear_mask(ptr, size, ptr_mask) + out[j, i] = result + + if result != result: + result_mask[j, i] = 1 + ptr += size + ptr_mask += size + + else: + with nogil: + for i in range(K): + # exclude NA group + ptr += _counts[0] + for j in range(ngroups): + size = _counts[j + 1] + out[j, i] = median_linear(ptr, size) + ptr += size @cython.boundscheck(False) @@ -206,13 +289,6 @@ def group_cumprod_float64( accum[lab, j] = NaN -ctypedef fused int64float_t: - int64_t - uint64_t - float32_t - float64_t - - @cython.boundscheck(False) @cython.wraparound(False) def group_cumsum( diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index c118c7f16af8f..04960379fbc42 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -162,6 +162,7 @@ def __init__(self, kind: str, how: str, has_dropped_na: bool) -> None: "prod", "mean", "var", + "median", } _cython_arity = {"ohlc": 4} # OHLC @@ -600,7 +601,7 @@ def _call_cython_op( min_count=min_count, is_datetimelike=is_datetimelike, ) - elif self.how in ["var", "ohlc", "prod"]: + elif self.how in ["var", "ohlc", "prod", "median"]: func( result, counts,
- [x] xref #37493 (Replace xxxx with the Github issue number) - [] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Only a small speed up (5-10%, depending on the number of NAs). In general, this is needed to streamline the code base in ops.py after everything supports masks.
https://api.github.com/repos/pandas-dev/pandas/pulls/48387
2022-09-04T16:23:27Z
2022-09-06T20:03:19Z
2022-09-06T20:03:19Z
2022-10-13T17:00:43Z
CLN/DOC: Adjust xpath validation and error messaging in read_xml with IO tools doc note and example
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 7a7e518e1f7db..15b3b894c68b6 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -3174,6 +3174,42 @@ But assigning *any* temporary name to correct URI allows parsing by nodes. However, if XPath does not reference node names such as default, ``/*``, then ``namespaces`` is not required. +.. note:: + + Since ``xpath`` identifies the parent of content to be parsed, only immediate + desendants which include child nodes or current attributes are parsed. + Therefore, ``read_xml`` will not parse the text of grandchildren or other + descendants and will not parse attributes of any descendant. To retrieve + lower level content, adjust xpath to lower level. For example, + + .. ipython:: python + :okwarning: + + xml = """ + <data> + <row> + <shape sides="4">square</shape> + <degrees>360</degrees> + </row> + <row> + <shape sides="0">circle</shape> + <degrees>360</degrees> + </row> + <row> + <shape sides="3">triangle</shape> + <degrees>180</degrees> + </row> + </data>""" + + df = pd.read_xml(xml, xpath="./row") + df + + shows the attribute ``sides`` on ``shape`` element was not parsed as + expected since this attribute resides on the child of ``row`` element + and not ``row`` element itself. In other words, ``sides`` attribute is a + grandchild level descendant of ``row`` element. However, the ``xpath`` + targets ``row`` element which covers only its children and attributes. + With `lxml`_ as parser, you can flatten nested XML documents with an XSLT script which also can be string/file/URL types. As background, `XSLT`_ is a special-purpose language written in a special XML file that can transform diff --git a/pandas/io/xml.py b/pandas/io/xml.py index fbe3e41be88a9..71d19b7861fc2 100644 --- a/pandas/io/xml.py +++ b/pandas/io/xml.py @@ -387,7 +387,7 @@ def _iterparse_nodes(self, iterparse: Callable) -> list[dict[str, str | None]]: return dicts - def _validate_path(self) -> None: + def _validate_path(self) -> list[Any]: """ Validate xpath. @@ -446,8 +446,7 @@ def parse_data(self) -> list[dict[str, str | None]]: if self.iterparse is None: self.xml_doc = self._parse_doc(self.path_or_buffer) - self._validate_path() - elems = self.xml_doc.findall(self.xpath, namespaces=self.namespaces) + elems = self._validate_path() self._validate_names() @@ -459,7 +458,7 @@ def parse_data(self) -> list[dict[str, str | None]]: return xml_dicts - def _validate_path(self) -> None: + def _validate_path(self) -> list[Any]: """ Notes ----- @@ -468,18 +467,28 @@ def _validate_path(self) -> None: """ msg = ( - "xpath does not return any nodes. " + "xpath does not return any nodes or attributes. " + "Be sure to specify in `xpath` the parent nodes of " + "children and attributes to parse. " "If document uses namespaces denoted with " "xmlns, be sure to define namespaces and " "use them in xpath." ) try: - elems = self.xml_doc.find(self.xpath, namespaces=self.namespaces) + elems = self.xml_doc.findall(self.xpath, namespaces=self.namespaces) + children = [ch for el in elems for ch in el.findall("*")] + attrs = {k: v for el in elems for k, v in el.attrib.items()} + if elems is None: raise ValueError(msg) - if elems is not None and elems.find("*") is None and elems.attrib is None: - raise ValueError(msg) + if elems is not None: + if self.elems_only and children == []: + raise ValueError(msg) + elif self.attrs_only and attrs == {}: + raise ValueError(msg) + elif children == [] and attrs == {}: + raise ValueError(msg) except (KeyError, SyntaxError): raise SyntaxError( @@ -488,6 +497,8 @@ def _validate_path(self) -> None: "undeclared namespace prefix." ) + return elems + def _validate_names(self) -> None: children: list[Any] @@ -554,8 +565,7 @@ def parse_data(self) -> list[dict[str, str | None]]: self.xsl_doc = self._parse_doc(self.stylesheet) self.xml_doc = self._transform_doc() - self._validate_path() - elems = self.xml_doc.xpath(self.xpath, namespaces=self.namespaces) + elems = self._validate_path() self._validate_names() @@ -567,25 +577,33 @@ def parse_data(self) -> list[dict[str, str | None]]: return xml_dicts - def _validate_path(self) -> None: + def _validate_path(self) -> list[Any]: msg = ( - "xpath does not return any nodes. " - "Be sure row level nodes are in xpath. " + "xpath does not return any nodes or attributes. " + "Be sure to specify in `xpath` the parent nodes of " + "children and attributes to parse. " "If document uses namespaces denoted with " "xmlns, be sure to define namespaces and " "use them in xpath." ) elems = self.xml_doc.xpath(self.xpath, namespaces=self.namespaces) - children = self.xml_doc.xpath(self.xpath + "/*", namespaces=self.namespaces) - attrs = self.xml_doc.xpath(self.xpath + "/@*", namespaces=self.namespaces) + children = [ch for el in elems for ch in el.xpath("*")] + attrs = {k: v for el in elems for k, v in el.attrib.items()} if elems == []: raise ValueError(msg) - if elems != [] and attrs == [] and children == []: - raise ValueError(msg) + if elems != []: + if self.elems_only and children == []: + raise ValueError(msg) + elif self.attrs_only and attrs == {}: + raise ValueError(msg) + elif children == [] and attrs == {}: + raise ValueError(msg) + + return elems def _validate_names(self) -> None: children: list[Any] diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index fd4ba87bd302c..935a44d0e0901 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -760,6 +760,45 @@ def test_elem_and_attrs_only(datapath, parser): read_xml(filename, elems_only=True, attrs_only=True, parser=parser) +def test_empty_attrs_only(parser): + xml = """ + <data> + <row> + <shape sides="4">square</shape> + <degrees>360</degrees> + </row> + <row> + <shape sides="0">circle</shape> + <degrees>360</degrees> + </row> + <row> + <shape sides="3">triangle</shape> + <degrees>180</degrees> + </row> + </data>""" + + with pytest.raises( + ValueError, + match=("xpath does not return any nodes or attributes"), + ): + read_xml(xml, xpath="./row", attrs_only=True, parser=parser) + + +def test_empty_elems_only(parser): + xml = """ + <data> + <row sides="4" shape="square" degrees="360"/> + <row sides="0" shape="circle" degrees="360"/> + <row sides="3" shape="triangle" degrees="180"/> + </data>""" + + with pytest.raises( + ValueError, + match=("xpath does not return any nodes or attributes"), + ): + read_xml(xml, xpath="./row", elems_only=True, parser=parser) + + @td.skip_if_no("lxml") def test_attribute_centric_xml(): xml = """\
- [X] closes #48181 - [X] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [X] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48386
2022-09-04T16:02:27Z
2022-09-06T20:08:49Z
2022-09-06T20:08:49Z
2022-10-29T17:39:18Z
CLN: assorted
diff --git a/pandas/_libs/tslibs/offsets.pyi b/pandas/_libs/tslibs/offsets.pyi index c3d550c7a5ba9..0390aad23d83a 100644 --- a/pandas/_libs/tslibs/offsets.pyi +++ b/pandas/_libs/tslibs/offsets.pyi @@ -81,6 +81,7 @@ class BaseOffset: @property def freqstr(self) -> str: ... def apply_index(self, dtindex: DatetimeIndex) -> DatetimeIndex: ... + def _apply(self, other): ... def _apply_array(self, dtarr) -> None: ... def rollback(self, dt: datetime) -> datetime: ... def rollforward(self, dt: datetime) -> datetime: ... diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 565c887d1f40c..7be7381bcb4d1 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -681,6 +681,9 @@ cdef class BaseOffset: res = self._apply_array(dtindex) return type(dtindex)(res) + def _apply(self, other): + raise NotImplementedError("implemented by subclasses") + @apply_array_wraps def _apply_array(self, dtarr): raise NotImplementedError( diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 28cde46a03758..e96e9b44112d6 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -77,7 +77,6 @@ from pandas.tseries.frequencies import get_period_alias from pandas.tseries.offsets import ( - BDay, Day, Tick, ) @@ -395,7 +394,9 @@ def _generate_range( if isinstance(freq, Tick): i8values = generate_regular_range(start, end, periods, freq) else: - xdr = generate_range(start=start, end=end, periods=periods, offset=freq) + xdr = _generate_range( + start=start, end=end, periods=periods, offset=freq + ) i8values = np.array([x.value for x in xdr], dtype=np.int64) endpoint_tz = start.tz if start is not None else end.tz @@ -2494,7 +2495,12 @@ def _maybe_localize_point(ts, is_none, is_not_none, freq, tz, ambiguous, nonexis return ts -def generate_range(start=None, end=None, periods=None, offset=BDay()): +def _generate_range( + start: Timestamp | None, + end: Timestamp | None, + periods: int | None, + offset: BaseOffset, +): """ Generates a sequence of dates corresponding to the specified time offset. Similar to dateutil.rrule except uses pandas DateOffset @@ -2502,10 +2508,10 @@ def generate_range(start=None, end=None, periods=None, offset=BDay()): Parameters ---------- - start : datetime, (default None) - end : datetime, (default None) - periods : int, (default None) - offset : DateOffset, (default BDay()) + start : Timestamp or None + end : Timestamp or None + periods : int or None + offset : DateOffset, Notes ----- @@ -2520,26 +2526,46 @@ def generate_range(start=None, end=None, periods=None, offset=BDay()): """ offset = to_offset(offset) - start = Timestamp(start) - start = start if start is not NaT else None - end = Timestamp(end) - end = end if end is not NaT else None + # Argument 1 to "Timestamp" has incompatible type "Optional[Timestamp]"; + # expected "Union[integer[Any], float, str, date, datetime64]" + start = Timestamp(start) # type: ignore[arg-type] + # Non-overlapping identity check (left operand type: "Timestamp", right + # operand type: "NaTType") + start = start if start is not NaT else None # type: ignore[comparison-overlap] + # Argument 1 to "Timestamp" has incompatible type "Optional[Timestamp]"; + # expected "Union[integer[Any], float, str, date, datetime64]" + end = Timestamp(end) # type: ignore[arg-type] + # Non-overlapping identity check (left operand type: "Timestamp", right + # operand type: "NaTType") + end = end if end is not NaT else None # type: ignore[comparison-overlap] if start and not offset.is_on_offset(start): - start = offset.rollforward(start) + # Incompatible types in assignment (expression has type "datetime", + # variable has type "Optional[Timestamp]") + start = offset.rollforward(start) # type: ignore[assignment] elif end and not offset.is_on_offset(end): - end = offset.rollback(end) + # Incompatible types in assignment (expression has type "datetime", + # variable has type "Optional[Timestamp]") + end = offset.rollback(end) # type: ignore[assignment] - if periods is None and end < start and offset.n >= 0: + # Unsupported operand types for < ("Timestamp" and "None") + if periods is None and end < start and offset.n >= 0: # type: ignore[operator] end = None periods = 0 if end is None: - end = start + (periods - 1) * offset + # error: No overload variant of "__radd__" of "BaseOffset" matches + # argument type "None" + end = start + (periods - 1) * offset # type: ignore[operator] if start is None: - start = end - (periods - 1) * offset + # error: No overload variant of "__radd__" of "BaseOffset" matches + # argument type "None" + start = end - (periods - 1) * offset # type: ignore[operator] + + start = cast(Timestamp, start) + end = cast(Timestamp, end) cur = start if offset.n >= 0: diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 7f896c5334313..91eeee936cba1 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -172,7 +172,7 @@ class PeriodArray(dtl.DatelikeOps, libperiod.PeriodMixin): _typ = "periodarray" # ABCPeriodArray _internal_fill_value = np.int64(iNaT) _recognized_scalars = (Period,) - _is_recognized_dtype = is_period_dtype + _is_recognized_dtype = is_period_dtype # check_compatible_with checks freq match _infer_matches = ("period",) @property diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2dfa505bc4932..f8aafa6e9cd8b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1917,7 +1917,7 @@ def _drop_labels_or_levels(self, keys, axis: int = 0): # Perform copy upfront and then use inplace operations below. # This ensures that we always perform exactly one copy. # ``copy`` and/or ``inplace`` options could be added in the future. - dropped = self.copy() + dropped = self.copy(deep=False) if axis == 0: # Handle dropping index levels diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 27ca114519f77..d415cbd035cd1 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -955,8 +955,6 @@ def _getitem_lowerdim(self, tup: tuple): # is equivalent. # (see the other place where we call _handle_lowerdim_multi_index_axis0) with suppress(IndexingError): - # error "_LocationIndexer" has no attribute - # "_handle_lowerdim_multi_index_axis0" return cast(_LocIndexer, self)._handle_lowerdim_multi_index_axis0(tup) tup = self._validate_key_length(tup) @@ -1013,8 +1011,6 @@ def _getitem_nested_tuple(self, tup: tuple): # DataFrame, IndexingError is not raised when slice(None,None,None) # with one row. with suppress(IndexingError): - # error "_LocationIndexer" has no attribute - # "_handle_lowerdim_multi_index_axis0" return cast(_LocIndexer, self)._handle_lowerdim_multi_index_axis0( tup ) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index c8bc9efd824b2..ba84c8b364be7 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -455,7 +455,7 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: if upcasted_na is None and self.block.dtype.kind != "V": # No upcasting is necessary fill_value = self.block.fill_value - values = self.block.get_values() + values = self.block.values else: fill_value = upcasted_na diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 377974a918ad9..5f4f941057b55 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -34,7 +34,7 @@ offsets, ) import pandas._testing as tm -from pandas.core.arrays.datetimes import generate_range +from pandas.core.arrays.datetimes import _generate_range as generate_range START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) @@ -840,27 +840,45 @@ def test_date_range_with_tz(self, tzstr): class TestGenRangeGeneration: def test_generate(self): - rng1 = list(generate_range(START, END, offset=BDay())) - rng2 = list(generate_range(START, END, offset="B")) + rng1 = list(generate_range(START, END, periods=None, offset=BDay())) + rng2 = list(generate_range(START, END, periods=None, offset="B")) assert rng1 == rng2 def test_generate_cday(self): - rng1 = list(generate_range(START, END, offset=CDay())) - rng2 = list(generate_range(START, END, offset="C")) + rng1 = list(generate_range(START, END, periods=None, offset=CDay())) + rng2 = list(generate_range(START, END, periods=None, offset="C")) assert rng1 == rng2 def test_1(self): - rng = list(generate_range(start=datetime(2009, 3, 25), periods=2)) + rng = list( + generate_range( + start=datetime(2009, 3, 25), end=None, periods=2, offset=BDay() + ) + ) expected = [datetime(2009, 3, 25), datetime(2009, 3, 26)] assert rng == expected def test_2(self): - rng = list(generate_range(start=datetime(2008, 1, 1), end=datetime(2008, 1, 3))) + rng = list( + generate_range( + start=datetime(2008, 1, 1), + end=datetime(2008, 1, 3), + periods=None, + offset=BDay(), + ) + ) expected = [datetime(2008, 1, 1), datetime(2008, 1, 2), datetime(2008, 1, 3)] assert rng == expected def test_3(self): - rng = list(generate_range(start=datetime(2008, 1, 5), end=datetime(2008, 1, 6))) + rng = list( + generate_range( + start=datetime(2008, 1, 5), + end=datetime(2008, 1, 6), + periods=None, + offset=BDay(), + ) + ) expected = [] assert rng == expected diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index c49354816b8b0..2c196a7b46d9c 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -734,7 +734,11 @@ def test_custom_business_day_freq(self): _check_plot_works(s.plot) - @pytest.mark.xfail(reason="GH#24426") + @pytest.mark.xfail( + reason="GH#24426, see also " + "github.com/pandas-dev/pandas/commit/" + "ef1bd69fa42bbed5d09dd17f08c44fc8bfc2b685#r61470674" + ) def test_plot_accessor_updates_on_inplace(self): ser = Series([1, 2, 3, 4]) _, ax = self.plt.subplots() diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 67ad152dcab30..dc3ddc7361afd 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -902,17 +902,17 @@ def test_addsub_timedeltalike_non_nano(self, dt64, ts, td): assert result._reso == ts._reso assert result == expected - @pytest.mark.xfail(reason="tz_localize not yet implemented for non-nano") def test_addsub_offset(self, ts_tz): # specifically non-Tick offset - off = offsets.YearBegin(1) + off = offsets.YearEnd(1) result = ts_tz + off assert isinstance(result, Timestamp) assert result._reso == ts_tz._reso - # If ts_tz is ever on the last day of the year, the year would be - # incremented by one - assert result.year == ts_tz.year + if ts_tz.month == 12 and ts_tz.day == 31: + assert result.year == ts_tz.year + 1 + else: + assert result.year == ts_tz.year assert result.day == 31 assert result.month == 12 assert tz_compare(result.tz, ts_tz.tz)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48385
2022-09-04T03:44:58Z
2022-09-12T18:23:38Z
2022-09-12T18:23:38Z
2022-10-13T17:00:41Z
PERF: avoid unnecessary reordering in MultiIndex._reorder_indexer
diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index a7c9a7eb88221..75e107bfb5892 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -109,6 +109,7 @@ Performance improvements - Performance improvement in :meth:`.GroupBy.mean` and :meth:`.GroupBy.var` for extension array dtypes (:issue:`37493`) - Performance improvement for :meth:`Series.value_counts` with nullable dtype (:issue:`48338`) - Performance improvement for :class:`Series` constructor passing integer numpy array with nullable dtype (:issue:`48338`) +- Performance improvement in :meth:`DataFrame.loc` and :meth:`Series.loc` for tuple-based indexing of a :class:`MultiIndex` (:issue:`48384`) - Performance improvement for :meth:`MultiIndex.unique` (:issue:`48335`) - Performance improvement in ``var`` for nullable dtypes (:issue:`48379`). - Performance improvement to :func:`read_sas` with ``blank_missing=True`` (:issue:`48502`) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 9506e775ceb03..dd63ea94d5211 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -3466,22 +3466,35 @@ def _reorder_indexer( ------- indexer : a sorted position indexer of self ordered as seq """ - # If the index is lexsorted and the list_like label in seq are sorted - # then we do not need to sort - if self._is_lexsorted(): - need_sort = False - for i, k in enumerate(seq): - if is_list_like(k): - if not need_sort: - k_codes = self.levels[i].get_indexer(k) - k_codes = k_codes[k_codes >= 0] # Filter absent keys - # True if the given codes are not ordered - need_sort = (k_codes[:-1] > k_codes[1:]).any() - elif isinstance(k, slice) and k.step is not None and k.step < 0: + + # check if sorting is necessary + need_sort = False + for i, k in enumerate(seq): + if com.is_null_slice(k) or com.is_bool_indexer(k) or is_scalar(k): + pass + elif is_list_like(k): + if len(k) <= 1: # type: ignore[arg-type] + pass + elif self._is_lexsorted(): + # If the index is lexsorted and the list_like label + # in seq are sorted then we do not need to sort + k_codes = self.levels[i].get_indexer(k) + k_codes = k_codes[k_codes >= 0] # Filter absent keys + # True if the given codes are not ordered + need_sort = (k_codes[:-1] > k_codes[1:]).any() + else: need_sort = True - # Bail out if both index and seq are sorted - if not need_sort: - return indexer + elif isinstance(k, slice): + if self._is_lexsorted(): + need_sort = k.step is not None and k.step < 0 + else: + need_sort = True + else: + need_sort = True + if need_sort: + break + if not need_sort: + return indexer n = len(self) keys: tuple[np.ndarray, ...] = () diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 9626352ac7e36..591b7abf60cc0 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -898,3 +898,29 @@ def test_pyint_engine(): missing = tuple([0, 1] * 5 * N) result = index.get_indexer([missing] + [keys[i] for i in idces]) tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize( + "keys,expected", + [ + ((slice(None), [5, 4]), [1, 0]), + ((slice(None), [4, 5]), [0, 1]), + (([True, False, True], [4, 6]), [0, 2]), + (([True, False, True], [6, 4]), [0, 2]), + ((2, [4, 5]), [0, 1]), + ((2, [5, 4]), [1, 0]), + (([2], [4, 5]), [0, 1]), + (([2], [5, 4]), [1, 0]), + ], +) +def test_get_locs_reordering(keys, expected): + # GH48384 + idx = MultiIndex.from_arrays( + [ + [2, 2, 1], + [4, 5, 6], + ] + ) + result = idx.get_locs(keys) + expected = np.array(expected, dtype=np.intp) + tm.assert_numpy_array_equal(result, expected)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v1.6.0.rst` file if fixing a bug or adding a new feature. `MultiIndex._reorder_indexer` contains logic to determine if indexer reordering is required. This PR expands the logic a bit to identify additional cases where reordering is not necessary. ASVs: ``` before after ratio [4b645ae5] [07679a60] <main> <multiindex-need-sort> - 5.07±1ms 726±9μs 0.14 indexing.MultiIndexing.time_loc_all_bool_indexers(True) - 8.13±2ms 709±20μs 0.09 indexing.MultiIndexing.time_loc_all_bool_indexers(False) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/48384
2022-09-04T02:35:49Z
2022-09-14T17:38:38Z
2022-09-14T17:38:38Z
2022-10-13T17:00:41Z
TYP: contextmanager expects a Generator
diff --git a/pandas/_config/config.py b/pandas/_config/config.py index fc35b95bba7dd..e1a6cf04a435e 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -59,9 +59,9 @@ from typing import ( Any, Callable, + Generator, Generic, Iterable, - Iterator, NamedTuple, cast, ) @@ -743,7 +743,7 @@ def pp(name: str, ks: Iterable[str]) -> list[str]: @contextmanager -def config_prefix(prefix) -> Iterator[None]: +def config_prefix(prefix) -> Generator[None, None, None]: """ contextmanager for multiple invocations of API with a common prefix diff --git a/pandas/_config/localization.py b/pandas/_config/localization.py index c4355e954c67c..eaae30ee9098b 100644 --- a/pandas/_config/localization.py +++ b/pandas/_config/localization.py @@ -11,7 +11,7 @@ import subprocess from typing import ( Callable, - Iterator, + Generator, ) from pandas._config.config import options @@ -20,7 +20,7 @@ @contextmanager def set_locale( new_locale: str | tuple[str, str], lc_var: int = locale.LC_ALL -) -> Iterator[str | tuple[str, str]]: +) -> Generator[str | tuple[str, str], None, None]: """ Context manager for temporarily setting a locale. diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py index a5b0d1e199863..f42004bdfdef3 100644 --- a/pandas/_testing/_warnings.py +++ b/pandas/_testing/_warnings.py @@ -7,6 +7,7 @@ import re import sys from typing import ( + Generator, Literal, Sequence, Type, @@ -24,7 +25,7 @@ def assert_produces_warning( check_stacklevel: bool = True, raise_on_extra_warnings: bool = True, match: str | None = None, -): +) -> Generator[list[warnings.WarningMessage], None, None]: """ Context manager for running code expected to either raise a specific warning, multiple specific warnings, or not raise any warnings. Verifies that the code diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index e64adb06bea7a..9647d46ac3391 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -8,7 +8,7 @@ from typing import ( IO, Any, - Iterator, + Generator, ) import uuid @@ -20,7 +20,7 @@ @contextmanager -def decompress_file(path, compression) -> Iterator[IO[bytes]]: +def decompress_file(path, compression) -> Generator[IO[bytes], None, None]: """ Open a compressed file and return a file object. @@ -41,7 +41,7 @@ def decompress_file(path, compression) -> Iterator[IO[bytes]]: @contextmanager -def set_timezone(tz: str) -> Iterator[None]: +def set_timezone(tz: str) -> Generator[None, None, None]: """ Context manager for temporarily setting a timezone. @@ -84,7 +84,9 @@ def setTZ(tz): @contextmanager -def ensure_clean(filename=None, return_filelike: bool = False, **kwargs: Any): +def ensure_clean( + filename=None, return_filelike: bool = False, **kwargs: Any +) -> Generator[Any, None, None]: """ Gets a temporary path and agrees to remove on close. @@ -127,7 +129,7 @@ def ensure_clean(filename=None, return_filelike: bool = False, **kwargs: Any): @contextmanager -def ensure_clean_dir() -> Iterator[str]: +def ensure_clean_dir() -> Generator[str, None, None]: """ Get a temporary directory path and agrees to remove on close. @@ -146,7 +148,7 @@ def ensure_clean_dir() -> Iterator[str]: @contextmanager -def ensure_safe_environment_variables() -> Iterator[None]: +def ensure_safe_environment_variables() -> Generator[None, None, None]: """ Get a context manager to safely set environment variables @@ -162,7 +164,7 @@ def ensure_safe_environment_variables() -> Iterator[None]: @contextmanager -def with_csv_dialect(name, **kwargs) -> Iterator[None]: +def with_csv_dialect(name, **kwargs) -> Generator[None, None, None]: """ Context manager to temporarily register a CSV dialect for parsing CSV. @@ -196,7 +198,7 @@ def with_csv_dialect(name, **kwargs) -> Iterator[None]: @contextmanager -def use_numexpr(use, min_elements=None) -> Iterator[None]: +def use_numexpr(use, min_elements=None) -> Generator[None, None, None]: from pandas.core.computation import expressions as expr if min_elements is None: diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index 813e8de72f96e..a9ae5f89b1a47 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -9,7 +9,7 @@ import pickle as pkl from typing import ( TYPE_CHECKING, - Iterator, + Generator, ) import warnings @@ -294,7 +294,7 @@ def loads( @contextlib.contextmanager -def patch_pickle() -> Iterator[None]: +def patch_pickle() -> Generator[None, None, None]: """ Temporarily patch pickle to use our unpickler. """ diff --git a/pandas/core/common.py b/pandas/core/common.py index 41ed68e73a4c0..e276e2d37d86c 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -18,9 +18,9 @@ Any, Callable, Collection, + Generator, Hashable, Iterable, - Iterator, Sequence, cast, overload, @@ -534,7 +534,7 @@ def convert_to_list_like( @contextlib.contextmanager -def temp_setattr(obj, attr: str, value) -> Iterator[None]: +def temp_setattr(obj, attr: str, value) -> Generator[None, None, None]: """Temporarily set attribute on an object. Args: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 89c9f3701a424..7cd6a93fea92d 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -20,6 +20,7 @@ class providing the base-class of operations. from typing import ( TYPE_CHECKING, Callable, + Generator, Hashable, Iterable, Iterator, @@ -1106,7 +1107,7 @@ def _reset_group_selection(self) -> None: self._reset_cache("_selected_obj") @contextmanager - def _group_selection_context(self) -> Iterator[GroupBy]: + def _group_selection_context(self) -> Generator[GroupBy, None, None]: """ Set / reset the _group_selection_context. """ diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 27094fff5f812..2b388411e6de7 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -21,9 +21,9 @@ Any, Callable, Final, + Generator, Hashable, Iterable, - Iterator, List, Mapping, Sequence, @@ -1216,7 +1216,7 @@ def save_to_buffer( @contextmanager def get_buffer( buf: FilePath | WriteBuffer[str] | None, encoding: str | None = None -) -> Iterator[WriteBuffer[str]] | Iterator[StringIO]: +) -> Generator[WriteBuffer[str], None, None] | Generator[StringIO, None, None]: """ Context manager to open, yield and close buffer for filenames or Path-like objects, otherwise yield buf unchanged. diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index a2a9079642344..d670931625a08 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -11,6 +11,7 @@ from typing import ( Any, Callable, + Generator, Hashable, Sequence, overload, @@ -80,7 +81,7 @@ @contextmanager -def _mpl(func: Callable): +def _mpl(func: Callable) -> Generator[tuple[Any, Any], None, None]: if has_mpl: yield plt, mpl else: diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 51a081645373e..5fe97534112b4 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -12,7 +12,7 @@ TYPE_CHECKING, Any, Final, - Iterator, + Generator, cast, ) @@ -99,7 +99,7 @@ def wrapper(*args, **kwargs): @contextlib.contextmanager -def pandas_converters() -> Iterator[None]: +def pandas_converters() -> Generator[None, None, None]: """ Context manager registering pandas' converters for a plot. diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 59117a3400bfd..4f197b5fc7095 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -3,7 +3,7 @@ from contextlib import contextmanager from typing import ( TYPE_CHECKING, - Iterator, + Generator, ) from pandas.plotting._core import _get_plot_backend @@ -594,7 +594,7 @@ def _get_canonical_key(self, key): return self._ALIASES.get(key, key) @contextmanager - def use(self, key, value) -> Iterator[_Options]: + def use(self, key, value) -> Generator[_Options, None, None]: """ Temporarily set a parameter value using the with statement. Aliasing allowed. diff --git a/pandas/tests/io/pytables/common.py b/pandas/tests/io/pytables/common.py index 67c3a2902dbcb..88a32e1a75972 100644 --- a/pandas/tests/io/pytables/common.py +++ b/pandas/tests/io/pytables/common.py @@ -1,6 +1,7 @@ from contextlib import contextmanager import os import tempfile +from typing import Generator import pytest @@ -36,7 +37,9 @@ def create_tempfile(path): # contextmanager to ensure the file cleanup @contextmanager -def ensure_clean_store(path, mode="a", complevel=None, complib=None, fletcher32=False): +def ensure_clean_store( + path, mode="a", complevel=None, complib=None, fletcher32=False +) -> Generator[HDFStore, None, None]: try: diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py index 0a3a10315b5fd..0cd340ab80897 100644 --- a/pandas/tests/libs/test_hashtable.py +++ b/pandas/tests/libs/test_hashtable.py @@ -1,6 +1,7 @@ from contextlib import contextmanager import struct import tracemalloc +from typing import Generator import numpy as np import pytest @@ -13,7 +14,7 @@ @contextmanager -def activated_tracemalloc(): +def activated_tracemalloc() -> Generator[None, None, None]: tracemalloc.start() try: yield diff --git a/pandas/tests/test_register_accessor.py b/pandas/tests/test_register_accessor.py index 3e4e57414269a..f0f330cc741b7 100644 --- a/pandas/tests/test_register_accessor.py +++ b/pandas/tests/test_register_accessor.py @@ -1,4 +1,5 @@ import contextlib +from typing import Generator import pytest @@ -23,7 +24,7 @@ def __init__(self) -> None: @contextlib.contextmanager -def ensure_removed(obj, attr): +def ensure_removed(obj, attr) -> Generator[None, None, None]: """Ensure that an attribute added to 'obj' during the test is removed when we're done """ diff --git a/pandas/util/_exceptions.py b/pandas/util/_exceptions.py index fcd191e25ced5..ebd92e8366e18 100644 --- a/pandas/util/_exceptions.py +++ b/pandas/util/_exceptions.py @@ -4,11 +4,11 @@ import functools import inspect import os -from typing import Iterator +from typing import Generator @contextlib.contextmanager -def rewrite_exception(old_name: str, new_name: str) -> Iterator[None]: +def rewrite_exception(old_name: str, new_name: str) -> Generator[None, None, None]: """ Rewrite the message of an exception. """ diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index 5a799cdb89146..f94b2511da678 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -30,7 +30,7 @@ def test_foo(): import locale from typing import ( Callable, - Iterator, + Generator, ) import warnings @@ -257,7 +257,7 @@ def check_file_leaks(func) -> Callable: @contextmanager -def file_leak_context() -> Iterator[None]: +def file_leak_context() -> Generator[None, None, None]: """ ContextManager analogue to check_file_leaks. """
`contextmanager` should expect a `Generator`, not an `Iterator`. `Iterator[...]` and `Generator[..., None, None]` are not the same, see https://github.com/python/typeshed/issues/2772 This might help @asottile a bit with https://github.com/python/typeshed/pull/7430. Basically, staled because it would impact too many projects - after this PR there is one fewer :)
https://api.github.com/repos/pandas-dev/pandas/pulls/48383
2022-09-04T00:07:05Z
2022-09-06T20:14:16Z
2022-09-06T20:14:16Z
2022-10-13T17:00:40Z
CI: Pin mambaforge image
diff --git a/Dockerfile b/Dockerfile index 0bfb0e15d63fe..02c360d2f3d49 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM quay.io/condaforge/mambaforge +FROM quay.io/condaforge/mambaforge:4.13.0-1 # if you forked pandas, you can pass in your own GitHub username to use your fork # i.e. gh_username=myname
- [x] xref #48382 (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Just a temporary fix, but can not reproduce the failure on arm so hard to inverstigate
https://api.github.com/repos/pandas-dev/pandas/pulls/48381
2022-09-03T21:58:08Z
2022-09-05T17:07:19Z
2022-09-05T17:07:18Z
2022-09-05T17:13:38Z
DOC: Clarify that objects dtype takes precedence in where
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 8671b73526f80..4a0619b7beb5b 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -308,6 +308,7 @@ Other enhancements - Implemented a complex-dtype :class:`Index`, passing a complex-dtype array-like to ``pd.Index`` will now retain complex dtype instead of casting to ``object`` (:issue:`45845`) - :class:`Series` and :class:`DataFrame` with :class:`IntegerDtype` now supports bitwise operations (:issue:`34463`) - Add ``milliseconds`` field support for :class:`.DateOffset` (:issue:`43371`) +- :meth:`DataFrame.where` tries to maintain dtype of :class:`DataFrame` if fill value can be cast without loss of precision (:issue:`45582`) - :meth:`DataFrame.reset_index` now accepts a ``names`` argument which renames the index names (:issue:`6878`) - :func:`concat` now raises when ``levels`` is given but ``keys`` is None (:issue:`46653`) - :func:`concat` now raises when ``levels`` contains duplicate values (:issue:`46653`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 32d4ac24a1d53..a5a75e0a3f7fb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9897,6 +9897,9 @@ def where( For further details and examples see the ``{name}`` documentation in :ref:`indexing <indexing.where_mask>`. + The dtype of the object takes precedence. The fill value is casted to + the objects dtype, if this can be done losslessly. + Examples -------- >>> s = pd.Series(range(5))
- [x] closes #48373 (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. cc @mroeschke Should we add a whatsnew too?
https://api.github.com/repos/pandas-dev/pandas/pulls/48380
2022-09-03T19:26:34Z
2022-09-07T18:08:16Z
2022-09-07T18:08:16Z
2022-09-07T19:06:05Z
PERF: Add var to masked arrays
diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index aff950c6933dd..9260ac0e63771 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -108,6 +108,7 @@ Performance improvements - Performance improvement for :meth:`Series.value_counts` with nullable dtype (:issue:`48338`) - Performance improvement for :class:`Series` constructor passing integer numpy array with nullable dtype (:issue:`48338`) - Performance improvement for :meth:`MultiIndex.unique` (:issue:`48335`) +- Performance improvement in ``var`` for nullable dtypes (:issue:`48379`). - Performance improvement to :func:`read_sas` with ``blank_missing=True`` (:issue:`48502`) - diff --git a/pandas/core/array_algos/masked_reductions.py b/pandas/core/array_algos/masked_reductions.py index 041905c993b0d..979d3ddac63c2 100644 --- a/pandas/core/array_algos/masked_reductions.py +++ b/pandas/core/array_algos/masked_reductions.py @@ -22,6 +22,7 @@ def _reductions( skipna: bool = True, min_count: int = 0, axis: int | None = None, + **kwargs, ): """ Sum, mean or product for 1D masked array. @@ -45,14 +46,14 @@ def _reductions( if mask.any(axis=axis) or check_below_min_count(values.shape, None, min_count): return libmissing.NA else: - return func(values, axis=axis) + return func(values, axis=axis, **kwargs) else: if check_below_min_count(values.shape, mask, min_count) and ( axis is None or values.ndim == 1 ): return libmissing.NA - return func(values, where=~mask, axis=axis) + return func(values, where=~mask, axis=axis, **kwargs) def sum( @@ -149,3 +150,19 @@ def mean( if not values.size or mask.all(): return libmissing.NA return _reductions(np.mean, values=values, mask=mask, skipna=skipna, axis=axis) + + +def var( + values: np.ndarray, + mask: npt.NDArray[np.bool_], + *, + skipna: bool = True, + axis: int | None = None, + ddof: int = 1, +): + if not values.size or mask.all(): + return libmissing.NA + + return _reductions( + np.var, values=values, mask=mask, skipna=skipna, axis=axis, ddof=ddof + ) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 7fe2c8fdd62f0..d67a5e215886b 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -1028,7 +1028,7 @@ def _quantile( # Reductions def _reduce(self, name: str, *, skipna: bool = True, **kwargs): - if name in {"any", "all", "min", "max", "sum", "prod", "mean"}: + if name in {"any", "all", "min", "max", "sum", "prod", "mean", "var"}: return getattr(self, name)(skipna=skipna, **kwargs) data = self._data @@ -1106,6 +1106,19 @@ def mean(self, *, skipna=True, axis: int | None = 0, **kwargs): "mean", result, skipna=skipna, axis=axis, **kwargs ) + def var(self, *, skipna=True, axis: int | None = 0, ddof: int = 1, **kwargs): + nv.validate_stat_ddof_func((), kwargs, fname="var") + result = masked_reductions.var( + self._data, + self._mask, + skipna=skipna, + axis=axis, + ddof=ddof, + ) + return self._wrap_reduction_result( + "var", result, skipna=skipna, axis=axis, **kwargs + ) + def min(self, *, skipna=True, axis: int | None = 0, **kwargs): nv.validate_min((), kwargs) return masked_reductions.min( diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index ef94a18016719..66f263b84de4d 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -696,7 +696,7 @@ def test_empty_multi(self, method, unit): expected = Series([1, np.nan], index=["a", "b"]) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("method", ["mean"]) + @pytest.mark.parametrize("method", ["mean", "var"]) @pytest.mark.parametrize("dtype", ["Float64", "Int64", "boolean"]) def test_ops_consistency_on_empty_nullable(self, method, dtype): @@ -787,6 +787,16 @@ def test_mean_masked_overflow(self): assert result_masked - result_numpy == 0 assert result_masked == 1e17 + @pytest.mark.parametrize("ddof, exp", [(1, 2.5), (0, 2.0)]) + def test_var_masked_array(self, ddof, exp): + # GH#48379 + ser = Series([1, 2, 3, 4, 5], dtype="Int64") + ser_numpy_dtype = Series([1, 2, 3, 4, 5], dtype="int64") + result = ser.var(ddof=ddof) + result_numpy_dtype = ser_numpy_dtype.var(ddof=ddof) + assert result == result_numpy_dtype + assert result == exp + @pytest.mark.parametrize("dtype", ("m8[ns]", "m8[ns]", "M8[ns]", "M8[ns, UTC]")) @pytest.mark.parametrize("skipna", [True, False]) def test_empty_timeseries_reductions_return_nat(self, dtype, skipna):
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48379
2022-09-03T19:20:45Z
2022-09-13T16:16:10Z
2022-09-13T16:16:09Z
2022-12-28T03:37:18Z
BUG: masked mean unnecessarily overflowing
diff --git a/doc/source/whatsnew/v1.6.0.rst b/doc/source/whatsnew/v1.6.0.rst index c393b8a57f805..42d3ce8069322 100644 --- a/doc/source/whatsnew/v1.6.0.rst +++ b/doc/source/whatsnew/v1.6.0.rst @@ -200,7 +200,7 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ -- +- Bug in :meth:`Series.mean` overflowing unnecessarily with nullable integers (:issue:`48378`) - Styler diff --git a/pandas/core/array_algos/masked_reductions.py b/pandas/core/array_algos/masked_reductions.py index 3e59a267f7191..041905c993b0d 100644 --- a/pandas/core/array_algos/masked_reductions.py +++ b/pandas/core/array_algos/masked_reductions.py @@ -14,7 +14,7 @@ from pandas.core.nanops import check_below_min_count -def _sumprod( +def _reductions( func: Callable, values: np.ndarray, mask: npt.NDArray[np.bool_], @@ -24,7 +24,7 @@ def _sumprod( axis: int | None = None, ): """ - Sum or product for 1D masked array. + Sum, mean or product for 1D masked array. Parameters ---------- @@ -63,7 +63,7 @@ def sum( min_count: int = 0, axis: int | None = None, ): - return _sumprod( + return _reductions( np.sum, values=values, mask=mask, skipna=skipna, min_count=min_count, axis=axis ) @@ -76,7 +76,7 @@ def prod( min_count: int = 0, axis: int | None = None, ): - return _sumprod( + return _reductions( np.prod, values=values, mask=mask, skipna=skipna, min_count=min_count, axis=axis ) @@ -139,11 +139,13 @@ def max( return _minmax(np.max, values=values, mask=mask, skipna=skipna, axis=axis) -# TODO: axis kwarg -def mean(values: np.ndarray, mask: npt.NDArray[np.bool_], skipna: bool = True): +def mean( + values: np.ndarray, + mask: npt.NDArray[np.bool_], + *, + skipna: bool = True, + axis: int | None = None, +): if not values.size or mask.all(): return libmissing.NA - _sum = _sumprod(np.sum, values=values, mask=mask, skipna=skipna) - count = np.count_nonzero(~mask) - mean_value = _sum / count - return mean_value + return _reductions(np.mean, values=values, mask=mask, skipna=skipna, axis=axis) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index c5f6dea7157ab..5c77a50f4a805 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -1036,17 +1036,12 @@ def _quantile( # Reductions def _reduce(self, name: str, *, skipna: bool = True, **kwargs): - if name in {"any", "all", "min", "max", "sum", "prod"}: + if name in {"any", "all", "min", "max", "sum", "prod", "mean"}: return getattr(self, name)(skipna=skipna, **kwargs) data = self._data mask = self._mask - if name in {"mean"}: - op = getattr(masked_reductions, name) - result = op(data, mask, skipna=skipna, **kwargs) - return result - # coerce to a nan-aware float if needed # (we explicitly use NaN within reductions) if self._hasna: @@ -1107,6 +1102,18 @@ def prod(self, *, skipna=True, min_count=0, axis: int | None = 0, **kwargs): "prod", result, skipna=skipna, axis=axis, **kwargs ) + def mean(self, *, skipna=True, axis: int | None = 0, **kwargs): + nv.validate_mean((), kwargs) + result = masked_reductions.mean( + self._data, + self._mask, + skipna=skipna, + axis=axis, + ) + return self._wrap_reduction_result( + "mean", result, skipna=skipna, axis=axis, **kwargs + ) + def min(self, *, skipna=True, axis: int | None = 0, **kwargs): nv.validate_min((), kwargs) return masked_reductions.min( diff --git a/pandas/tests/extension/base/dim2.py b/pandas/tests/extension/base/dim2.py index f71f3cf164bfc..d2c1e6971c56e 100644 --- a/pandas/tests/extension/base/dim2.py +++ b/pandas/tests/extension/base/dim2.py @@ -6,7 +6,13 @@ from pandas._libs.missing import is_matching_na +from pandas.core.dtypes.common import ( + is_bool_dtype, + is_integer_dtype, +) + import pandas as pd +import pandas._testing as tm from pandas.core.arrays.integer import INT_STR_TO_DTYPE from pandas.tests.extension.base.base import BaseExtensionTests @@ -191,7 +197,12 @@ def test_reductions_2d_axis0(self, data, method): kwargs["ddof"] = 0 try: - result = getattr(arr2d, method)(axis=0, **kwargs) + if method == "mean" and hasattr(data, "_mask"): + # Empty slices produced by the mask cause RuntimeWarnings by numpy + with tm.assert_produces_warning(RuntimeWarning, check_stacklevel=False): + result = getattr(arr2d, method)(axis=0, **kwargs) + else: + result = getattr(arr2d, method)(axis=0, **kwargs) except Exception as err: try: getattr(data, method)() @@ -212,7 +223,7 @@ def get_reduction_result_dtype(dtype): # i.e. dtype.kind == "u" return INT_STR_TO_DTYPE[np.dtype(np.uint).name] - if method in ["mean", "median", "sum", "prod"]: + if method in ["median", "sum", "prod"]: # std and var are not dtype-preserving expected = data if method in ["sum", "prod"] and data.dtype.kind in "iub": @@ -229,6 +240,10 @@ def get_reduction_result_dtype(dtype): self.assert_extension_array_equal(result, expected) elif method == "std": self.assert_extension_array_equal(result, data - data) + elif method == "mean": + if is_integer_dtype(data) or is_bool_dtype(data): + data = data.astype("Float64") + self.assert_extension_array_equal(result, data) # punt on method == "var" @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index fa53ed47dbdba..ef94a18016719 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -775,6 +775,18 @@ def test_sum_overflow_float(self, use_bottleneck, dtype): result = s.max(skipna=False) assert np.allclose(float(result), v[-1]) + def test_mean_masked_overflow(self): + # GH#48378 + val = 100_000_000_000_000_000 + n_elements = 100 + na = np.array([val] * n_elements) + ser = Series([val] * n_elements, dtype="Int64") + + result_numpy = np.mean(na) + result_masked = ser.mean() + assert result_masked - result_numpy == 0 + assert result_masked == 1e17 + @pytest.mark.parametrize("dtype", ("m8[ns]", "m8[ns]", "M8[ns]", "M8[ns, UTC]")) @pytest.mark.parametrize("skipna", [True, False]) def test_empty_timeseries_reductions_return_nat(self, dtype, skipna):
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Do we want to add mean to the Masked Array interface (I would say yes, but want to check anyway)? This would simplify things a bit. cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/48378
2022-09-03T18:02:11Z
2022-09-07T17:39:42Z
2022-09-07T17:39:42Z
2022-10-13T17:00:39Z
DOC: More types for groupby's by argument
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index 296e25fd5c187..210d7d79bfe15 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -94,7 +94,7 @@ Parameters ---------- -by : mapping, function, label, pd.Grouper or list of labels +by : mapping, function, label, pd.Grouper or list of such Used to determine the groups for the groupby. If ``by`` is a function, it's called on each value of the object's index. If a dict or Series is passed, the Series or dict VALUES
Added to the typing of the `by` argument in the documentation of the `groupby` functions, to allow lists of functions/mappings/`pd.Grouper` and not just lists of labels.
https://api.github.com/repos/pandas-dev/pandas/pulls/48377
2022-09-03T16:26:37Z
2022-09-06T20:21:17Z
2022-09-06T20:21:17Z
2022-10-13T17:00:38Z
DOC: how to_datetime %S differs from strptime
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 203a5711b7a59..78e12c96ceee8 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -777,11 +777,19 @@ def to_datetime( #time-zone-handling>`_. format : str, default None - The strftime to parse time, e.g. :const:`"%d/%m/%Y"`. Note that - :const:`"%f"` will parse all the way up to nanoseconds. See + The strftime to parse time, e.g. :const:`"%d/%m/%Y"`. See `strftime documentation <https://docs.python.org/3/library/datetime.html - #strftime-and-strptime-behavior>`_ for more information on choices. + #strftime-and-strptime-behavior>`_ for more information on choices, though + note the following differences: + + - :const:`"%f"` will parse all the way + up to nanoseconds; + + - :const:`"%S"` without :const:`"%f"` will capture all the way + up to nanoseconds if present as decimal places, and will also handle + the case where the number of seconds is an integer. + exact : bool, default True Control how `format` is used: @@ -950,6 +958,21 @@ def to_datetime( DatetimeIndex(['1960-01-02', '1960-01-03', '1960-01-04'], dtype='datetime64[ns]', freq=None) + **Differences with strptime behavior** + + :const:`"%f"` will parse all the way up to nanoseconds. + + >>> pd.to_datetime('2018-10-26 12:00:00.0000000011', + ... format='%Y-%m-%d %H:%M:%S.%f') + Timestamp('2018-10-26 12:00:00.000000001') + + :const:`"%S"` without :const:`"%f"` will capture all the way + up to nanoseconds if present as decimal places. + + >>> pd.to_datetime('2017-03-22 15:16:45.433502912', + ... format='%Y-%m-%d %H:%M:%S') + Timestamp('2017-03-22 15:16:45.433502912') + **Non-convertible date/times** If a date does not meet the `timestamp limitations
- [ ] closes #47134 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48376
2022-09-03T11:40:37Z
2022-09-03T15:37:40Z
2022-09-03T15:37:40Z
2022-10-13T17:00:37Z
TST: to_numeric(large_float, downcast=float) isn't lossy
diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py index 38a50a10b3482..1347f6eb50b09 100644 --- a/pandas/tests/tools/test_to_numeric.py +++ b/pandas/tests/tools/test_to_numeric.py @@ -799,3 +799,11 @@ def test_to_numeric_scientific_notation(): result = to_numeric("1.7e+308") expected = np.float64(1.7e308) assert result == expected + + +@pytest.mark.parametrize("val", [9876543210.0, 2.0**128]) +def test_to_numeric_large_float_not_downcast_to_float_32(val): + # GH 19729 + expected = Series([val]) + result = to_numeric(expected, downcast="float") + tm.assert_series_equal(result, expected)
- [x] closes #19729 (Replace xxxx with the Github issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Fixed by https://github.com/pandas-dev/pandas/pull/43710 but adding an additional test.
https://api.github.com/repos/pandas-dev/pandas/pulls/48372
2022-09-02T18:53:22Z
2022-09-02T21:26:18Z
2022-09-02T21:26:18Z
2022-10-13T17:00:37Z
Backport PR #48265 on branch 1.5.x (CI: Setting up ssh key to upload prod docs)
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml index 5ad146eccb253..031e1ca054ba8 100644 --- a/.github/workflows/docbuild-and-upload.yml +++ b/.github/workflows/docbuild-and-upload.yml @@ -67,7 +67,7 @@ jobs: echo "${{ secrets.server_ssh_key }}" > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa echo "${{ secrets.server_ip }} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBE1Kkopomm7FHG5enATf7SgnpICZ4W2bw+Ho+afqin+w7sMcrsa0je7sbztFAV8YchDkiBKnWTG4cRT+KZgZCaY=" > ~/.ssh/known_hosts - if: github.event_name == 'push' && github.ref == 'refs/heads/main' + if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/')) - name: Copy cheatsheets into site directory run: cp doc/cheatsheet/Pandas_Cheat_Sheet* web/build/
Backport PR #48265: CI: Setting up ssh key to upload prod docs
https://api.github.com/repos/pandas-dev/pandas/pulls/48370
2022-09-02T17:26:57Z
2022-09-02T21:11:55Z
2022-09-02T21:11:55Z
2022-09-02T21:11:56Z
Fix build warning for use of `strdup` in ultrajson
diff --git a/pandas/_libs/src/headers/portable.h b/pandas/_libs/src/headers/portable.h index cb8e5ba8138eb..3464fba963a5e 100644 --- a/pandas/_libs/src/headers/portable.h +++ b/pandas/_libs/src/headers/portable.h @@ -1,8 +1,16 @@ #ifndef _PANDAS_PORTABLE_H_ #define _PANDAS_PORTABLE_H_ +// To get `strdup` from strings.h +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 600 +#endif + +#include <string.h> + #if defined(_MSC_VER) #define strcasecmp( s1, s2 ) _stricmp( s1, s2 ) +#define strdup _strdup #endif // GH-23516 - works around locale perf issues diff --git a/pandas/_libs/src/ujson/lib/ultrajson.h b/pandas/_libs/src/ujson/lib/ultrajson.h index 71df0c5a186b7..5c851254815b7 100644 --- a/pandas/_libs/src/ujson/lib/ultrajson.h +++ b/pandas/_libs/src/ujson/lib/ultrajson.h @@ -54,6 +54,7 @@ tree doesn't have cyclic references. #include <stdio.h> #include <wchar.h> +#include "../../headers/portable.h" // Don't output any extra whitespaces when encoding #define JSON_NO_EXTRA_WHITESPACE
When building with `-std=c99` (I was having a look at @lithomas1's `meson-poc` branch) on Linux this gives a warning: ``` [2/3] Compiling C object pandas/_libs/json.cpython-310-x86_64-linux-gnu.so.p/src_ujson_lib_ultrajsonenc.c.o ../pandas/_libs/src/ujson/lib/ultrajsonenc.c: In function 'JSON_EncodeObject': ../pandas/_libs/src/ujson/lib/ultrajsonenc.c:1180:18: warning: implicit declaration of function 'strdup'; did you mean 'strcmp'? [-Wimplicit-function-declaration] 1180 | locale = strdup(locale); | ^~~~~~ | strcmp ../pandas/_libs/src/ujson/lib/ultrajsonenc.c:1180:16: warning: assignment to 'char *' from 'int' makes pointer from integer without a cast [-Wint-conversion] 1180 | locale = strdup(locale); ``` And for the MSVC builds in CI the warnings look like: ``` building 'pandas._libs.json' extension creating build\temp.win-amd64-cpython-310\Release\pandas\_libs\src\ujson creating build\temp.win-amd64-cpython-310\Release\pandas\_libs\src\ujson\lib creating build\temp.win-amd64-cpython-310\Release\pandas\_libs\src\ujson\python "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.33.31629\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DNPY_NO_DEPRECATED_API=0 -Ipandas/_libs/src/ujson/python -Ipandas/_libs/src/ujson/lib -Ipandas/_libs/src/datetime -IC:\Users\runneradmin\micromamba\envs\test\lib\site-packages\numpy\core\include -IC:\Users\runneradmin\micromamba\envs\test\include -IC:\Users\runneradmin\micromamba\envs\test\Include "-IC:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.33.31629\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Tools\MSVC\14.33.31629\ATLMFC\include" "-IC:\Program Files\Microsoft Visual Studio\2022\Enterprise\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22621.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22621.0\\cppwinrt" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" /Tcpandas/_libs/src/ujson/lib/ultrajsondec.c /Fobuild\temp.win-amd64-cpython-310\Release\pandas/_libs/src/ujson/lib/ultrajsondec.obj -D_GNU_SOURCE ultrajsondec.c pandas/_libs/src/ujson/lib/ultrajsondec.c(1178): warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C and C++ conformant name: _strdup. See online help for details. ``` I considered avoiding the code duplication by putting this block in a shared file, but the two files touched here already have quite a bit of duplicated code, so that's best left alone.
https://api.github.com/repos/pandas-dev/pandas/pulls/48369
2022-09-02T16:57:32Z
2022-09-20T13:49:42Z
2022-09-20T13:49:42Z
2022-10-13T17:00:36Z
DOC: update query/eval figures on performance comparison
diff --git a/doc/scripts/eval_performance.py b/doc/scripts/eval_performance.py new file mode 100644 index 0000000000000..27d9bf23fc1af --- /dev/null +++ b/doc/scripts/eval_performance.py @@ -0,0 +1,108 @@ +from timeit import repeat as timeit + +import numpy as np +import seaborn as sns + +from pandas import DataFrame + +setup_common = """from pandas import DataFrame +from numpy.random import randn +df = DataFrame(randn(%d, 3), columns=list('abc')) +%s""" + +setup_with = "s = 'a + b * (c ** 2 + b ** 2 - a) / (a * c) ** 3'" + + +def bench_with(n, times=10, repeat=3, engine="numexpr"): + return ( + np.array( + timeit( + "df.eval(s, engine=%r)" % engine, + setup=setup_common % (n, setup_with), + repeat=repeat, + number=times, + ) + ) + / times + ) + + +setup_subset = "s = 'a <= b <= c ** 2 + b ** 2 - a and b > c'" + + +def bench_subset(n, times=20, repeat=3, engine="numexpr"): + return ( + np.array( + timeit( + "df.query(s, engine=%r)" % engine, + setup=setup_common % (n, setup_subset), + repeat=repeat, + number=times, + ) + ) + / times + ) + + +def bench(mn=3, mx=7, num=100, engines=("python", "numexpr"), verbose=False): + r = np.logspace(mn, mx, num=num).round().astype(int) + + ev = DataFrame(np.empty((num, len(engines))), columns=engines) + qu = ev.copy(deep=True) + + ev["size"] = qu["size"] = r + + for engine in engines: + for i, n in enumerate(r): + if verbose & (i % 10 == 0): + print("engine: %r, i == %d" % (engine, i)) + ev_times = bench_with(n, times=1, repeat=1, engine=engine) + ev.loc[i, engine] = np.mean(ev_times) + qu_times = bench_subset(n, times=1, repeat=1, engine=engine) + qu.loc[i, engine] = np.mean(qu_times) + + return ev, qu + + +def plot_perf(df, engines, title, filename=None): + from matplotlib.pyplot import figure + + sns.set() + sns.set_palette("Set2") + + fig = figure(figsize=(4, 3), dpi=120) + ax = fig.add_subplot(111) + + for engine in engines: + ax.loglog(df["size"], df[engine], label=engine, lw=2) + + ax.set_xlabel("Number of Rows") + ax.set_ylabel("Time (s)") + ax.set_title(title) + ax.legend(loc="best") + ax.tick_params(top=False, right=False) + + fig.tight_layout() + + if filename is not None: + fig.savefig(filename) + + +if __name__ == "__main__": + import os + + pandas_dir = os.path.dirname( + os.path.dirname(os.path.abspath(os.path.dirname(__file__))) + ) + static_path = os.path.join(pandas_dir, "doc", "source", "_static") + + join = lambda p: os.path.join(static_path, p) + + fn = join("eval-query-perf-data.h5") + + engines = "python", "numexpr" + + ev, qu = bench(verbose=True) # only this one + + plot_perf(ev, engines, "DataFrame.eval()", filename=join("eval-perf.png")) + plot_perf(qu, engines, "DataFrame.query()", filename=join("query-perf.png")) diff --git a/doc/source/_static/eval-perf-small.png b/doc/source/_static/eval-perf-small.png deleted file mode 100644 index d86018363ffdc..0000000000000 Binary files a/doc/source/_static/eval-perf-small.png and /dev/null differ diff --git a/doc/source/_static/eval-perf.png b/doc/source/_static/eval-perf.png index 14c69c1b85d9e..ed92337c1d995 100644 Binary files a/doc/source/_static/eval-perf.png and b/doc/source/_static/eval-perf.png differ diff --git a/doc/source/_static/query-perf-small.png b/doc/source/_static/query-perf-small.png deleted file mode 100644 index e14fa69db7fe8..0000000000000 Binary files a/doc/source/_static/query-perf-small.png and /dev/null differ diff --git a/doc/source/_static/query-perf.png b/doc/source/_static/query-perf.png index d96318df94357..c52849a0edd53 100644 Binary files a/doc/source/_static/query-perf.png and b/doc/source/_static/query-perf.png differ diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst index 1a1229f95523b..9375bb066781b 100644 --- a/doc/source/user_guide/enhancingperf.rst +++ b/doc/source/user_guide/enhancingperf.rst @@ -690,21 +690,12 @@ The equivalent in standard Python would be df["a"] = 1 df -The :class:`DataFrame.query` method has a ``inplace`` keyword which determines -whether the query modifies the original frame. - -.. ipython:: python - - df = pd.DataFrame(dict(a=range(5), b=range(5, 10))) - df.query("a > 2") - df.query("a > 2", inplace=True) - df - Local variables ~~~~~~~~~~~~~~~ You must *explicitly reference* any local variable that you want to use in an -expression by placing the ``@`` character in front of the name. For example, +expression by placing the ``@`` character in front of the name. This mechanism is +the same for both :meth:`DataFrame.query` and :meth:`DataFrame.eval`. For example, .. ipython:: python @@ -820,17 +811,12 @@ significant performance benefit. Here is a plot showing the running time of :func:`pandas.eval` as function of the size of the frame involved in the computation. The two lines are two different engines. +.. + The eval-perf.png figure below was generated with /doc/scripts/eval_performance.py .. image:: ../_static/eval-perf.png - -.. note:: - - Operations with smallish objects (around 15k-20k rows) are faster using - plain Python: - - .. image:: ../_static/eval-perf-small.png - +You will only see the performance benefits of using the ``numexpr`` engine with :func:`pandas.eval` if your frame has more than approximately 100,000 rows. This plot was created using a :class:`DataFrame` with 3 columns each containing floating point values generated using ``numpy.random.randn()``. diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst index f939945fc6cda..dbd6d2757e1be 100644 --- a/doc/source/user_guide/indexing.rst +++ b/doc/source/user_guide/indexing.rst @@ -1240,6 +1240,17 @@ If instead you don't want to or cannot name your index, you can use the name renaming your columns to something less ambiguous. +The :class:`DataFrame.query` method has a ``inplace`` keyword which determines +whether the query modifies the original frame. + +.. ipython:: python + + df = pd.DataFrame(dict(a=range(5), b=range(5, 10))) + df.query("a > 2") + df.query("a > 2", inplace=True) + df + + :class:`~pandas.MultiIndex` :meth:`~pandas.DataFrame.query` Syntax ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1438,15 +1449,18 @@ Performance of :meth:`~pandas.DataFrame.query` ``DataFrame.query()`` using ``numexpr`` is slightly faster than Python for large frames. +.. + The eval-perf.png figure below was generated with /doc/scripts/eval_performance.py + .. image:: ../_static/query-perf.png -.. note:: - You will only see the performance benefits of using the ``numexpr`` engine - with ``DataFrame.query()`` if your frame has more than approximately 200,000 - rows. - .. image:: ../_static/query-perf-small.png +You will only see the performance benefits of using the ``numexpr`` engine +with ``DataFrame.query()`` if your frame has more than approximately 100,000 +rows. + + This plot was created using a ``DataFrame`` with 3 columns each containing floating point values generated using ``numpy.random.randn()``.
Feature reviewed by Joris (https://github.com/jorisvandenbossche) during the EuroScipy 2022 Sprint. This feature updates the pandas.eval() performance graphs here: https://pandas.pydata.org/docs/user_guide/enhancingperf.html#technical-minutia-regarding-expression-evaluation and the performance of the query here https://pandas.pydata.org/docs/user_guide/indexing.html#performance-of-query.
https://api.github.com/repos/pandas-dev/pandas/pulls/48368
2022-09-02T16:11:31Z
2022-10-28T16:31:25Z
2022-10-28T16:31:25Z
2022-10-28T16:31:38Z
Upgrade codespell version and fix misspelled words
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2ca5b5c9b896b..33e23e8ddb206 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -22,7 +22,7 @@ repos: hooks: - id: black - repo: https://github.com/codespell-project/codespell - rev: v2.1.0 + rev: v2.2.1 hooks: - id: codespell types_or: [python, rst, markdown] diff --git a/pandas/core/resample.py b/pandas/core/resample.py index e3d81e01ac94c..85731bbde6d40 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1045,7 +1045,7 @@ def quantile(self, q=0.5, **kwargs): Return a DataFrame, where the columns are the columns of self, and the values are the quantiles. DataFrameGroupBy.quantile - Return a DataFrame, where the coulmns are groupby columns, + Return a DataFrame, where the columns are groupby columns, and the values are its quantiles. """ return self._downsample("quantile", q=q, **kwargs) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index a2a9079642344..21db0023f4be7 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -828,7 +828,7 @@ def to_latex( ``display_value`` with the default structure: ``\<command><options> <display_value>``. Where there are multiple commands the latter is nested recursively, so that - the above example highlighed cell is rendered as + the above example highlighted cell is rendered as ``\cellcolor{red} \bfseries 4``. Occasionally this format does not suit the applied command, or diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index ff8c21ab89f30..5d5b497a04c04 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -1272,7 +1272,7 @@ def __next__(self) -> list[str]: else: line = next(self.f) # type: ignore[arg-type] # Note: 'colspecs' is a sequence of half-open intervals. - return [line[fromm:to].strip(self.delimiter) for (fromm, to) in self.colspecs] + return [line[from_:to].strip(self.delimiter) for (from_, to) in self.colspecs] class FixedWidthFieldParser(PythonParser): diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 24f4dd4a1f64a..633a763dab80a 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -450,7 +450,7 @@ def test_constructor_str_unknown(self): Categorical([1, 2], dtype="foo") def test_constructor_np_strs(self): - # GH#31499 Hastable.map_locations needs to work on np.str_ objects + # GH#31499 Hashtable.map_locations needs to work on np.str_ objects cat = Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")]) assert all(isinstance(x, np.str_) for x in cat.categories) diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 6a17a56a47cbc..0a48d8e2a4983 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -178,15 +178,15 @@ def test_mul(dtype, request): @pytest.mark.xfail(reason="GH-28527") def test_add_strings(dtype): arr = pd.array(["a", "b", "c", "d"], dtype=dtype) - df = pd.DataFrame([["t", "u", "v", "w"]]) + df = pd.DataFrame([["t", "y", "v", "w"]]) assert arr.__add__(df) is NotImplemented result = arr + df - expected = pd.DataFrame([["at", "bu", "cv", "dw"]]).astype(dtype) + expected = pd.DataFrame([["at", "by", "cv", "dw"]]).astype(dtype) tm.assert_frame_equal(result, expected) result = df + arr - expected = pd.DataFrame([["ta", "ub", "vc", "wd"]]).astype(dtype) + expected = pd.DataFrame([["ta", "yb", "vc", "wd"]]).astype(dtype) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/config/test_config.py b/pandas/tests/config/test_config.py index cc394bbb23d00..85a3d6f89aa72 100644 --- a/pandas/tests/config/test_config.py +++ b/pandas/tests/config/test_config.py @@ -14,9 +14,9 @@ def setup_class(cls): from copy import deepcopy cls.cf = cf - cls.gc = deepcopy(getattr(cls.cf, "_global_config")) - cls.do = deepcopy(getattr(cls.cf, "_deprecated_options")) - cls.ro = deepcopy(getattr(cls.cf, "_registered_options")) + cls._global_config = deepcopy(getattr(cls.cf, "_global_config")) + cls._deprecated_options = deepcopy(getattr(cls.cf, "_deprecated_options")) + cls._registered_options = deepcopy(getattr(cls.cf, "_registered_options")) def setup_method(self): setattr(self.cf, "_global_config", {}) @@ -31,9 +31,9 @@ def setup_method(self): self.cf.register_option("chained_assignment", "raise") def teardown_method(self): - setattr(self.cf, "_global_config", self.gc) - setattr(self.cf, "_deprecated_options", self.do) - setattr(self.cf, "_registered_options", self.ro) + setattr(self.cf, "_global_config", self._global_config) + setattr(self.cf, "_deprecated_options", self._deprecated_options) + setattr(self.cf, "_registered_options", self._registered_options) def test_api(self): diff --git a/setup.cfg b/setup.cfg index f2314316f7732..53dfa2623c972 100644 --- a/setup.cfg +++ b/setup.cfg @@ -178,7 +178,7 @@ exclude = doc/source/getting_started/comparison/includes/*.rst [codespell] -ignore-words-list = ba,blocs,coo,hist,nd,sav,ser +ignore-words-list = blocs,coo,hist,nd,sav,ser,recuse ignore-regex = https://([\w/\.])+ [coverage:run]
- [x] closes #48349
https://api.github.com/repos/pandas-dev/pandas/pulls/48364
2022-09-02T14:49:00Z
2022-09-06T20:24:01Z
2022-09-06T20:24:01Z
2022-10-13T17:00:35Z
pytest: Use colored output
diff --git a/pyproject.toml b/pyproject.toml index 67c56123a847c..592994ce6e520 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,7 +34,7 @@ exclude = ''' [tool.pytest.ini_options] # sync minversion with pyproject.toml & install.rst minversion = "6.0" -addopts = "--strict-data-files --strict-markers --strict-config --capture=no --durations=30 --junitxml=test-data.xml" +addopts = "--strict-data-files --strict-markers --strict-config --capture=no --durations=30 --junitxml=test-data.xml --color=yes" xfail_strict = true testpaths = "pandas" doctest_optionflags = [
This gives nice colored output locally and on GitHub Actions. - [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48359
2022-09-02T06:26:57Z
2022-09-02T16:54:18Z
2022-09-02T16:54:18Z
2022-10-13T17:00:35Z
TST: Address/catch more test warnings
diff --git a/pandas/io/date_converters.py b/pandas/io/date_converters.py index 5885a3b9d14d7..99a838c61b996 100644 --- a/pandas/io/date_converters.py +++ b/pandas/io/date_converters.py @@ -92,9 +92,7 @@ def generic_parser(parse_func, *cols) -> np.ndarray: """ warnings.warn( - """ - Use pd.to_datetime instead. -""", + "Use pd.to_datetime instead.", FutureWarning, stacklevel=find_stack_level(inspect.currentframe()), ) diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 4cf6706707569..3d7e5c6823e9d 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -777,6 +777,6 @@ def test_fillna_nonconsolidated_frame(): ], columns=["i1", "i2", "i3", "f1"], ) - df_nonconsol = df.pivot("i1", "i2") + df_nonconsol = df.pivot(index="i1", columns="i2") result = df_nonconsol.fillna(0) assert result.isna().sum().sum() == 0 diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index f804f7df06bb8..b64af2dd98bcb 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -70,7 +70,8 @@ def test_plot(self): ax = _check_plot_works(df.plot, use_index=True) self._check_ticks_props(ax, xrot=0) - _check_plot_works(df.plot, sort_columns=False) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + _check_plot_works(df.plot, sort_columns=False) _check_plot_works(df.plot, yticks=[1, 5, 10]) _check_plot_works(df.plot, xticks=[1, 5, 10]) _check_plot_works(df.plot, ylim=(-100, 100), xlim=(-100, 100))
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/48358
2022-09-02T03:55:32Z
2022-09-06T14:03:56Z
2022-09-06T14:03:55Z
2022-10-13T17:00:34Z
DOC: add pd.Grouper type to groupby by argument types
diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index 09c8cf39f5839..296e25fd5c187 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -94,7 +94,7 @@ Parameters ---------- -by : mapping, function, label, or list of labels +by : mapping, function, label, pd.Grouper or list of labels Used to determine the groups for the groupby. If ``by`` is a function, it's called on each value of the object's index. If a dict or Series is passed, the Series or dict VALUES
- [ ] closes #48230 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48357
2022-09-02T03:37:14Z
2022-09-02T16:56:03Z
2022-09-02T16:56:03Z
2022-10-13T17:00:33Z
CLN: consistent use of rval within left_join_indexer_unique (minor cleanup)
diff --git a/pandas/_libs/join.pyx b/pandas/_libs/join.pyx index cc7d863bf326c..e574aa10f6b57 100644 --- a/pandas/_libs/join.pyx +++ b/pandas/_libs/join.pyx @@ -298,7 +298,7 @@ def left_join_indexer_unique( indexer[i] = j i += 1 - if left[i] == right[j]: + if left[i] == rval: indexer[i] = j i += 1 while i < nleft - 1 and left[i] == rval:
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Very minor cleanup. Replacing `right[j]` with `rval` to be consistent with code above and below the line in question. (`rval = right[j]`)
https://api.github.com/repos/pandas-dev/pandas/pulls/48356
2022-09-02T01:38:59Z
2022-09-02T07:05:27Z
2022-09-02T07:05:27Z
2022-10-13T17:00:33Z
CI: Bump timeout to 180 minutes
diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml index 9cbd41917110e..8b3d69943bd9d 100644 --- a/.github/workflows/macos-windows.yml +++ b/.github/workflows/macos-windows.yml @@ -28,7 +28,7 @@ jobs: defaults: run: shell: bash -el {0} - timeout-minutes: 120 + timeout-minutes: 180 strategy: matrix: os: [macos-latest, windows-latest] diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 301e7804ddbd8..b7cddc6bb3d05 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -26,7 +26,7 @@ jobs: defaults: run: shell: bash -el {0} - timeout-minutes: 120 + timeout-minutes: 180 strategy: matrix: env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml]
Noticing a few timeouts on builds lately. Investigating whether we need to bump the timeout limit or some tests are stalling.
https://api.github.com/repos/pandas-dev/pandas/pulls/48354
2022-09-01T21:33:35Z
2022-09-07T22:50:15Z
2022-09-07T22:50:15Z
2022-09-08T21:32:27Z
Backport PR #48254 on branch 1.5.x (REF: avoid FutureWarning about using deprecates loc.__setitem__ non-inplace usage)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index abab32ae145bd..7b345a58bda88 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6869,14 +6869,48 @@ def fillna( if not is_dict else downcast.get(k) # type: ignore[union-attr] ) - # GH47649 - result.loc[:, k] = ( - result[k].fillna(v, limit=limit, downcast=downcast_k).values - ) - # TODO: result.loc[:, k] = result.loc[:, k].fillna( - # v, limit=limit, downcast=downcast_k - # ) - # Revert when GH45751 is fixed + + res_k = result[k].fillna(v, limit=limit, downcast=downcast_k) + + if not inplace: + result[k] = res_k + else: + # We can write into our existing column(s) iff dtype + # was preserved. + if isinstance(res_k, ABCSeries): + # i.e. 'k' only shows up once in self.columns + if res_k.dtype == result[k].dtype: + result.loc[:, k] = res_k + else: + # Different dtype -> no way to do inplace. + result[k] = res_k + else: + # see test_fillna_dict_inplace_nonunique_columns + locs = result.columns.get_loc(k) + if isinstance(locs, slice): + locs = np.arange(self.shape[1])[locs] + elif ( + isinstance(locs, np.ndarray) and locs.dtype.kind == "b" + ): + locs = locs.nonzero()[0] + elif not ( + isinstance(locs, np.ndarray) and locs.dtype.kind == "i" + ): + # Should never be reached, but let's cover our bases + raise NotImplementedError( + "Unexpected get_loc result, please report a bug at " + "https://github.com/pandas-dev/pandas" + ) + + for i, loc in enumerate(locs): + res_loc = res_k.iloc[:, i] + target = self.iloc[:, loc] + + if res_loc.dtype == target.dtype: + result.iloc[:, loc] = res_loc + else: + result.isetitem(loc, res_loc) + return result if not inplace else None elif not is_list_like(value): diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 8355502c47c61..4cf6706707569 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -19,6 +19,30 @@ class TestFillNA: + @td.skip_array_manager_not_yet_implemented + def test_fillna_dict_inplace_nonunique_columns(self, using_copy_on_write): + df = DataFrame( + {"A": [np.nan] * 3, "B": [NaT, Timestamp(1), NaT], "C": [np.nan, "foo", 2]} + ) + df.columns = ["A", "A", "A"] + orig = df[:] + + df.fillna({"A": 2}, inplace=True) + # The first and third columns can be set inplace, while the second cannot. + + expected = DataFrame( + {"A": [2.0] * 3, "B": [2, Timestamp(1), 2], "C": [2, "foo", 2]} + ) + expected.columns = ["A", "A", "A"] + tm.assert_frame_equal(df, expected) + + # TODO: what's the expected/desired behavior with CoW? + if not using_copy_on_write: + assert tm.shares_memory(df.iloc[:, 0], orig.iloc[:, 0]) + assert not tm.shares_memory(df.iloc[:, 1], orig.iloc[:, 1]) + if not using_copy_on_write: + assert tm.shares_memory(df.iloc[:, 2], orig.iloc[:, 2]) + @td.skip_array_manager_not_yet_implemented def test_fillna_on_column_view(self, using_copy_on_write): # GH#46149 avoid unnecessary copies @@ -287,7 +311,6 @@ def test_fillna_downcast_noop(self, frame_or_series): res3 = obj2.fillna("foo", downcast=np.dtype(np.int32)) tm.assert_equal(res3, expected) - @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) def test_fillna_dictlike_value_duplicate_colnames(self, columns): # GH#43476
Backport PR #48254: REF: avoid FutureWarning about using deprecates loc.__setitem__ non-inplace usage
https://api.github.com/repos/pandas-dev/pandas/pulls/48353
2022-09-01T21:28:38Z
2022-09-02T16:21:43Z
2022-09-02T16:21:43Z
2022-09-02T16:21:43Z
Added test for `assert_index_equal` to check that function raises an exception if two different types
diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index 1fa7b979070a7..0b2c2e12a2d2a 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -2,6 +2,7 @@ import pytest from pandas import ( + NA, Categorical, CategoricalIndex, Index, @@ -238,6 +239,21 @@ def test_index_equal_range_categories(check_categorical, exact): ) +def test_assert_index_equal_different_inferred_types(): + # GH#31884 + msg = """\ +Index are different + +Attribute "inferred_type" are different +\\[left\\]: mixed +\\[right\\]: datetime""" + + idx1 = Index([NA, np.datetime64("nat")]) + idx2 = Index([NA, NaT]) + with pytest.raises(AssertionError, match=msg): + tm.assert_index_equal(idx1, idx2) + + def test_assert_index_equal_different_names_check_order_false(): # GH#47328 idx1 = Index([1, 3], name="a")
- [x] closes #31884 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48351
2022-09-01T20:17:44Z
2022-09-02T21:32:44Z
2022-09-02T21:32:44Z
2022-10-13T17:00:32Z
Backport PR #48334 on branch 1.5.x (BUG: read_html(extract_links=all) with no header)
diff --git a/pandas/io/html.py b/pandas/io/html.py index f890ad86519df..acf98a2f83921 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -34,6 +34,7 @@ from pandas import isna from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.indexes.base import Index +from pandas.core.indexes.multi import MultiIndex from pandas.io.common import ( file_exists, @@ -1009,9 +1010,11 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, extract_links, ** try: df = _data_to_frame(data=table, **kwargs) # Cast MultiIndex header to an Index of tuples when extracting header - # links and replace nan with None. + # links and replace nan with None (therefore can't use mi.to_flat_index()). # This maintains consistency of selection (e.g. df.columns.str[1]) - if extract_links in ("all", "header"): + if extract_links in ("all", "header") and isinstance( + df.columns, MultiIndex + ): df.columns = Index( ((col[0], None if isna(col[1]) else col[1]) for col in df.columns), tupleize_cols=False, diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 045c22f106105..de0d4c1b49ea5 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -1416,3 +1416,18 @@ def test_extract_links_bad(self, spam_data): ) with pytest.raises(ValueError, match=msg): read_html(spam_data, extract_links="incorrect") + + def test_extract_links_all_no_header(self): + # GH 48316 + data = """ + <table> + <tr> + <td> + <a href='https://google.com'>Google.com</a> + </td> + </tr> + </table> + """ + result = self.read_html(data, extract_links="all")[0] + expected = DataFrame([[("Google.com", "https://google.com")]]) + tm.assert_frame_equal(result, expected)
Backport PR #48334: BUG: read_html(extract_links=all) with no header
https://api.github.com/repos/pandas-dev/pandas/pulls/48350
2022-09-01T19:28:28Z
2022-09-02T16:21:57Z
2022-09-02T16:21:57Z
2022-09-02T16:21:58Z
REF: simplify Block.diff
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e471e7efb20ae..eb265dd655e34 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9241,8 +9241,14 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: periods = int(periods) axis = self._get_axis_number(axis) - if axis == 1 and periods != 0: - return self - self.shift(periods, axis=axis) + if axis == 1: + if periods != 0: + # in the periods == 0 case, this is equivalent diff of 0 periods + # along axis=0, and the Manager method may be somewhat more + # performant, so we dispatch in that case. + return self - self.shift(periods, axis=axis) + # With periods=0 this is equivalent to a diff with axis=0 + axis = 0 new_data = self._mgr.diff(n=periods, axis=axis) return self._constructor(new_data).__finalize__(self, "diff") diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index dcf69dfda1ae8..3e0a8df79b037 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -363,11 +363,7 @@ def putmask(self: T, mask, new, align: bool = True) -> T: ) def diff(self: T, n: int, axis: int) -> T: - if axis == 1: - # DataFrame only calls this for n=0, in which case performing it - # with axis=0 is equivalent - assert n == 0 - axis = 0 + assert self.ndim == 2 and axis == 0 # caller ensures return self.apply(algos.diff, n=n, axis=axis) def interpolate(self: T, **kwargs) -> T: diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 010358d3a21ec..d49945b2a67cc 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1271,6 +1271,7 @@ def interpolate( def diff(self, n: int, axis: int = 1) -> list[Block]: """return block for the diff of the values""" + # only reached with ndim == 2 and axis == 1 new_values = algos.diff(self.values, n, axis=axis) return [self.make_block(values=new_values)] @@ -1830,17 +1831,10 @@ def getitem_block_index(self, slicer: slice) -> ExtensionBlock: return type(self)(new_values, self._mgr_locs, ndim=self.ndim) def diff(self, n: int, axis: int = 1) -> list[Block]: - if axis == 0 and n != 0: - # n==0 case will be a no-op so let is fall through - # Since we only have one column, the result will be all-NA. - # Create this result by shifting along axis=0 past the length of - # our values. - return super().diff(len(self.values), axis=0) - if axis == 1: - # TODO(EA2D): unnecessary with 2D EAs - # we are by definition 1D. - axis = 0 - return super().diff(n, axis) + # only reached with ndim == 2 and axis == 1 + # TODO(EA2D): Can share with NDArrayBackedExtensionBlock + new_values = algos.diff(self.values, n, axis=0) + return [self.make_block(values=new_values)] def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Block]: """ @@ -1964,6 +1958,7 @@ def diff(self, n: int, axis: int = 0) -> list[Block]: The arguments here are mimicking shift so they are called correctly by apply. """ + # only reached with ndim == 2 and axis == 1 values = self.values new_values = values - values.shift(n, axis=axis) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 900bb077b6014..cfacfc2b38553 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -413,6 +413,7 @@ def putmask(self, mask, new, align: bool = True): ) def diff(self: T, n: int, axis: int) -> T: + # only reached with self.ndim == 2 and axis == 1 axis = self._normalize_axis(axis) return self.apply("diff", n=n, axis=axis)
- [ ] closes #xxxx (Replace xxxx with the Github issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/48348
2022-09-01T15:13:50Z
2022-09-09T18:09:32Z
2022-09-09T18:09:32Z
2022-10-13T17:00:31Z
ENH: __pandas_priority__
diff --git a/doc/source/development/extending.rst b/doc/source/development/extending.rst index c7286616672b9..1d52a5595472b 100644 --- a/doc/source/development/extending.rst +++ b/doc/source/development/extending.rst @@ -488,3 +488,49 @@ registers the default "matplotlib" backend as follows. More information on how to implement a third-party plotting backend can be found at https://github.com/pandas-dev/pandas/blob/main/pandas/plotting/__init__.py#L1. + +.. _extending.pandas_priority: + +Arithmetic with 3rd party types +------------------------------- + +In order to control how arithmetic works between a custom type and a pandas type, +implement ``__pandas_priority__``. Similar to numpy's ``__array_priority__`` +semantics, arithmetic methods on :class:`DataFrame`, :class:`Series`, and :class:`Index` +objects will delegate to ``other``, if it has an attribute ``__pandas_priority__`` with a higher value. + +By default, pandas objects try to operate with other objects, even if they are not types known to pandas: + +.. code-block:: python + + >>> pd.Series([1, 2]) + [10, 20] + 0 11 + 1 22 + dtype: int64 + +In the example above, if ``[10, 20]`` was a custom type that can be understood as a list, pandas objects will still operate with it in the same way. + +In some cases, it is useful to delegate to the other type the operation. For example, consider I implement a +custom list object, and I want the result of adding my custom list with a pandas :class:`Series` to be an instance of my list +and not a :class:`Series` as seen in the previous example. This is now possible by defining the ``__pandas_priority__`` attribute +of my custom list, and setting it to a higher value, than the priority of the pandas objects I want to operate with. + +The ``__pandas_priority__`` of :class:`DataFrame`, :class:`Series`, and :class:`Index` are ``4000``, ``3000``, and ``2000`` respectively. The base ``ExtensionArray.__pandas_priority__`` is ``1000``. + +.. code-block:: python + + class CustomList(list): + __pandas_priority__ = 5000 + + def __radd__(self, other): + # return `self` and not the addition for simplicity + return self + + custom = CustomList() + series = pd.Series([1, 2, 3]) + + # Series refuses to add custom, since it's an unknown type with higher priority + assert series.__add__(custom) is NotImplemented + + # This will cause the custom class `__radd__` being used instead + assert series + custom is custom diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 7e8403c94ceef..ccf76f0fbc7fd 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -28,6 +28,7 @@ enhancement2 Other enhancements ^^^^^^^^^^^^^^^^^^ +- Implemented ``__pandas_priority__`` to allow custom types to take precedence over :class:`DataFrame`, :class:`Series`, :class:`Index`, or :class:`ExtensionArray` for arithmetic operations, :ref:`see the developer guide <extending.pandas_priority>` (:issue:`48347`) - :meth:`MultiIndex.sort_values` now supports ``na_position`` (:issue:`51612`) - :meth:`MultiIndex.sortlevel` and :meth:`Index.sortlevel` gained a new keyword ``na_position`` (:issue:`51612`) - Improve error message when setting :class:`DataFrame` with wrong number of columns through :meth:`DataFrame.isetitem` (:issue:`51701`) diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index bbfe9b9bbb6c7..8c269244c37ce 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -235,6 +235,12 @@ class ExtensionArray: # Don't override this. _typ = "extension" + # similar to __array_priority__, positions ExtensionArray after Index, + # Series, and DataFrame. EA subclasses may override to choose which EA + # subclass takes priority. If overriding, the value should always be + # strictly less than 2000 to be below Index.__pandas_priority__. + __pandas_priority__ = 1000 + # ------------------------------------------------------------------------ # Constructors # ------------------------------------------------------------------------ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 70019030da182..bc28cc425a412 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -634,6 +634,10 @@ class DataFrame(NDFrame, OpsMixin): _hidden_attrs: frozenset[str] = NDFrame._hidden_attrs | frozenset([]) _mgr: BlockManager | ArrayManager + # similar to __array_priority__, positions DataFrame before Series, Index, + # and ExtensionArray. Should NOT be overridden by subclasses. + __pandas_priority__ = 4000 + @property def _constructor(self) -> Callable[..., DataFrame]: return DataFrame diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 620823b9703ab..2f658006cf93f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -351,6 +351,10 @@ class Index(IndexOpsMixin, PandasObject): # To hand over control to subclasses _join_precedence = 1 + # similar to __array_priority__, positions Index after Series and DataFrame + # but before ExtensionArray. Should NOT be overridden by subclasses. + __pandas_priority__ = 2000 + # Cython methods; see github.com/cython/cython/issues/2647 # for why we need to wrap these instead of making them class attributes # Moreover, cython will choose the appropriate-dtyped sub-function diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py index 01fb9aa17fc48..f8f53310e773b 100644 --- a/pandas/core/ops/common.py +++ b/pandas/core/ops/common.py @@ -14,7 +14,6 @@ from pandas._libs.missing import is_matching_na from pandas.core.dtypes.generic import ( - ABCDataFrame, ABCIndex, ABCSeries, ) @@ -75,10 +74,10 @@ def new_method(self, other): # For comparison ops, Index does *not* defer to Series pass else: - for cls in [ABCDataFrame, ABCSeries, ABCIndex]: - if isinstance(self, cls): - break - if isinstance(other, cls): + prio = getattr(other, "__pandas_priority__", None) + if prio is not None: + if prio > self.__pandas_priority__: + # e.g. other is DataFrame while self is Index/Series/EA return NotImplemented other = item_from_zerodim(other) diff --git a/pandas/core/series.py b/pandas/core/series.py index e8d6491e43007..58cd42eaa7ca3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -352,6 +352,10 @@ class Series(base.IndexOpsMixin, NDFrame): # type: ignore[misc] base.IndexOpsMixin._hidden_attrs | NDFrame._hidden_attrs | frozenset([]) ) + # similar to __array_priority__, positions Series after DataFrame + # but before Index and ExtensionArray. Should NOT be overridden by subclasses. + __pandas_priority__ = 3000 + # Override cache_readonly bc Series is mutable # error: Incompatible types in assignment (expression has type "property", # base class "IndexOpsMixin" defined the type as "Callable[[IndexOpsMixin], bool]") diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index b17dce234043c..a97676578c079 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -267,3 +267,19 @@ def test_frame_setitem_dask_array_into_new_col(): tm.assert_frame_equal(result, expected) finally: pd.set_option("compute.use_numexpr", olduse) + + +def test_pandas_priority(): + # GH#48347 + + class MyClass: + __pandas_priority__ = 5000 + + def __radd__(self, other): + return self + + left = MyClass() + right = Series(range(3)) + + assert right.__add__(left) is NotImplemented + assert right + left is left
Will allow dask/modin to address #38946 and https://github.com/modin-project/modin/issues/4646, respectively. Also can be used to make non-masked EAs defer to masked EAs.
https://api.github.com/repos/pandas-dev/pandas/pulls/48347
2022-09-01T15:00:56Z
2023-03-14T18:06:38Z
2023-03-14T18:06:38Z
2023-03-14T18:34:34Z
Backport PR #48324 on branch 1.5.x (BUG: Add note in whatsnew for DataFrame.at behavior change)
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 5471beba44486..75941a3d8edef 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -1081,7 +1081,7 @@ Indexing - Bug in :meth:`DataFrame.sum` min_count changes dtype if input contains NaNs (:issue:`46947`) - Bug in :class:`IntervalTree` that lead to an infinite recursion. (:issue:`46658`) - Bug in :class:`PeriodIndex` raising ``AttributeError`` when indexing on ``NA``, rather than putting ``NaT`` in its place. (:issue:`46673`) -- +- Bug in :meth:`DataFrame.at` would allow the modification of multiple columns (:issue:`48296`) Missing ^^^^^^^ diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py index 96c73b007cef3..1e502ca70189a 100644 --- a/pandas/tests/indexing/test_at.py +++ b/pandas/tests/indexing/test_at.py @@ -6,6 +6,8 @@ import numpy as np import pytest +from pandas.errors import InvalidIndexError + from pandas import ( CategoricalDtype, CategoricalIndex, @@ -192,6 +194,12 @@ def test_at_frame_raises_key_error2(self, indexer_al): with pytest.raises(KeyError, match="^0$"): indexer_al(df)["a", 0] + def test_at_frame_multiple_columns(self): + # GH#48296 - at shouldn't modify multiple columns + df = DataFrame({"a": [1, 2], "b": [3, 4]}) + with pytest.raises(InvalidIndexError, match=r"slice\(None, None, None\)"): + df.at[5] = [6, 7] + def test_at_getitem_mixed_index_no_fallback(self): # GH#19860 ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2])
Backport PR #48324: BUG: Add note in whatsnew for DataFrame.at behavior change
https://api.github.com/repos/pandas-dev/pandas/pulls/48345
2022-09-01T07:16:30Z
2022-09-01T08:56:31Z
2022-09-01T08:56:31Z
2022-09-01T08:56:31Z
DOC: Correct return type of read_csv
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index 1c3d37912743b..4c8437736ea35 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -427,7 +427,7 @@ Returns ------- -DataFrame or TextParser +DataFrame or TextFileReader A comma-separated values (csv) file is returned as two-dimensional data structure with labeled axes.
- [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
https://api.github.com/repos/pandas-dev/pandas/pulls/48343
2022-09-01T06:51:13Z
2022-09-01T08:57:13Z
2022-09-01T08:57:13Z
2022-10-13T17:00:31Z
Backport PR #48336 on branch 1.5.x (DOC: Add whatsnew note for #45404)
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 5471beba44486..1cef615a7706b 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -1060,6 +1060,7 @@ Indexing - Bug when setting a value too large for a :class:`Series` dtype failing to coerce to a common type (:issue:`26049`, :issue:`32878`) - Bug in :meth:`loc.__setitem__` treating ``range`` keys as positional instead of label-based (:issue:`45479`) - Bug in :meth:`DataFrame.__setitem__` casting extension array dtypes to object when setting with a scalar key and :class:`DataFrame` as value (:issue:`46896`) +- Bug in :meth:`Series.__setitem__` when setting a scalar to a nullable pandas dtype would not raise a ``TypeError`` if the scalar could not be cast (losslessly) to the nullable type (:issue:`45404`) - Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`) - Bug in :meth:`Series.loc` raising with boolean indexer containing ``NA`` when :class:`Index` did not match (:issue:`46551`) - Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtype :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`)
Backport PR #48336: DOC: Add whatsnew note for #45404
https://api.github.com/repos/pandas-dev/pandas/pulls/48341
2022-09-01T00:19:14Z
2022-09-01T08:57:41Z
2022-09-01T08:57:41Z
2022-09-01T08:57:42Z