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
BUG: Better handling of invalid na_option argument for groupby.rank
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index e9d4225c3dbd9..3dff5eed8a81a 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -653,6 +653,7 @@ Reshaping - Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``datetime64[ns, tz]`` dtype (:issue:`21546`) - Bug in :meth:`Series.mask` and :meth:`DataFrame.mask` with ``list`` conditionals (:issue:`21891`) - Bug in :meth:`DataFrame.replace` raises RecursionError when converting OutOfBounds ``datetime64[ns, tz]`` (:issue:`20380`) +- :func:`pandas.core.groupby.GroupBy.rank` now raises a ``ValueError`` when an invalid value is passed for argument ``na_option`` (:issue:`22124`) - Build Changes diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 4b0143b3e1ced..3f84fa0f0670e 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1705,6 +1705,9 @@ def rank(self, method='average', ascending=True, na_option='keep', ----- DataFrame with ranking of values within each group """ + if na_option not in {'keep', 'top', 'bottom'}: + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + raise ValueError(msg) return self._cython_transform('rank', numeric_only=False, ties_method=method, ascending=ascending, na_option=na_option, pct=pct, axis=axis) diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index 0628f9c79a154..f0dcf768e3607 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -172,35 +172,35 @@ def test_infs_n_nans(grps, vals, ties_method, ascending, na_option, exp): [3., 3., np.nan, 1., 3., 2., np.nan, np.nan]), ('dense', False, 'keep', True, [3. / 3., 3. / 3., np.nan, 1. / 3., 3. / 3., 2. / 3., np.nan, np.nan]), - ('average', True, 'no_na', False, [2., 2., 7., 5., 2., 4., 7., 7.]), - ('average', True, 'no_na', True, + ('average', True, 'bottom', False, [2., 2., 7., 5., 2., 4., 7., 7.]), + ('average', True, 'bottom', True, [0.25, 0.25, 0.875, 0.625, 0.25, 0.5, 0.875, 0.875]), - ('average', False, 'no_na', False, [4., 4., 7., 1., 4., 2., 7., 7.]), - ('average', False, 'no_na', True, + ('average', False, 'bottom', False, [4., 4., 7., 1., 4., 2., 7., 7.]), + ('average', False, 'bottom', True, [0.5, 0.5, 0.875, 0.125, 0.5, 0.25, 0.875, 0.875]), - ('min', True, 'no_na', False, [1., 1., 6., 5., 1., 4., 6., 6.]), - ('min', True, 'no_na', True, + ('min', True, 'bottom', False, [1., 1., 6., 5., 1., 4., 6., 6.]), + ('min', True, 'bottom', True, [0.125, 0.125, 0.75, 0.625, 0.125, 0.5, 0.75, 0.75]), - ('min', False, 'no_na', False, [3., 3., 6., 1., 3., 2., 6., 6.]), - ('min', False, 'no_na', True, + ('min', False, 'bottom', False, [3., 3., 6., 1., 3., 2., 6., 6.]), + ('min', False, 'bottom', True, [0.375, 0.375, 0.75, 0.125, 0.375, 0.25, 0.75, 0.75]), - ('max', True, 'no_na', False, [3., 3., 8., 5., 3., 4., 8., 8.]), - ('max', True, 'no_na', True, + ('max', True, 'bottom', False, [3., 3., 8., 5., 3., 4., 8., 8.]), + ('max', True, 'bottom', True, [0.375, 0.375, 1., 0.625, 0.375, 0.5, 1., 1.]), - ('max', False, 'no_na', False, [5., 5., 8., 1., 5., 2., 8., 8.]), - ('max', False, 'no_na', True, + ('max', False, 'bottom', False, [5., 5., 8., 1., 5., 2., 8., 8.]), + ('max', False, 'bottom', True, [0.625, 0.625, 1., 0.125, 0.625, 0.25, 1., 1.]), - ('first', True, 'no_na', False, [1., 2., 6., 5., 3., 4., 7., 8.]), - ('first', True, 'no_na', True, + ('first', True, 'bottom', False, [1., 2., 6., 5., 3., 4., 7., 8.]), + ('first', True, 'bottom', True, [0.125, 0.25, 0.75, 0.625, 0.375, 0.5, 0.875, 1.]), - ('first', False, 'no_na', False, [3., 4., 6., 1., 5., 2., 7., 8.]), - ('first', False, 'no_na', True, + ('first', False, 'bottom', False, [3., 4., 6., 1., 5., 2., 7., 8.]), + ('first', False, 'bottom', True, [0.375, 0.5, 0.75, 0.125, 0.625, 0.25, 0.875, 1.]), - ('dense', True, 'no_na', False, [1., 1., 4., 3., 1., 2., 4., 4.]), - ('dense', True, 'no_na', True, + ('dense', True, 'bottom', False, [1., 1., 4., 3., 1., 2., 4., 4.]), + ('dense', True, 'bottom', True, [0.25, 0.25, 1., 0.75, 0.25, 0.5, 1., 1.]), - ('dense', False, 'no_na', False, [3., 3., 4., 1., 3., 2., 4., 4.]), - ('dense', False, 'no_na', True, + ('dense', False, 'bottom', False, [3., 3., 4., 1., 3., 2., 4., 4.]), + ('dense', False, 'bottom', True, [0.75, 0.75, 1., 0.25, 0.75, 0.5, 1., 1.]) ]) def test_rank_args_missing(grps, vals, ties_method, ascending, @@ -252,14 +252,24 @@ def test_rank_object_raises(ties_method, ascending, na_option, with tm.assert_raises_regex(TypeError, "not callable"): df.groupby('key').rank(method=ties_method, ascending=ascending, - na_option='bad', pct=pct) + na_option=na_option, pct=pct) - with tm.assert_raises_regex(TypeError, "not callable"): - df.groupby('key').rank(method=ties_method, - ascending=ascending, - na_option=True, pct=pct) - with tm.assert_raises_regex(TypeError, "not callable"): +@pytest.mark.parametrize("na_option", [True, "bad", 1]) +@pytest.mark.parametrize("ties_method", [ + 'average', 'min', 'max', 'first', 'dense']) +@pytest.mark.parametrize("ascending", [True, False]) +@pytest.mark.parametrize("pct", [True, False]) +@pytest.mark.parametrize("vals", [ + ['bar', 'bar', 'foo', 'bar', 'baz'], + ['bar', np.nan, 'foo', np.nan, 'baz'], + [1, np.nan, 2, np.nan, 3] +]) +def test_rank_naoption_raises(ties_method, ascending, na_option, pct, vals): + df = DataFrame({'key': ['foo'] * 5, 'val': vals}) + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + + with tm.assert_raises_regex(ValueError, msg): df.groupby('key').rank(method=ties_method, ascending=ascending, na_option=na_option, pct=pct)
- [x] closes #22124 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff - [x] whatsnew entry This is also related to #19499
https://api.github.com/repos/pandas-dev/pandas/pulls/22125
2018-07-30T05:34:27Z
2018-08-01T22:10:54Z
2018-08-01T22:10:54Z
2018-08-02T00:58:20Z
Lint configuration followup
diff --git a/ci/lint.sh b/ci/lint.sh index 9fc283c04f09e..ec99e1e559d6e 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -8,6 +8,17 @@ RET=0 if [ "$LINT" ]; then + # We're ignoring the following codes across the board + #E402, # module level import not at top of file + #E731, # do not assign a lambda expression, use a def + #E741, # do not use variables named 'l', 'O', or 'I' + #W503, # line break before binary operator + #C405, # Unnecessary (list/tuple) literal - rewrite as a set literal. + #C406, # Unnecessary (list/tuple) literal - rewrite as a dict literal. + #C408, # Unnecessary (dict/list/tuple) call - rewrite as a literal. + #C409, # Unnecessary (list/tuple) passed to tuple() - (remove the outer call to tuple()/rewrite as a tuple literal). + #C410 # Unnecessary (list/tuple) passed to list() - (remove the outer call to list()/rewrite as a list literal). + # pandas/_libs/src is C code, so no need to search there. echo "Linting *.py" flake8 pandas --filename=*.py --exclude pandas/_libs/src --ignore=C405,C406,C408,C409,C410,E402,E731,E741,W503 diff --git a/ci/requirements_dev.txt b/ci/requirements_dev.txt index 83ee30b52071d..c89aae8f2ffca 100644 --- a/ci/requirements_dev.txt +++ b/ci/requirements_dev.txt @@ -1,8 +1,9 @@ # This file was autogenerated by scripts/convert_deps.py # Do not modify directly -Cython +Cython>=0.28.2 NumPy flake8 +flake8-comprehensions moto pytest>=3.1 python-dateutil>=2.5.0 diff --git a/setup.cfg b/setup.cfg index 9ec967c25e225..d00d527da49e2 100644 --- a/setup.cfg +++ b/setup.cfg @@ -16,7 +16,12 @@ ignore = E402, # module level import not at top of file E731, # do not assign a lambda expression, use a def E741, # do not use variables named 'l', 'O', or 'I' - W503 # line break before binary operator + W503, # line break before binary operator + C405, # Unnecessary (list/tuple) literal - rewrite as a set literal. + C406, # Unnecessary (list/tuple) literal - rewrite as a dict literal. + C408, # Unnecessary (dict/list/tuple) call - rewrite as a literal. + C409, # Unnecessary (list/tuple) passed to tuple() - (remove the outer call to tuple()/rewrite as a tuple literal). + C410 # Unnecessary (list/tuple) passed to list() - (remove the outer call to list()/rewrite as a list literal). max-line-length = 79 [yapf]
Post #22075 - Ran scripts/convert_deps.py - Documented flake8 checks we are ignoring cc @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/22123
2018-07-30T01:16:34Z
2018-07-30T10:00:24Z
2018-07-30T10:00:24Z
2018-07-30T15:21:44Z
DOC: Fix spaces and brackets in ValueError message for option_context.
diff --git a/pandas/core/config.py b/pandas/core/config.py index 369e0568346ef..abcdbfa12e4e9 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -391,7 +391,7 @@ class option_context(object): def __init__(self, *args): if not (len(args) % 2 == 0 and len(args) >= 2): raise ValueError('Need to invoke as' - 'option_context(pat, val, [(pat, val), ...)).') + ' option_context(pat, val, [(pat, val), ...]).') self.ops = list(zip(args[::2], args[1::2]))
Add a missing space and changed a parenthesis to a bracket in the message of the ValueError raised whenever the `args` in `option_context(*args)` don't meet requirements. 'Need to invoke asoption_context(pat, val, [(pat, val), ...)).' -> 'Need to invoke as option_context(pat, val, [(pat, val), ...]).' - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/22121
2018-07-29T22:19:10Z
2018-07-30T10:06:32Z
2018-07-30T10:06:32Z
2018-07-30T10:06:36Z
Centralize m8[ns] Arithmetic Tests
diff --git a/pandas/tests/indexes/timedeltas/test_arithmetic.py b/pandas/tests/indexes/timedeltas/test_arithmetic.py index d47d75d2f3485..a5e75de2a267e 100644 --- a/pandas/tests/indexes/timedeltas/test_arithmetic.py +++ b/pandas/tests/indexes/timedeltas/test_arithmetic.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- -import operator import pytest import numpy as np @@ -13,7 +12,6 @@ Series, Timestamp, Timedelta) from pandas.errors import PerformanceWarning, NullFrequencyError -from pandas.core import ops @pytest.fixture(params=[pd.offsets.Hour(2), timedelta(hours=2), @@ -270,53 +268,6 @@ def test_tdi_floordiv_timedelta_scalar(self, scalar_td): class TestTimedeltaIndexArithmetic(object): # Addition and Subtraction Operations - # ------------------------------------------------------------- - # Invalid Operations - - @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])]) - @pytest.mark.parametrize('op', [operator.add, ops.radd, - operator.sub, ops.rsub]) - def test_tdi_add_sub_float(self, op, other): - dti = DatetimeIndex(['2011-01-01', '2011-01-02'], freq='D') - tdi = dti - dti.shift(1) - with pytest.raises(TypeError): - op(tdi, other) - - def test_tdi_add_str_invalid(self): - # GH 13624 - tdi = TimedeltaIndex(['1 day', '2 days']) - - with pytest.raises(TypeError): - tdi + 'a' - with pytest.raises(TypeError): - 'a' + tdi - - @pytest.mark.parametrize('freq', [None, 'H']) - def test_tdi_sub_period(self, freq): - # GH#13078 - # not supported, check TypeError - p = pd.Period('2011-01-01', freq='D') - - idx = pd.TimedeltaIndex(['1 hours', '2 hours'], freq=freq) - - with pytest.raises(TypeError): - idx - p - - with pytest.raises(TypeError): - p - idx - - @pytest.mark.parametrize('op', [operator.add, ops.radd, - operator.sub, ops.rsub]) - @pytest.mark.parametrize('pi_freq', ['D', 'W', 'Q', 'H']) - @pytest.mark.parametrize('tdi_freq', [None, 'H']) - def test_dti_sub_pi(self, tdi_freq, pi_freq, op): - # GH#20049 subtracting PeriodIndex should raise TypeError - tdi = pd.TimedeltaIndex(['1 hours', '2 hours'], freq=tdi_freq) - dti = pd.Timestamp('2018-03-07 17:16:40') + tdi - pi = dti.to_period(pi_freq) - with pytest.raises(TypeError): - op(dti, pi) - # ------------------------------------------------------------- # TimedeltaIndex.shift is used by __add__/__sub__ @@ -626,29 +577,6 @@ def test_tdi_isub_timedeltalike(self, delta): rng -= delta tm.assert_index_equal(rng, expected) - # ------------------------------------------------------------- - # Binary operations TimedeltaIndex and datetime-like - - def test_tdi_sub_timestamp_raises(self): - idx = TimedeltaIndex(['1 day', '2 day']) - msg = "cannot subtract a datelike from a TimedeltaIndex" - with tm.assert_raises_regex(TypeError, msg): - idx - Timestamp('2011-01-01') - - def test_tdi_add_timestamp(self): - idx = TimedeltaIndex(['1 day', '2 day']) - - result = idx + Timestamp('2011-01-01') - expected = DatetimeIndex(['2011-01-02', '2011-01-03']) - tm.assert_index_equal(result, expected) - - def test_tdi_radd_timestamp(self): - idx = TimedeltaIndex(['1 day', '2 day']) - - result = Timestamp('2011-01-01') + idx - expected = DatetimeIndex(['2011-01-02', '2011-01-03']) - tm.assert_index_equal(result, expected) - # ------------------------------------------------------------- # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64] diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 2571498ca802c..c091df63fcfc7 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -6,21 +6,13 @@ import numpy as np import pytest -from pandas import Series, Timestamp, Timedelta, Period, NaT +from pandas import Series, Timestamp, Period from pandas._libs.tslibs.period import IncompatibleFrequency import pandas as pd import pandas.util.testing as tm -@pytest.fixture -def tdser(): - """ - Return a Series with dtype='timedelta64[ns]', including a NaT. - """ - return Series(['59 Days', '59 Days', 'NaT'], dtype='timedelta64[ns]') - - # ------------------------------------------------------------------ # Comparisons @@ -552,342 +544,3 @@ def test_dt64ser_sub_datetime_dtype(self): ser = Series([ts]) result = pd.to_timedelta(np.abs(ser - dt)) assert result.dtype == 'timedelta64[ns]' - - -class TestTimedeltaSeriesAdditionSubtraction(object): - # Tests for Series[timedelta64[ns]] __add__, __sub__, __radd__, __rsub__ - - # ------------------------------------------------------------------ - # Operations with int-like others - - def test_td64series_add_int_series_invalid(self, tdser): - with pytest.raises(TypeError): - tdser + Series([2, 3, 4]) - - @pytest.mark.xfail(reason='GH#19123 integer interpreted as nanoseconds') - def test_td64series_radd_int_series_invalid(self, tdser): - with pytest.raises(TypeError): - Series([2, 3, 4]) + tdser - - def test_td64series_sub_int_series_invalid(self, tdser): - with pytest.raises(TypeError): - tdser - Series([2, 3, 4]) - - @pytest.mark.xfail(reason='GH#19123 integer interpreted as nanoseconds') - def test_td64series_rsub_int_series_invalid(self, tdser): - with pytest.raises(TypeError): - Series([2, 3, 4]) - tdser - - def test_td64_series_add_intlike(self): - # GH#19123 - tdi = pd.TimedeltaIndex(['59 days', '59 days', 'NaT']) - ser = Series(tdi) - - other = Series([20, 30, 40], dtype='uint8') - - pytest.raises(TypeError, ser.__add__, 1) - pytest.raises(TypeError, ser.__sub__, 1) - - pytest.raises(TypeError, ser.__add__, other) - pytest.raises(TypeError, ser.__sub__, other) - - pytest.raises(TypeError, ser.__add__, other.values) - pytest.raises(TypeError, ser.__sub__, other.values) - - pytest.raises(TypeError, ser.__add__, pd.Index(other)) - pytest.raises(TypeError, ser.__sub__, pd.Index(other)) - - @pytest.mark.parametrize('scalar', [1, 1.5, np.array(2)]) - def test_td64series_add_sub_numeric_scalar_invalid(self, scalar, tdser): - with pytest.raises(TypeError): - tdser + scalar - with pytest.raises(TypeError): - scalar + tdser - with pytest.raises(TypeError): - tdser - scalar - with pytest.raises(TypeError): - scalar - tdser - - @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', - 'uint64', 'uint32', 'uint16', 'uint8', - 'float64', 'float32', 'float16']) - @pytest.mark.parametrize('vector', [ - np.array([1, 2, 3]), - pd.Index([1, 2, 3]), - pytest.param(Series([1, 2, 3]), - marks=pytest.mark.xfail(reason='GH#19123 integer ' - 'interpreted as nanos')) - ]) - def test_td64series_add_sub_numeric_array_invalid(self, vector, - dtype, tdser): - vector = vector.astype(dtype) - with pytest.raises(TypeError): - tdser + vector - with pytest.raises(TypeError): - vector + tdser - with pytest.raises(TypeError): - tdser - vector - with pytest.raises(TypeError): - vector - tdser - - # ------------------------------------------------------------------ - # Operations with datetime-like others - - def test_td64series_add_sub_timestamp(self): - # GH#11925 - tdser = Series(pd.timedelta_range('1 day', periods=3)) - ts = Timestamp('2012-01-01') - expected = Series(pd.date_range('2012-01-02', periods=3)) - tm.assert_series_equal(ts + tdser, expected) - tm.assert_series_equal(tdser + ts, expected) - - expected2 = Series(pd.date_range('2011-12-31', periods=3, freq='-1D')) - tm.assert_series_equal(ts - tdser, expected2) - tm.assert_series_equal(ts + (-tdser), expected2) - - with pytest.raises(TypeError): - tdser - ts - - # ------------------------------------------------------------------ - # Operations with timedelta-like others (including DateOffsets) - - @pytest.mark.parametrize('names', [(None, None, None), - ('Egon', 'Venkman', None), - ('NCC1701D', 'NCC1701D', 'NCC1701D')]) - def test_td64_series_with_tdi(self, names): - # GH#17250 make sure result dtype is correct - # GH#19043 make sure names are propagated correctly - tdi = pd.TimedeltaIndex(['0 days', '1 day'], name=names[0]) - ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[1]) - expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], - name=names[2]) - - result = tdi + ser - tm.assert_series_equal(result, expected) - assert result.dtype == 'timedelta64[ns]' - - result = ser + tdi - tm.assert_series_equal(result, expected) - assert result.dtype == 'timedelta64[ns]' - - expected = Series([Timedelta(hours=-3), Timedelta(days=1, hours=-4)], - name=names[2]) - - result = tdi - ser - tm.assert_series_equal(result, expected) - assert result.dtype == 'timedelta64[ns]' - - result = ser - tdi - tm.assert_series_equal(result, -expected) - assert result.dtype == 'timedelta64[ns]' - - def test_td64_sub_NaT(self): - # GH#18808 - ser = Series([NaT, Timedelta('1s')]) - res = ser - NaT - expected = Series([NaT, NaT], dtype='timedelta64[ns]') - tm.assert_series_equal(res, expected) - - -class TestTimedeltaSeriesMultiplicationDivision(object): - # Tests for Series[timedelta64[ns]] - # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__ - - # ------------------------------------------------------------------ - # __floordiv__, __rfloordiv__ - - @pytest.mark.parametrize('scalar_td', [ - timedelta(minutes=5, seconds=4), - Timedelta('5m4s'), - Timedelta('5m4s').to_timedelta64()]) - def test_timedelta_floordiv(self, scalar_td): - # GH#18831 - td1 = Series([timedelta(minutes=5, seconds=3)] * 3) - td1.iloc[2] = np.nan - - result = td1 // scalar_td - expected = Series([0, 0, np.nan]) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('scalar_td', [ - timedelta(minutes=5, seconds=4), - Timedelta('5m4s'), - Timedelta('5m4s').to_timedelta64()]) - def test_timedelta_rfloordiv(self, scalar_td): - # GH#18831 - td1 = Series([timedelta(minutes=5, seconds=3)] * 3) - td1.iloc[2] = np.nan - result = scalar_td // td1 - expected = Series([1, 1, np.nan]) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('scalar_td', [ - timedelta(minutes=5, seconds=4), - Timedelta('5m4s'), - Timedelta('5m4s').to_timedelta64()]) - def test_timedelta_rfloordiv_explicit(self, scalar_td): - # GH#18831 - td1 = Series([timedelta(minutes=5, seconds=3)] * 3) - td1.iloc[2] = np.nan - - # We can test __rfloordiv__ using this syntax, - # see `test_timedelta_rfloordiv` - result = td1.__rfloordiv__(scalar_td) - expected = Series([1, 1, np.nan]) - tm.assert_series_equal(result, expected) - - # ------------------------------------------------------------------ - # Operations with int-like others - - @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', - 'uint64', 'uint32', 'uint16', 'uint8', - 'float64', 'float32', 'float16']) - @pytest.mark.parametrize('vector', [np.array([20, 30, 40]), - pd.Index([20, 30, 40]), - Series([20, 30, 40])]) - def test_td64series_div_numeric_array(self, vector, dtype, tdser): - # GH#4521 - # divide/multiply by integers - vector = vector.astype(dtype) - expected = Series(['2.95D', '1D 23H 12m', 'NaT'], - dtype='timedelta64[ns]') - - result = tdser / vector - tm.assert_series_equal(result, expected) - - with pytest.raises(TypeError): - vector / tdser - - @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', - 'uint64', 'uint32', 'uint16', 'uint8', - 'float64', 'float32', 'float16']) - @pytest.mark.parametrize('vector', [np.array([20, 30, 40]), - pd.Index([20, 30, 40]), - Series([20, 30, 40])]) - def test_td64series_mul_numeric_array(self, vector, dtype, tdser): - # GH#4521 - # divide/multiply by integers - vector = vector.astype(dtype) - - expected = Series(['1180 Days', '1770 Days', 'NaT'], - dtype='timedelta64[ns]') - - result = tdser * vector - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', - 'uint64', 'uint32', 'uint16', 'uint8', - 'float64', 'float32', 'float16']) - @pytest.mark.parametrize('vector', [ - np.array([20, 30, 40]), - pytest.param(pd.Index([20, 30, 40]), - marks=pytest.mark.xfail(reason='__mul__ raises ' - 'instead of returning ' - 'NotImplemented')), - Series([20, 30, 40]) - ]) - def test_td64series_rmul_numeric_array(self, vector, dtype, tdser): - # GH#4521 - # divide/multiply by integers - vector = vector.astype(dtype) - - expected = Series(['1180 Days', '1770 Days', 'NaT'], - dtype='timedelta64[ns]') - - result = vector * tdser - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('one', [1, np.array(1), 1.0, np.array(1.0)]) - def test_td64series_mul_numeric_scalar(self, one, tdser): - # GH#4521 - # divide/multiply by integers - expected = Series(['-59 Days', '-59 Days', 'NaT'], - dtype='timedelta64[ns]') - - result = tdser * (-one) - tm.assert_series_equal(result, expected) - result = (-one) * tdser - tm.assert_series_equal(result, expected) - - expected = Series(['118 Days', '118 Days', 'NaT'], - dtype='timedelta64[ns]') - - result = tdser * (2 * one) - tm.assert_series_equal(result, expected) - result = (2 * one) * tdser - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('two', [ - 2, 2.0, - pytest.param(np.array(2), - marks=pytest.mark.xfail(reason='GH#19011 is_list_like ' - 'incorrectly True.')), - pytest.param(np.array(2.0), - marks=pytest.mark.xfail(reason='GH#19011 is_list_like ' - 'incorrectly True.')), - ]) - def test_td64series_div_numeric_scalar(self, two, tdser): - # GH#4521 - # divide/multiply by integers - expected = Series(['29.5D', '29.5D', 'NaT'], dtype='timedelta64[ns]') - - result = tdser / two - tm.assert_series_equal(result, expected) - - # ------------------------------------------------------------------ - # Operations with timedelta-like others - - @pytest.mark.parametrize('names', [(None, None, None), - ('Egon', 'Venkman', None), - ('NCC1701D', 'NCC1701D', 'NCC1701D')]) - def test_tdi_mul_int_series(self, names): - # GH#19042 - tdi = pd.TimedeltaIndex(['0days', '1day', '2days', '3days', '4days'], - name=names[0]) - ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1]) - - expected = Series(['0days', '1day', '4days', '9days', '16days'], - dtype='timedelta64[ns]', - name=names[2]) - - result = ser * tdi - tm.assert_series_equal(result, expected) - - # The direct operation tdi * ser still needs to be fixed. - result = ser.__rmul__(tdi) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('names', [(None, None, None), - ('Egon', 'Venkman', None), - ('NCC1701D', 'NCC1701D', 'NCC1701D')]) - def test_float_series_rdiv_tdi(self, names): - # GH#19042 - # TODO: the direct operation TimedeltaIndex / Series still - # needs to be fixed. - tdi = pd.TimedeltaIndex(['0days', '1day', '2days', '3days', '4days'], - name=names[0]) - ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1]) - - expected = Series([tdi[n] / ser[n] for n in range(len(ser))], - dtype='timedelta64[ns]', - name=names[2]) - - result = ser.__rdiv__(tdi) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize('scalar_td', [ - timedelta(minutes=5, seconds=4), - Timedelta('5m4s'), - Timedelta('5m4s').to_timedelta64()]) - def test_td64series_mul_timedeltalike_invalid(self, scalar_td): - td1 = Series([timedelta(minutes=5, seconds=3)] * 3) - td1.iloc[2] = np.nan - - # check that we are getting a TypeError - # with 'operate' (from core/ops.py) for the ops that are not - # defined - pattern = 'operate|unsupported|cannot|not supported' - with tm.assert_raises_regex(TypeError, pattern): - td1 * scalar_td - with tm.assert_raises_regex(TypeError, pattern): - scalar_td * td1 diff --git a/pandas/tests/test_arithmetic.py b/pandas/tests/test_arithmetic.py index f15b629f15ae3..8ee0bf9ec874a 100644 --- a/pandas/tests/test_arithmetic.py +++ b/pandas/tests/test_arithmetic.py @@ -2,6 +2,7 @@ # Arithmetc tests for DataFrame/Series/Index/Array classes that should # behave identically. from datetime import timedelta +import operator import pytest import numpy as np @@ -9,7 +10,22 @@ import pandas as pd import pandas.util.testing as tm -from pandas import Timedelta +from pandas.core import ops +from pandas.errors import NullFrequencyError +from pandas._libs.tslibs import IncompatibleFrequency +from pandas import ( + Timedelta, Timestamp, NaT, Series, TimedeltaIndex, DatetimeIndex) + + +# ------------------------------------------------------------------ +# Fixtures + +@pytest.fixture +def tdser(): + """ + Return a Series with dtype='timedelta64[ns]', including a NaT. + """ + return Series(['59 Days', '59 Days', 'NaT'], dtype='timedelta64[ns]') # ------------------------------------------------------------------ @@ -19,7 +35,7 @@ class TestNumericArraylikeArithmeticWithTimedeltaScalar(object): @pytest.mark.parametrize('box', [ pd.Index, - pd.Series, + Series, pytest.param(pd.DataFrame, marks=pytest.mark.xfail(reason="block.eval incorrect", strict=True)) @@ -35,10 +51,10 @@ class TestNumericArraylikeArithmeticWithTimedeltaScalar(object): Timedelta(days=1).to_timedelta64(), Timedelta(days=1).to_pytimedelta()], ids=lambda x: type(x).__name__) - def test_index_mul_timedelta(self, scalar_td, index, box): + def test_numeric_arr_mul_tdscalar(self, scalar_td, index, box): # GH#19333 - if (box is pd.Series and + if (box is Series and type(scalar_td) is timedelta and index.dtype == 'f8'): raise pytest.xfail(reason="Cannot multiply timedelta by float") @@ -53,7 +69,7 @@ def test_index_mul_timedelta(self, scalar_td, index, box): commute = scalar_td * index tm.assert_equal(commute, expected) - @pytest.mark.parametrize('box', [pd.Index, pd.Series, pd.DataFrame]) + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame]) @pytest.mark.parametrize('index', [ pd.Int64Index(range(1, 3)), pd.UInt64Index(range(1, 3)), @@ -65,14 +81,14 @@ def test_index_mul_timedelta(self, scalar_td, index, box): Timedelta(days=1).to_timedelta64(), Timedelta(days=1).to_pytimedelta()], ids=lambda x: type(x).__name__) - def test_index_rdiv_timedelta(self, scalar_td, index, box): + def test_numeric_arr_rdiv_tdscalar(self, scalar_td, index, box): - if box is pd.Series and type(scalar_td) is timedelta: + if box is Series and type(scalar_td) is timedelta: raise pytest.xfail(reason="TODO: Figure out why this case fails") if box is pd.DataFrame and isinstance(scalar_td, timedelta): raise pytest.xfail(reason="TODO: Figure out why this case fails") - expected = pd.TimedeltaIndex(['1 Day', '12 Hours']) + expected = TimedeltaIndex(['1 Day', '12 Hours']) index = tm.box_expected(index, box) expected = tm.box_expected(expected, box) @@ -87,12 +103,727 @@ def test_index_rdiv_timedelta(self, scalar_td, index, box): # ------------------------------------------------------------------ # Timedelta64[ns] dtype Arithmetic Operations +class TestTimedeltaArraylikeAddSubOps(object): + # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__ + + # ------------------------------------------------------------- + # Invalid Operations + + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame], + ids=lambda x: x.__name__) + def test_td64arr_add_str_invalid(self, box): + # GH#13624 + tdi = TimedeltaIndex(['1 day', '2 days']) + tdi = tm.box_expected(tdi, box) + + with pytest.raises(TypeError): + tdi + 'a' + with pytest.raises(TypeError): + 'a' + tdi + + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame], + ids=lambda x: x.__name__) + @pytest.mark.parametrize('other', [3.14, np.array([2.0, 3.0])]) + @pytest.mark.parametrize('op', [operator.add, ops.radd, + operator.sub, ops.rsub], + ids=lambda x: x.__name__) + def test_td64arr_add_sub_float(self, box, op, other): + tdi = TimedeltaIndex(['-1 days', '-1 days']) + tdi = tm.box_expected(tdi, box) + + if box is pd.DataFrame and op in [operator.add, operator.sub]: + pytest.xfail(reason="Tries to align incorrectly, " + "raises ValueError") + + with pytest.raises(TypeError): + op(tdi, other) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Tries to cast df to " + "Period", + strict=True, + raises=IncompatibleFrequency)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('freq', [None, 'H']) + def test_td64arr_sub_period(self, box, freq): + # GH#13078 + # not supported, check TypeError + p = pd.Period('2011-01-01', freq='D') + idx = TimedeltaIndex(['1 hours', '2 hours'], freq=freq) + idx = tm.box_expected(idx, box) + + with pytest.raises(TypeError): + idx - p + + with pytest.raises(TypeError): + p - idx + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="broadcasts along " + "wrong axis", + raises=ValueError, + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('pi_freq', ['D', 'W', 'Q', 'H']) + @pytest.mark.parametrize('tdi_freq', [None, 'H']) + def test_td64arr_sub_pi(self, box, tdi_freq, pi_freq): + # GH#20049 subtracting PeriodIndex should raise TypeError + tdi = TimedeltaIndex(['1 hours', '2 hours'], freq=tdi_freq) + dti = Timestamp('2018-03-07 17:16:40') + tdi + pi = dti.to_period(pi_freq) + + # TODO: parametrize over box for pi? + tdi = tm.box_expected(tdi, box) + with pytest.raises(TypeError): + tdi - pi + + # ------------------------------------------------------------- + # Binary operations td64 arraylike and datetime-like + + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame], + ids=lambda x: x.__name__) + def test_td64arr_sub_timestamp_raises(self, box): + idx = TimedeltaIndex(['1 day', '2 day']) + idx = tm.box_expected(idx, box) + + msg = "cannot subtract a datelike from|Could not operate" + with tm.assert_raises_regex(TypeError, msg): + idx - Timestamp('2011-01-01') + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Returns object dtype", + strict=True)) + ], ids=lambda x: x.__name__) + def test_td64arr_add_timestamp(self, box): + idx = TimedeltaIndex(['1 day', '2 day']) + expected = DatetimeIndex(['2011-01-02', '2011-01-03']) + + idx = tm.box_expected(idx, box) + expected = tm.box_expected(expected, box) + + result = idx + Timestamp('2011-01-01') + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Returns object dtype", + strict=True)) + ], ids=lambda x: x.__name__) + def test_td64_radd_timestamp(self, box): + idx = TimedeltaIndex(['1 day', '2 day']) + expected = DatetimeIndex(['2011-01-02', '2011-01-03']) + + idx = tm.box_expected(idx, box) + expected = tm.box_expected(expected, box) + + # TODO: parametrize over scalar datetime types? + result = Timestamp('2011-01-01') + idx + tm.assert_equal(result, expected) + + # ------------------------------------------------------------------ + # Operations with int-like others + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Attempts to broadcast " + "incorrectly", + strict=True, raises=ValueError)) + ], ids=lambda x: x.__name__) + def test_td64arr_add_int_series_invalid(self, box, tdser): + tdser = tm.box_expected(tdser, box) + err = TypeError if box is not pd.Index else NullFrequencyError + with pytest.raises(err): + tdser + Series([2, 3, 4]) + + @pytest.mark.parametrize('box', [ + pd.Index, + pytest.param(Series, + marks=pytest.mark.xfail(reason="GH#19123 integer " + "interpreted as " + "nanoseconds", + strict=True)), + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Attempts to broadcast " + "incorrectly", + strict=True, raises=ValueError)) + ], ids=lambda x: x.__name__) + def test_td64arr_radd_int_series_invalid(self, box, tdser): + tdser = tm.box_expected(tdser, box) + err = TypeError if box is not pd.Index else NullFrequencyError + with pytest.raises(err): + Series([2, 3, 4]) + tdser + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Attempts to broadcast " + "incorrectly", + strict=True, raises=ValueError)) + ], ids=lambda x: x.__name__) + def test_td64arr_sub_int_series_invalid(self, box, tdser): + tdser = tm.box_expected(tdser, box) + err = TypeError if box is not pd.Index else NullFrequencyError + with pytest.raises(err): + tdser - Series([2, 3, 4]) + + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame], + ids=lambda x: x.__name__) + @pytest.mark.xfail(reason='GH#19123 integer interpreted as nanoseconds', + strict=True) + def test_td64arr_rsub_int_series_invalid(self, box, tdser): + tdser = tm.box_expected(tdser, box) + with pytest.raises(TypeError): + Series([2, 3, 4]) - tdser + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Tries to broadcast " + "incorrectly", + strict=True, raises=ValueError)) + ], ids=lambda x: x.__name__) + def test_td64arr_add_intlike(self, box): + # GH#19123 + tdi = TimedeltaIndex(['59 days', '59 days', 'NaT']) + ser = tm.box_expected(tdi, box) + err = TypeError if box is not pd.Index else NullFrequencyError + + other = Series([20, 30, 40], dtype='uint8') + + # TODO: separate/parametrize + with pytest.raises(err): + ser + 1 + with pytest.raises(err): + ser - 1 + + with pytest.raises(err): + ser + other + with pytest.raises(err): + ser - other + + with pytest.raises(err): + ser + np.array(other) + with pytest.raises(err): + ser - np.array(other) + + with pytest.raises(err): + ser + pd.Index(other) + with pytest.raises(err): + ser - pd.Index(other) + + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame], + ids=lambda x: x.__name__) + @pytest.mark.parametrize('scalar', [1, 1.5, np.array(2)]) + def test_td64arr_add_sub_numeric_scalar_invalid(self, box, scalar, tdser): + + if box is pd.DataFrame and isinstance(scalar, np.ndarray): + # raises ValueError + pytest.xfail(reason="DataFrame to broadcast incorrectly") + + tdser = tm.box_expected(tdser, box) + err = TypeError + if box is pd.Index and not isinstance(scalar, float): + err = NullFrequencyError + + with pytest.raises(err): + tdser + scalar + with pytest.raises(err): + scalar + tdser + with pytest.raises(err): + tdser - scalar + with pytest.raises(err): + scalar - tdser + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Tries to broadcast " + "incorrectly", + strict=True, raises=ValueError)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', + 'uint64', 'uint32', 'uint16', 'uint8', + 'float64', 'float32', 'float16']) + @pytest.mark.parametrize('vec', [ + np.array([1, 2, 3]), + pd.Index([1, 2, 3]), + Series([1, 2, 3]) + # TODO: Add DataFrame in here? + ], ids=lambda x: type(x).__name__) + def test_td64arr_add_sub_numeric_arr_invalid(self, box, vec, dtype, tdser): + if type(vec) is Series and not dtype.startswith('float'): + pytest.xfail(reason='GH#19123 integer interpreted as nanos') + + tdser = tm.box_expected(tdser, box) + err = TypeError + if box is pd.Index and not dtype.startswith('float'): + err = NullFrequencyError + + vector = vec.astype(dtype) + # TODO: parametrize over these four ops? + with pytest.raises(err): + tdser + vector + with pytest.raises(err): + vector + tdser + with pytest.raises(err): + tdser - vector + with pytest.raises(err): + vector - tdser + + # ------------------------------------------------------------------ + # Operations with datetime-like others + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Returns object dtype " + "instead of " + "datetime64[ns]", + strict=True)) + ], ids=lambda x: x.__name__) + def test_td64arr_add_sub_timestamp(self, box): + # GH#11925 + ts = Timestamp('2012-01-01') + # TODO: parametrize over types of datetime scalar? + + tdser = Series(pd.timedelta_range('1 day', periods=3)) + expected = Series(pd.date_range('2012-01-02', periods=3)) + + tdser = tm.box_expected(tdser, box) + expected = tm.box_expected(expected, box) + + tm.assert_equal(ts + tdser, expected) + tm.assert_equal(tdser + ts, expected) + + expected2 = Series(pd.date_range('2011-12-31', + periods=3, freq='-1D')) + expected2 = tm.box_expected(expected2, box) + + tm.assert_equal(ts - tdser, expected2) + tm.assert_equal(ts + (-tdser), expected2) + + with pytest.raises(TypeError): + tdser - ts + + # ------------------------------------------------------------------ + # Operations with timedelta-like others (including DateOffsets) + + # TODO: parametrize over [add, sub, radd, rsub]? + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Tries to broadcast " + "incorrectly leading " + "to alignment error", + strict=True, raises=ValueError)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('names', [(None, None, None), + ('Egon', 'Venkman', None), + ('NCC1701D', 'NCC1701D', 'NCC1701D')]) + def test_td64arr_add_sub_tdi(self, box, names): + # GH#17250 make sure result dtype is correct + # GH#19043 make sure names are propagated correctly + tdi = TimedeltaIndex(['0 days', '1 day'], name=names[0]) + ser = Series([Timedelta(hours=3), Timedelta(hours=4)], name=names[1]) + expected = Series([Timedelta(hours=3), Timedelta(days=1, hours=4)], + name=names[2]) + + ser = tm.box_expected(ser, box) + expected = tm.box_expected(expected, box) + + result = tdi + ser + tm.assert_equal(result, expected) + if box is not pd.DataFrame: + assert result.dtype == 'timedelta64[ns]' + else: + assert result.dtypes[0] == 'timedelta64[ns]' + + result = ser + tdi + tm.assert_equal(result, expected) + if box is not pd.DataFrame: + assert result.dtype == 'timedelta64[ns]' + else: + assert result.dtypes[0] == 'timedelta64[ns]' + + expected = Series([Timedelta(hours=-3), Timedelta(days=1, hours=-4)], + name=names[2]) + expected = tm.box_expected(expected, box) + + result = tdi - ser + tm.assert_equal(result, expected) + if box is not pd.DataFrame: + assert result.dtype == 'timedelta64[ns]' + else: + assert result.dtypes[0] == 'timedelta64[ns]' + + result = ser - tdi + tm.assert_equal(result, -expected) + if box is not pd.DataFrame: + assert result.dtype == 'timedelta64[ns]' + else: + assert result.dtypes[0] == 'timedelta64[ns]' + + @pytest.mark.parametrize('box', [pd.Index, Series, pd.DataFrame], + ids=lambda x: x.__name__) + def test_td64arr_sub_NaT(self, box): + # GH#18808 + ser = Series([NaT, Timedelta('1s')]) + expected = Series([NaT, NaT], dtype='timedelta64[ns]') + + ser = tm.box_expected(ser, box) + expected = tm.box_expected(expected, box) + + res = ser - NaT + tm.assert_equal(res, expected) + + +class TestTimedeltaArraylikeMulDivOps(object): + # Tests for timedelta64[ns] + # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__ + + # ------------------------------------------------------------------ + # __floordiv__, __rfloordiv__ + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Incorrectly returns " + "m8[ns] instead of f8", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('scalar_td', [ + timedelta(minutes=5, seconds=4), + Timedelta('5m4s'), + Timedelta('5m4s').to_timedelta64()]) + def test_td64arr_floordiv_tdscalar(self, box, scalar_td): + # GH#18831 + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) + td1.iloc[2] = np.nan + + expected = Series([0, 0, np.nan]) + + td1 = tm.box_expected(td1, box) + expected = tm.box_expected(expected, box) + + result = td1 // scalar_td + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Incorrectly casts to f8", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('scalar_td', [ + timedelta(minutes=5, seconds=4), + Timedelta('5m4s'), + Timedelta('5m4s').to_timedelta64()]) + def test_td64arr_rfloordiv_tdscalar(self, box, scalar_td): + # GH#18831 + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) + td1.iloc[2] = np.nan + + expected = Series([1, 1, np.nan]) + + td1 = tm.box_expected(td1, box) + expected = tm.box_expected(expected, box) + + result = scalar_td // td1 + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Returns m8[ns] dtype " + "instead of f8", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('scalar_td', [ + timedelta(minutes=5, seconds=4), + Timedelta('5m4s'), + Timedelta('5m4s').to_timedelta64()]) + def test_td64arr_rfloordiv_tdscalar_explicit(self, box, scalar_td): + # GH#18831 + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) + td1.iloc[2] = np.nan + + expected = Series([1, 1, np.nan]) + + td1 = tm.box_expected(td1, box) + expected = tm.box_expected(expected, box) + + # We can test __rfloordiv__ using this syntax, + # see `test_timedelta_rfloordiv` + result = td1.__rfloordiv__(scalar_td) + tm.assert_equal(result, expected) + + # ------------------------------------------------------------------ + # Operations with timedelta-like others + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="__mul__ op treats " + "timedelta other as i8; " + "rmul OK", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('scalar_td', [ + timedelta(minutes=5, seconds=4), + Timedelta('5m4s'), + Timedelta('5m4s').to_timedelta64()]) + def test_td64arr_mul_tdscalar_invalid(self, box, scalar_td): + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) + td1.iloc[2] = np.nan + + td1 = tm.box_expected(td1, box) + + # check that we are getting a TypeError + # with 'operate' (from core/ops.py) for the ops that are not + # defined + pattern = 'operate|unsupported|cannot|not supported' + with tm.assert_raises_regex(TypeError, pattern): + td1 * scalar_td + with tm.assert_raises_regex(TypeError, pattern): + scalar_td * td1 + + # ------------------------------------------------------------------ + # Operations with numeric others + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Returns object-dtype", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('one', [1, np.array(1), 1.0, np.array(1.0)]) + def test_td64arr_mul_numeric_scalar(self, box, one, tdser): + # GH#4521 + # divide/multiply by integers + expected = Series(['-59 Days', '-59 Days', 'NaT'], + dtype='timedelta64[ns]') + + tdser = tm.box_expected(tdser, box) + expected = tm.box_expected(expected, box) + + result = tdser * (-one) + tm.assert_equal(result, expected) + result = (-one) * tdser + tm.assert_equal(result, expected) + + expected = Series(['118 Days', '118 Days', 'NaT'], + dtype='timedelta64[ns]') + expected = tm.box_expected(expected, box) + + result = tdser * (2 * one) + tm.assert_equal(result, expected) + result = (2 * one) * tdser + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="Returns object-dtype", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('two', [2, 2.0, np.array(2), np.array(2.0)]) + def test_td64arr_div_numeric_scalar(self, box, two, tdser): + # GH#4521 + # divide/multiply by integers + expected = Series(['29.5D', '29.5D', 'NaT'], dtype='timedelta64[ns]') + + tdser = tm.box_expected(tdser, box) + expected = tm.box_expected(expected, box) + + result = tdser / two + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="broadcasts along " + "wrong axis", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', + 'uint64', 'uint32', 'uint16', 'uint8', + 'float64', 'float32', 'float16']) + @pytest.mark.parametrize('vector', [np.array([20, 30, 40]), + pd.Index([20, 30, 40]), + Series([20, 30, 40])]) + def test_td64arr_mul_numeric_array(self, box, vector, dtype, tdser): + # GH#4521 + # divide/multiply by integers + vector = vector.astype(dtype) + + expected = Series(['1180 Days', '1770 Days', 'NaT'], + dtype='timedelta64[ns]') + + tdser = tm.box_expected(tdser, box) + # TODO: Make this up-casting more systematic? + box = Series if (box is pd.Index and type(vector) is Series) else box + expected = tm.box_expected(expected, box) + + result = tdser * vector + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="broadcasts along " + "wrong axis", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', + 'uint64', 'uint32', 'uint16', 'uint8', + 'float64', 'float32', 'float16']) + @pytest.mark.parametrize('vector', [np.array([20, 30, 40]), + pd.Index([20, 30, 40]), + Series([20, 30, 40])], + ids=lambda x: type(x).__name__) + def test_td64arr_rmul_numeric_array(self, box, vector, dtype, tdser): + # GH#4521 + # divide/multiply by integers + vector = vector.astype(dtype) + + expected = Series(['1180 Days', '1770 Days', 'NaT'], + dtype='timedelta64[ns]') + + tdser = tm.box_expected(tdser, box) + box = Series if (box is pd.Index and type(vector) is Series) else box + expected = tm.box_expected(expected, box) + + result = vector * tdser + tm.assert_equal(result, expected) + + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="broadcasts along " + "wrong axis", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('dtype', ['int64', 'int32', 'int16', + 'uint64', 'uint32', 'uint16', 'uint8', + 'float64', 'float32', 'float16']) + @pytest.mark.parametrize('vector', [np.array([20, 30, 40]), + pd.Index([20, 30, 40]), + Series([20, 30, 40])]) + def test_td64arr_div_numeric_array(self, box, vector, dtype, tdser): + # GH#4521 + # divide/multiply by integers + vector = vector.astype(dtype) + expected = Series(['2.95D', '1D 23H 12m', 'NaT'], + dtype='timedelta64[ns]') + + tdser = tm.box_expected(tdser, box) + box = Series if (box is pd.Index and type(vector) is Series) else box + expected = tm.box_expected(expected, box) + + result = tdser / vector + tm.assert_equal(result, expected) + + with pytest.raises(TypeError): + vector / tdser + + # TODO: Should we be parametrizing over types for `ser` too? + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pytest.param(pd.DataFrame, + marks=pytest.mark.xfail(reason="broadcasts along " + "wrong axis", + strict=True)) + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('names', [(None, None, None), + ('Egon', 'Venkman', None), + ('NCC1701D', 'NCC1701D', 'NCC1701D')]) + def test_td64arr_mul_int_series(self, box, names): + # GH#19042 test for correct name attachment + tdi = TimedeltaIndex(['0days', '1day', '2days', '3days', '4days'], + name=names[0]) + ser = Series([0, 1, 2, 3, 4], dtype=np.int64, name=names[1]) + + expected = Series(['0days', '1day', '4days', '9days', '16days'], + dtype='timedelta64[ns]', + name=names[2]) + + tdi = tm.box_expected(tdi, box) + box = Series if (box is pd.Index and type(ser) is Series) else box + expected = tm.box_expected(expected, box) + + result = ser * tdi + tm.assert_equal(result, expected) + + # The direct operation tdi * ser still needs to be fixed. + result = ser.__rmul__(tdi) + tm.assert_equal(result, expected) + + # TODO: Should we be parametrizing over types for `ser` too? + @pytest.mark.parametrize('box', [ + pd.Index, + Series, + pd.DataFrame + ], ids=lambda x: x.__name__) + @pytest.mark.parametrize('names', [(None, None, None), + ('Egon', 'Venkman', None), + ('NCC1701D', 'NCC1701D', 'NCC1701D')]) + def test_float_series_rdiv_td64arr(self, box, names): + # GH#19042 test for correct name attachment + # TODO: the direct operation TimedeltaIndex / Series still + # needs to be fixed. + tdi = TimedeltaIndex(['0days', '1day', '2days', '3days', '4days'], + name=names[0]) + ser = Series([1.5, 3, 4.5, 6, 7.5], dtype=np.float64, name=names[1]) + + expected = Series([tdi[n] / ser[n] for n in range(len(ser))], + dtype='timedelta64[ns]', + name=names[2]) + + tdi = tm.box_expected(tdi, box) + box = Series if (box is pd.Index and type(ser) is Series) else box + expected = tm.box_expected(expected, box) + + result = ser.__rdiv__(tdi) + if box is pd.DataFrame: + # TODO: Should we skip this case sooner or test something else? + assert result is NotImplemented + else: + tm.assert_equal(result, expected) + class TestTimedeltaArraylikeInvalidArithmeticOps(object): @pytest.mark.parametrize('box', [ pd.Index, - pd.Series, + Series, pytest.param(pd.DataFrame, marks=pytest.mark.xfail(reason="raises ValueError " "instead of TypeError", @@ -102,8 +833,8 @@ class TestTimedeltaArraylikeInvalidArithmeticOps(object): timedelta(minutes=5, seconds=4), Timedelta('5m4s'), Timedelta('5m4s').to_timedelta64()]) - def test_td64series_pow_invalid(self, scalar_td, box): - td1 = pd.Series([timedelta(minutes=5, seconds=3)] * 3) + def test_td64arr_pow_invalid(self, scalar_td, box): + td1 = Series([timedelta(minutes=5, seconds=3)] * 3) td1.iloc[2] = np.nan td1 = tm.box_expected(td1, box)
There are a bunch still left in the TDI tests, but the diff is already pretty big as it is. A _ton_ of `DataFrame` tests are xfailed here. Most of these will be fixed by the follow-up to (#22068 + #22074). xfails are made strict so that we get alerted when they are fixed. Several existing xfails are removed since they have been XPASSing for a while. @jreback I know you're going to want to make fixtures for a bunch of things. I agree, but think that will be 19.6x easier after fixing some of the xfails. Also this is step 2 of a many-step process and in general I'd prefer to do cleanup after getting more stuff in place.
https://api.github.com/repos/pandas-dev/pandas/pulls/22118
2018-07-29T20:55:14Z
2018-07-31T12:23:42Z
2018-07-31T12:23:42Z
2018-07-31T15:59:10Z
CLN: Remove special handling of nans in the float64-case of isin
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 34a8d552304d1..a26c5d89bc483 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -38,6 +38,27 @@ def time_isin(self, dtypes): self.s.isin(self.values) +class IsInFloat64(object): + + def setup(self): + self.small = Series([1, 2], dtype=np.float64) + self.many_different_values = np.arange(10**6, dtype=np.float64) + self.few_different_values = np.zeros(10**7, dtype=np.float64) + self.only_nans_values = np.full(10**7, np.nan, dtype=np.float64) + + def time_isin_many_different(self): + # runtime is dominated by creation of the lookup-table + self.small.isin(self.many_different_values) + + def time_isin_few_different(self): + # runtime is dominated by creation of the lookup-table + self.small.isin(self.few_different_values) + + def time_isin_nan_values(self): + # runtime is dominated by creation of the lookup-table + self.small.isin(self.few_different_values) + + class IsInForObjects(object): def setup(self): diff --git a/pandas/_libs/hashtable_func_helper.pxi.in b/pandas/_libs/hashtable_func_helper.pxi.in index 521e564447c59..e7f3701ee83c3 100644 --- a/pandas/_libs/hashtable_func_helper.pxi.in +++ b/pandas/_libs/hashtable_func_helper.pxi.in @@ -210,10 +210,10 @@ def duplicated_{{dtype}}({{scalar}}[:] values, object keep='first'): @cython.boundscheck(False) {{if dtype == 'object'}} -def ismember_{{dtype}}(ndarray[{{scalar}}] arr, ndarray[{{scalar}}] values, bint hasnans=0): +def ismember_{{dtype}}(ndarray[{{scalar}}] arr, ndarray[{{scalar}}] values): {{else}} -def ismember_{{dtype}}({{scalar}}[:] arr, {{scalar}}[:] values, bint hasnans=0): +def ismember_{{dtype}}({{scalar}}[:] arr, {{scalar}}[:] values): {{endif}} """ @@ -224,7 +224,6 @@ def ismember_{{dtype}}({{scalar}}[:] arr, {{scalar}}[:] values, bint hasnans=0): ---------- arr : {{dtype}} ndarray values : {{dtype}} ndarray - hasnans : bint, optional Returns ------- @@ -259,19 +258,13 @@ def ismember_{{dtype}}({{scalar}}[:] arr, {{scalar}}[:] values, bint hasnans=0): for i in range(n): val = arr[i] k = kh_get_{{ttype}}(table, <PyObject*> val) - if k != table.n_buckets: - result[i] = 1 - else: - result[i] = hasnans and val != val + result[i] = (k != table.n_buckets) {{else}} with nogil: for i in range(n): val = arr[i] k = kh_get_{{ttype}}(table, val) - if k != table.n_buckets: - result[i] = 1 - else: - result[i] = hasnans and val != val + result[i] = (k != table.n_buckets) {{endif}} kh_destroy_{{ttype}}(table) diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 4bf62b021cddc..2773e7b230084 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -437,8 +437,7 @@ def isin(comps, values): try: values = values.astype('float64', copy=False) comps = comps.astype('float64', copy=False) - checknull = isna(values).any() - f = lambda x, y: htable.ismember_float64(x, y, checknull) + f = lambda x, y: htable.ismember_float64(x, y) except (TypeError, ValueError): values = values.astype(object) comps = comps.astype(object) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index f89c7545765c9..4f8f61a9884b9 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -632,6 +632,28 @@ def test_different_nan_objects(self): result = algos.isin(comps, vals) tm.assert_numpy_array_equal(expected, result) + def test_different_nans_as_float64(self): + # GH 21866 + # create different nans from bit-patterns, + # these nans will land in different buckets in the hash-table + # if no special care is taken + NAN1 = struct.unpack("d", struct.pack("=Q", 0x7ff8000000000000))[0] + NAN2 = struct.unpack("d", struct.pack("=Q", 0x7ff8000000000001))[0] + assert NAN1 != NAN1 + assert NAN2 != NAN2 + + # check that NAN1 and NAN2 are equivalent: + arr = np.array([NAN1, NAN2], dtype=np.float64) + lookup1 = np.array([NAN1], dtype=np.float64) + result = algos.isin(arr, lookup1) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) + + lookup2 = np.array([NAN2], dtype=np.float64) + result = algos.isin(arr, lookup2) + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected) + class TestValueCounts(object):
It is no longer needed because the hash-table handles the nans correctly out of the box (see #21866) Not having to scan the values via isna(...).any() will improve the performance. - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` There are no changes visible for the user (others than slightly better performance).
https://api.github.com/repos/pandas-dev/pandas/pulls/22117
2018-07-29T20:51:53Z
2018-08-10T10:18:59Z
2018-08-10T10:18:59Z
2018-08-11T19:45:22Z
CLN: Unused varables pt2
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 928483005786a..60464bcfda1e7 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -814,7 +814,6 @@ def _format_data(self): summary = '[{head} ... {tail}]'.format( head=', '.join(head), tail=', '.join(tail)) else: - head = [] tail = [formatter(x) for x in self] summary = '[{tail}]'.format(tail=', '.join(tail)) diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 57b1d81d94754..cf771a127a696 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -305,7 +305,6 @@ def _hash_categories(categories, ordered=True): # everything to a str first, which means we treat # {'1', '2'} the same as {'1', 2} # find a better solution - cat_array = np.array([hash(x) for x in categories]) hashed = hash((tuple(categories), ordered)) return hashed cat_array = hash_array(np.asarray(categories), categorize=False) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 4c87f6122b956..5b2590cfcf010 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -134,7 +134,6 @@ def _cython_agg_blocks(self, how, alt=None, numeric_only=True, obj = self.obj[data.items[locs]] s = groupby(obj, self.grouper) result = s.aggregate(lambda x: alt(x, axis=self.axis)) - newb = result._data.blocks[0] finally: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 8ad058c001bba..2a191ef76473b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1647,11 +1647,11 @@ def is_int(v): # if we are mixed and have integers try: if is_positional and self.is_mixed(): - # TODO: i, j are not used anywhere + # Validate start & stop if start is not None: - i = self.get_loc(start) # noqa + self.get_loc(start) if stop is not None: - j = self.get_loc(stop) # noqa + self.get_loc(stop) is_positional = False except KeyError: if self.inferred_type == 'mixed-integer-float': diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 13c019dea469a..80b3d579d5447 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -788,11 +788,6 @@ def _align_frame(self, indexer, df): if isinstance(indexer, tuple): - aligners = [not com.is_null_slice(idx) for idx in indexer] - sum_aligners = sum(aligners) - # TODO: single_aligner is not used - single_aligner = sum_aligners == 1 # noqa - idx, cols = None, None sindexers = [] for i, ix in enumerate(indexer): @@ -865,9 +860,6 @@ def _align_frame(self, indexer, df): raise ValueError('Incompatible indexer with DataFrame') def _align_panel(self, indexer, df): - # TODO: is_frame, is_panel are unused - is_frame = self.obj.ndim == 2 # noqa - is_panel = self.obj.ndim >= 3 # noqa raise NotImplementedError("cannot set using an indexer with a Panel " "yet!") diff --git a/pandas/core/ops.py b/pandas/core/ops.py index c65d2dcdc478c..6d407c41daea6 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -1789,7 +1789,7 @@ def na_op(x, y): def f(self, other, axis=None): # Validate the axis parameter if axis is not None: - axis = self._get_axis_number(axis) + self._get_axis_number(axis) if isinstance(other, self._constructor): return self._compare_constructor(other, na_op, try_cast=False) diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 38b84ab685c3b..fd27e3ba650ea 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -296,7 +296,7 @@ def _getitem_multilevel(self, key): if isinstance(loc, (slice, np.ndarray)): new_index = info[loc] result_index = maybe_droplevels(new_index, key) - slices = [loc] + [slice(None) for x in range(self._AXIS_LEN - 1)] + slices = [loc] + [slice(None)] * (self._AXIS_LEN - 1) new_values = self.values[slices] d = self._construct_axes_dict(self._AXIS_ORDERS[1:]) diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index 1a92a27bfb390..8ac5d81f23bb2 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -624,8 +624,9 @@ def cumsum(self, axis=0, *args, **kwargs): cumsum : SparseSeries """ nv.validate_cumsum(args, kwargs) + # Validate axis if axis is not None: - axis = self._get_axis_number(axis) + self._get_axis_number(axis) new_array = self.values.cumsum() @@ -654,7 +655,8 @@ def dropna(self, axis=0, inplace=False, **kwargs): Analogous to Series.dropna. If fill_value=NaN, returns a dense Series """ # TODO: make more efficient - axis = self._get_axis_number(axis or 0) + # Validate axis + self._get_axis_number(axis or 0) dense_valid = self.to_dense().dropna() if inplace: raise NotImplementedError("Cannot perform inplace dropna" diff --git a/pandas/io/excel.py b/pandas/io/excel.py index 39131d390c69f..e2db6643c5ef0 100644 --- a/pandas/io/excel.py +++ b/pandas/io/excel.py @@ -647,7 +647,7 @@ def _parse_cell(cell_contents, cell_typ): if header is not None: if is_list_like(header): header_names = [] - control_row = [True for x in data[0]] + control_row = [True] * len(data[0]) for row in header: if is_integer(skiprows): row += skiprows diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index c6ca59aa08bf9..1ff0613876838 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1567,7 +1567,7 @@ def get_level_lengths(levels, sentinel=''): if len(levels) == 0: return [] - control = [True for x in levels[0]] + control = [True] * len(levels[0]) result = [] for level in levels: diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py index 3ea5cb95b9c5a..a6b03c9c6dd23 100644 --- a/pandas/io/formats/html.py +++ b/pandas/io/formats/html.py @@ -369,7 +369,7 @@ def _write_regular_rows(self, fmt_values, indent): for i in range(nrows): if truncate_v and i == (self.fmt.tr_row_num): - str_sep_row = ['...' for ele in row] + str_sep_row = ['...'] * len(row) self.write_tr(str_sep_row, indent, self.indent_delta, tags=None, nindex_levels=1)
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` xref #21986 Remove more unused variables including ones that were marked in TODOs as unused.
https://api.github.com/repos/pandas-dev/pandas/pulls/22115
2018-07-29T19:24:41Z
2018-07-30T10:11:49Z
2018-07-30T10:11:49Z
2018-07-30T15:21:53Z
remove cnp usage from sas.pyx
diff --git a/pandas/io/sas/sas.pyx b/pandas/io/sas/sas.pyx index 3d94dc127a1d2..221c07a0631d2 100644 --- a/pandas/io/sas/sas.pyx +++ b/pandas/io/sas/sas.pyx @@ -2,20 +2,22 @@ # cython: boundscheck=False, initializedcheck=False import numpy as np -cimport numpy as cnp -from numpy cimport uint8_t, uint16_t, int8_t, int64_t, ndarray import sas_constants as const +ctypedef signed long long int64_t +ctypedef unsigned char uint8_t +ctypedef unsigned short uint16_t + # rle_decompress decompresses data using a Run Length Encoding # algorithm. It is partially documented here: # # https://cran.r-project.org/web/packages/sas7bdat/vignettes/sas7bdat.pdf -cdef ndarray[uint8_t, ndim=1] rle_decompress( - int result_length, ndarray[uint8_t, ndim=1] inbuff): +cdef const uint8_t[:] rle_decompress(int result_length, + const uint8_t[:] inbuff): cdef: uint8_t control_byte, x - uint8_t [:] result = np.zeros(result_length, np.uint8) + uint8_t[:] result = np.zeros(result_length, np.uint8) int rpos = 0, ipos = 0, length = len(inbuff) int i, nbytes, end_of_first_byte @@ -115,14 +117,14 @@ cdef ndarray[uint8_t, ndim=1] rle_decompress( # rdc_decompress decompresses data using the Ross Data Compression algorithm: # # http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/1992/9210/ross/ross.htm -cdef ndarray[uint8_t, ndim=1] rdc_decompress( - int result_length, ndarray[uint8_t, ndim=1] inbuff): +cdef const uint8_t[:] rdc_decompress(int result_length, + const uint8_t[:] inbuff): cdef: uint8_t cmd uint16_t ctrl_bits, ctrl_mask = 0, ofs, cnt int ipos = 0, rpos = 0, k - uint8_t [:] outbuff = np.zeros(result_length, dtype=np.uint8) + uint8_t[:] outbuff = np.zeros(result_length, dtype=np.uint8) ii = -1 @@ -230,8 +232,8 @@ cdef class Parser(object): int subheader_pointer_length int current_page_type bint is_little_endian - ndarray[uint8_t, ndim=1] (*decompress)( - int result_length, ndarray[uint8_t, ndim=1] inbuff) + const uint8_t[:] (*decompress)(int result_length, + const uint8_t[:] inbuff) object parser def __init__(self, object parser): @@ -395,7 +397,7 @@ cdef class Parser(object): Py_ssize_t j int s, k, m, jb, js, current_row int64_t lngt, start, ct - ndarray[uint8_t, ndim=1] source + const uint8_t[:] source int64_t[:] column_types int64_t[:] lengths int64_t[:] offsets @@ -434,8 +436,8 @@ cdef class Parser(object): jb += 1 elif column_types[j] == column_type_string: # string - string_chunk[js, current_row] = source[start:( - start + lngt)].tostring().rstrip() + string_chunk[js, current_row] = np.array(source[start:( + start + lngt)]).tostring().rstrip() js += 1 self.current_row_on_page_index += 1
Building this particular file will no longer emit the numpy 1.7 deprecation warning.
https://api.github.com/repos/pandas-dev/pandas/pulls/22111
2018-07-29T01:31:45Z
2018-07-29T15:20:20Z
2018-07-29T15:20:20Z
2018-08-08T15:53:35Z
BUG: _cython_table bug fix
diff --git a/pandas/conftest.py b/pandas/conftest.py index e878b32fcad7b..c714ce2228d09 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -126,7 +126,7 @@ def all_arithmetic_operators(request): # use sorted as dicts in py<3.6 have random order, which xdist doesn't like _cython_table = sorted(((key, value) for key, value in pd.core.base.SelectionMixin._cython_table.items()), - key=lambda x: x[0].__class__.__name__) + key=lambda x: x[0].__name__) @pytest.fixture(params=_cython_table)
#21224 introduced a bug, where the ``conftest._cython_table`` isn't sorted by the function's name, but by the functions class name (i.e. "function"). This can make the sorting indeterministic and make the build fail on Python 2.7 and 3.5 at times. This PR makes the sort order follow the functions names again and therefore be deterministic.
https://api.github.com/repos/pandas-dev/pandas/pulls/22110
2018-07-29T00:59:02Z
2018-07-29T10:08:00Z
2018-07-29T10:08:00Z
2018-07-29T10:30:05Z
ENH: add np.nan* funcs to cython_table
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 9a781eda0e397..38b789f697b30 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -1080,6 +1080,7 @@ Numeric - Bug in :meth:`DataFrame.astype` to extension dtype may raise ``AttributeError`` (:issue:`22578`) - Bug in :class:`DataFrame` with ``timedelta64[ns]`` dtype arithmetic operations with ``ndarray`` with integer dtype incorrectly treating the narray as ``timedelta64[ns]`` dtype (:issue:`23114`) - Bug in :meth:`Series.rpow` with object dtype ``NaN`` for ``1 ** NA`` instead of ``1`` (:issue:`22922`). +- :meth:`Series.agg` can now handle numpy NaN-aware methods like :func:`numpy.nansum` (:issue:`19629`) Strings ^^^^^^^ diff --git a/pandas/core/base.py b/pandas/core/base.py index 88a36b0ecc7c7..de368f52b6f00 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -178,11 +178,13 @@ class SelectionMixin(object): _selection = None _internal_names = ['_cache', '__setstate__'] _internal_names_set = set(_internal_names) + _builtin_table = OrderedDict(( (builtins.sum, np.sum), (builtins.max, np.max), (builtins.min, np.min), )) + _cython_table = OrderedDict(( (builtins.sum, 'sum'), (builtins.max, 'max'), @@ -190,15 +192,25 @@ class SelectionMixin(object): (np.all, 'all'), (np.any, 'any'), (np.sum, 'sum'), + (np.nansum, 'sum'), (np.mean, 'mean'), + (np.nanmean, 'mean'), (np.prod, 'prod'), + (np.nanprod, 'prod'), (np.std, 'std'), + (np.nanstd, 'std'), (np.var, 'var'), + (np.nanvar, 'var'), (np.median, 'median'), + (np.nanmedian, 'median'), (np.max, 'max'), + (np.nanmax, 'max'), (np.min, 'min'), + (np.nanmin, 'min'), (np.cumprod, 'cumprod'), + (np.nancumprod, 'cumprod'), (np.cumsum, 'cumsum'), + (np.nancumsum, 'cumsum'), )) @property diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index 61db4cee1ab02..c35405ad739c9 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -487,17 +487,6 @@ def test_agg_structs_series(structure, expected): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize('observed', [ - True, - pytest.param(False, - marks=pytest.mark.xfail(reason="GH#18869: agg func not " - "called on empty groups.", - strict=True)), - pytest.param(None, - marks=pytest.mark.xfail(reason="GH#18869: agg func not " - "called on empty groups.", - strict=True)) -]) def test_agg_category_nansum(observed): categories = ['a', 'b', 'c'] df = pd.DataFrame({"A": pd.Categorical(['a', 'a', 'b'],
- [x] closes #19629 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This PR ensures that ``Series.agg`` can correctly take np.nan* funcs as inputs, e.g.: ```python >>> pd.Series([1,2,3,4]).agg(np.nansum) 10 ``` Previously that operation returned a Series. See #19629 for details. Tests are added through the use of ``_get_cython_table_params`` in the parametrisation of ``test_agg_cython_table`` test function in ``series/test_apply``/``frame/test_apply``.
https://api.github.com/repos/pandas-dev/pandas/pulls/22109
2018-07-28T23:00:48Z
2018-10-28T03:26:45Z
2018-10-28T03:26:45Z
2019-01-17T19:03:12Z
BUG: DataFrame.replace with out of bound datetime causing RecursionError
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 42e286f487a7d..95767b4e03822 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -558,7 +558,7 @@ Reshaping - Bug in :meth:`Series.combine_first` with ``datetime64[ns, tz]`` dtype which would return tz-naive result (:issue:`21469`) - Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``datetime64[ns, tz]`` dtype (:issue:`21546`) - Bug in :meth:`Series.mask` and :meth:`DataFrame.mask` with ``list`` conditionals (:issue:`21891`) -- +- Bug in :meth:`DataFrame.replace` raises RecursionError when converting OutOfBounds ``datetime64[ns, tz]`` (:issue:`20380`) - Build Changes diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index ead7b39309f5e..72b43f5d51901 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -6,7 +6,7 @@ import warnings from pandas._libs import tslib, lib, tslibs -from pandas._libs.tslibs import iNaT +from pandas._libs.tslibs import iNaT, OutOfBoundsDatetime from pandas.compat import string_types, text_type, PY3 from .common import (ensure_object, is_bool, is_integer, is_float, is_complex, is_datetimetz, is_categorical_dtype, @@ -838,7 +838,13 @@ def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True, # Soft conversions if datetime: - values = lib.maybe_convert_objects(values, convert_datetime=datetime) + # GH 20380, when datetime is beyond year 2262, hence outside + # bound of nanosecond-resolution 64-bit integers. + try: + values = lib.maybe_convert_objects(values, + convert_datetime=datetime) + except OutOfBoundsDatetime: + pass if timedelta and is_object_dtype(values.dtype): # Object check to ensure only run if previous did not convert diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ffa2267dd6877..d50b3e8a83928 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -802,12 +802,14 @@ def replace(self, to_replace, value, inplace=False, filter=None, copy=not inplace) for b in blocks] return blocks except (TypeError, ValueError): - # try again with a compatible block block = self.astype(object) - return block.replace( - to_replace=original_to_replace, value=value, inplace=inplace, - filter=filter, regex=regex, convert=convert) + return block.replace(to_replace=original_to_replace, + value=value, + inplace=inplace, + filter=filter, + regex=regex, + convert=convert) def _replace_single(self, *args, **kwargs): """ no-op on a non-ObjectBlock """ diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index dd83a94b7062a..e4ba07049c298 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -757,40 +757,37 @@ def test_replace_for_new_dtypes(self): result = tsframe.fillna(method='bfill') assert_frame_equal(result, tsframe.fillna(method='bfill')) - def test_replace_dtypes(self): - # int - df = DataFrame({'ints': [1, 2, 3]}) - result = df.replace(1, 0) - expected = DataFrame({'ints': [0, 2, 3]}) - assert_frame_equal(result, expected) - - df = DataFrame({'ints': [1, 2, 3]}, dtype=np.int32) - result = df.replace(1, 0) - expected = DataFrame({'ints': [0, 2, 3]}, dtype=np.int32) - assert_frame_equal(result, expected) - - df = DataFrame({'ints': [1, 2, 3]}, dtype=np.int16) - result = df.replace(1, 0) - expected = DataFrame({'ints': [0, 2, 3]}, dtype=np.int16) - assert_frame_equal(result, expected) - - # bools - df = DataFrame({'bools': [True, False, True]}) - result = df.replace(False, True) - assert result.values.all() - - # complex blocks - df = DataFrame({'complex': [1j, 2j, 3j]}) - result = df.replace(1j, 0j) - expected = DataFrame({'complex': [0j, 2j, 3j]}) - assert_frame_equal(result, expected) - - # datetime blocks - prev = datetime.today() - now = datetime.today() - df = DataFrame({'datetime64': Index([prev, now, prev])}) - result = df.replace(prev, now) - expected = DataFrame({'datetime64': Index([now] * 3)}) + @pytest.mark.parametrize('frame, to_replace, value, expected', [ + (DataFrame({'ints': [1, 2, 3]}), 1, 0, + DataFrame({'ints': [0, 2, 3]})), + (DataFrame({'ints': [1, 2, 3]}, dtype=np.int32), 1, 0, + DataFrame({'ints': [0, 2, 3]}, dtype=np.int32)), + (DataFrame({'ints': [1, 2, 3]}, dtype=np.int16), 1, 0, + DataFrame({'ints': [0, 2, 3]}, dtype=np.int16)), + (DataFrame({'bools': [True, False, True]}), False, True, + DataFrame({'bools': [True, True, True]})), + (DataFrame({'complex': [1j, 2j, 3j]}), 1j, 0, + DataFrame({'complex': [0j, 2j, 3j]})), + (DataFrame({'datetime64': Index([datetime(2018, 5, 28), + datetime(2018, 7, 28), + datetime(2018, 5, 28)])}), + datetime(2018, 5, 28), datetime(2018, 7, 28), + DataFrame({'datetime64': Index([datetime(2018, 7, 28)] * 3)})), + # GH 20380 + (DataFrame({'dt': [datetime(3017, 12, 20)], 'str': ['foo']}), + 'foo', 'bar', + DataFrame({'dt': [datetime(3017, 12, 20)], 'str': ['bar']})), + (DataFrame({'A': date_range('20130101', periods=3, tz='US/Eastern'), + 'B': [0, np.nan, 2]}), + Timestamp('20130102', tz='US/Eastern'), + Timestamp('20130104', tz='US/Eastern'), + DataFrame({'A': [Timestamp('20130101', tz='US/Eastern'), + Timestamp('20130104', tz='US/Eastern'), + Timestamp('20130103', tz='US/Eastern')], + 'B': [0, np.nan, 2]})) + ]) + def test_replace_dtypes(self, frame, to_replace, value, expected): + result = getattr(frame, 'replace')(to_replace, value) assert_frame_equal(result, expected) def test_replace_input_formats_listlike(self):
- [x] closes #20380 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry By default, keyword convert=True for replace method for Block and ObjectBlock. When trying to replace dataframe, blocks are operated on separately, during which conversion happens if convert=True. OutOfBoundsDatetime(inherited from ValueError) raised by lib.maybe_convert_objects caused Block.replace, ObjectBlock.replace to form infinite recursive loop. As mentioned in #20380, setting convert=False (private and not available to public) solves the issue at hand, but there appear to be other uses cases that expect it to be True by default. Right now, simply wrap a try...except block around the lib.maybe_convert_objects in cast module. Downside is it catches all ValueError in maybe_convert_objects silently.
https://api.github.com/repos/pandas-dev/pandas/pulls/22108
2018-07-28T22:47:59Z
2018-08-01T01:09:54Z
2018-08-01T01:09:54Z
2018-08-01T08:33:58Z
DOC: Clarify check_like behavior in assert_frame_equal
diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 9697c991122dd..8deb056d2bd15 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -1348,7 +1348,9 @@ def assert_frame_equal(left, right, check_dtype=True, check_categorical : bool, default True Whether to compare internal Categorical exactly. check_like : bool, default False - If true, ignore the order of rows & columns + If True, ignore the order of index & columns. + Note: index labels must match their respective rows + (same as in columns) - same labels must be with the same data obj : str, default 'DataFrame' Specify object name being compared, internally used to show appropriate assertion message
- [x] closes #22052
https://api.github.com/repos/pandas-dev/pandas/pulls/22106
2018-07-28T20:22:33Z
2018-07-31T15:44:07Z
2018-07-31T15:44:06Z
2018-07-31T18:24:17Z
CLN: Old helper functions
diff --git a/pandas/core/reshape/util.py b/pandas/core/reshape/util.py index e83bcf800e949..1c2033d90cd8a 100644 --- a/pandas/core/reshape/util.py +++ b/pandas/core/reshape/util.py @@ -3,16 +3,9 @@ from pandas.core.dtypes.common import is_list_like from pandas.compat import reduce -from pandas.core.index import Index from pandas.core import common as com -def match(needles, haystack): - haystack = Index(haystack) - needles = Index(needles) - return haystack.get_indexer(needles) - - def cartesian_product(X): """ Numpy version of itertools.product or pandas.compat.product. diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 83de83ab76a2c..be042c9bf8ab0 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -1,5 +1,5 @@ from functools import partial -from datetime import datetime, timedelta, time +from datetime import datetime, time from collections import MutableMapping import numpy as np @@ -850,24 +850,3 @@ def _convert_listlike(arg, format): return _convert_listlike(arg, format) return _convert_listlike(np.array([arg]), format)[0] - - -def format(dt): - """Returns date in YYYYMMDD format.""" - return dt.strftime('%Y%m%d') - - -OLE_TIME_ZERO = datetime(1899, 12, 30, 0, 0, 0) - - -def ole2datetime(oledt): - """function for converting excel date to normal date format""" - val = float(oledt) - - # Excel has a bug where it thinks the date 2/29/1900 exists - # we just reject any date before 3/1/1900. - if val < 61: - msg = "Value is outside of acceptable range: {value}".format(value=val) - raise ValueError(msg) - - return OLE_TIME_ZERO + timedelta(days=val) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 4b0edfce89174..77dd06cccc532 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -36,7 +36,6 @@ from pandas import date_range, to_datetime, to_timedelta, Timestamp import pandas.compat as compat from pandas.compat import range, lrange, string_types, PY36 -from pandas.core.tools.datetimes import format as date_format import pandas.io.sql as sql from pandas.io.sql import read_sql_table, read_sql_query @@ -2094,6 +2093,11 @@ def test_illegal_names(self): # -- Old tests from 0.13.1 (before refactor using sqlalchemy) +def date_format(dt): + """Returns date in YYYYMMDD format.""" + return dt.strftime('%Y%m%d') + + _formatters = { datetime: lambda dt: "'%s'" % date_format(dt), str: lambda x: "'%s'" % x, diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 35ee0d37e2b1a..57b9a281ac0eb 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -29,7 +29,6 @@ QuarterEnd, BusinessMonthEnd, FY5253, Nano, Easter, FY5253Quarter, LastWeekOfMonth, Tick) -from pandas.core.tools.datetimes import format, ole2datetime import pandas.tseries.offsets as offsets from pandas.io.pickle import read_pickle from pandas._libs.tslibs import timezones @@ -45,19 +44,6 @@ #### -def test_format(): - actual = format(datetime(2008, 1, 15)) - assert actual == '20080115' - - -def test_ole2datetime(): - actual = ole2datetime(60000) - assert actual == datetime(2064, 4, 8) - - with pytest.raises(ValueError): - ole2datetime(60) - - def test_to_m8(): valb = datetime(2007, 10, 1) valu = _to_m8(valb)
- [x] closes #21838 - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` It appears that these functions were helpers at one point in the past, but they don't appear anywhere in the codebase now (and are not publicly documented). I _think_ they are safe to blow away, although they exist the public namespace.
https://api.github.com/repos/pandas-dev/pandas/pulls/22104
2018-07-28T19:29:33Z
2018-07-29T15:25:14Z
2018-07-29T15:25:14Z
2018-07-29T18:15:16Z
TST: skip pytables test with not-updated pytables conda package
diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 865cab7a1596e..9b624ab78a406 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -14,7 +14,7 @@ from pandas import (Series, DataFrame, Panel, MultiIndex, Int64Index, RangeIndex, Categorical, bdate_range, date_range, timedelta_range, Index, DatetimeIndex, - isna, compat, concat, Timestamp) + isna, compat, concat, Timestamp, _np_version_under1p15) import pandas.util.testing as tm import pandas.util._test_decorators as td @@ -2191,6 +2191,10 @@ def test_unimplemented_dtypes_table_columns(self): # this fails because we have a date in the object block...... pytest.raises(TypeError, store.append, 'df_unimplemented', df) + @pytest.mark.skipif( + not _np_version_under1p15, + reason=("pytables conda build package needs build " + "with numpy 1.15: gh-22098")) def test_calendar_roundtrip_issue(self): # 8591
xref #22098
https://api.github.com/repos/pandas-dev/pandas/pulls/22099
2018-07-28T12:43:58Z
2018-07-28T13:16:08Z
2018-07-28T13:16:08Z
2018-07-28T13:16:08Z
Bug in date_range with semi-open interval and freq='B'
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 47d4d15420f1d..22fb8b2942bea 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -301,172 +301,6 @@ def test_construct_with_different_start_end_string_format(self): Timestamp('2013-01-01 02:00:00+09:00')]) tm.assert_index_equal(result, expected) - -class TestGenRangeGeneration(object): - - def test_generate(self): - rng1 = list(generate_range(START, END, offset=BDay())) - rng2 = list(generate_range(START, END, time_rule='B')) - assert rng1 == rng2 - - def test_generate_cday(self): - rng1 = list(generate_range(START, END, offset=CDay())) - rng2 = list(generate_range(START, END, time_rule='C')) - assert rng1 == rng2 - - def test_1(self): - rng = list(generate_range(start=datetime(2009, 3, 25), periods=2)) - 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))) - 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))) - expected = [] - assert rng == expected - - def test_precision_finer_than_offset(self): - # GH 9907 - result1 = DatetimeIndex(start='2015-04-15 00:00:03', - end='2016-04-22 00:00:00', freq='Q') - result2 = DatetimeIndex(start='2015-04-15 00:00:03', - end='2015-06-22 00:00:04', freq='W') - expected1_list = ['2015-06-30 00:00:03', '2015-09-30 00:00:03', - '2015-12-31 00:00:03', '2016-03-31 00:00:03'] - expected2_list = ['2015-04-19 00:00:03', '2015-04-26 00:00:03', - '2015-05-03 00:00:03', '2015-05-10 00:00:03', - '2015-05-17 00:00:03', '2015-05-24 00:00:03', - '2015-05-31 00:00:03', '2015-06-07 00:00:03', - '2015-06-14 00:00:03', '2015-06-21 00:00:03'] - expected1 = DatetimeIndex(expected1_list, dtype='datetime64[ns]', - freq='Q-DEC', tz=None) - expected2 = DatetimeIndex(expected2_list, dtype='datetime64[ns]', - freq='W-SUN', tz=None) - tm.assert_index_equal(result1, expected1) - tm.assert_index_equal(result2, expected2) - - dt1, dt2 = '2017-01-01', '2017-01-01' - tz1, tz2 = 'US/Eastern', 'Europe/London' - - @pytest.mark.parametrize("start,end", [ - (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2)), - (pd.Timestamp(dt1), pd.Timestamp(dt2, tz=tz2)), - (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2, tz=tz2)), - (pd.Timestamp(dt1, tz=tz2), pd.Timestamp(dt2, tz=tz1)) - ]) - def test_mismatching_tz_raises_err(self, start, end): - # issue 18488 - with pytest.raises(TypeError): - pd.date_range(start, end) - with pytest.raises(TypeError): - pd.DatetimeIndex(start, end, freq=BDay()) - - -class TestBusinessDateRange(object): - - def test_constructor(self): - bdate_range(START, END, freq=BDay()) - bdate_range(START, periods=20, freq=BDay()) - bdate_range(end=START, periods=20, freq=BDay()) - - msg = 'periods must be a number, got B' - with tm.assert_raises_regex(TypeError, msg): - date_range('2011-1-1', '2012-1-1', 'B') - - with tm.assert_raises_regex(TypeError, msg): - bdate_range('2011-1-1', '2012-1-1', 'B') - - msg = 'freq must be specified for bdate_range; use date_range instead' - with tm.assert_raises_regex(TypeError, msg): - bdate_range(START, END, periods=10, freq=None) - - def test_naive_aware_conflicts(self): - naive = bdate_range(START, END, freq=BDay(), tz=None) - aware = bdate_range(START, END, freq=BDay(), tz="Asia/Hong_Kong") - - msg = 'tz-naive.*tz-aware' - with tm.assert_raises_regex(TypeError, msg): - naive.join(aware) - - with tm.assert_raises_regex(TypeError, msg): - aware.join(naive) - - def test_cached_range(self): - DatetimeIndex._cached_range(START, END, freq=BDay()) - DatetimeIndex._cached_range(START, periods=20, freq=BDay()) - DatetimeIndex._cached_range(end=START, periods=20, freq=BDay()) - - with tm.assert_raises_regex(TypeError, "freq"): - DatetimeIndex._cached_range(START, END) - - with tm.assert_raises_regex(TypeError, "specify period"): - DatetimeIndex._cached_range(START, freq=BDay()) - - with tm.assert_raises_regex(TypeError, "specify period"): - DatetimeIndex._cached_range(end=END, freq=BDay()) - - with tm.assert_raises_regex(TypeError, "start or end"): - DatetimeIndex._cached_range(periods=20, freq=BDay()) - - def test_cached_range_bug(self): - rng = date_range('2010-09-01 05:00:00', periods=50, - freq=DateOffset(hours=6)) - assert len(rng) == 50 - assert rng[0] == datetime(2010, 9, 1, 5) - - def test_timezone_comparaison_bug(self): - # smoke test - start = Timestamp('20130220 10:00', tz='US/Eastern') - result = date_range(start, periods=2, tz='US/Eastern') - assert len(result) == 2 - - def test_timezone_comparaison_assert(self): - start = Timestamp('20130220 10:00', tz='US/Eastern') - msg = 'Inferred time zone not equal to passed time zone' - with tm.assert_raises_regex(AssertionError, msg): - date_range(start, periods=2, tz='Europe/Berlin') - - def test_misc(self): - end = datetime(2009, 5, 13) - dr = bdate_range(end=end, periods=20) - firstDate = end - 19 * BDay() - - assert len(dr) == 20 - assert dr[0] == firstDate - assert dr[-1] == end - - def test_date_parse_failure(self): - badly_formed_date = '2007/100/1' - - with pytest.raises(ValueError): - Timestamp(badly_formed_date) - - with pytest.raises(ValueError): - bdate_range(start=badly_formed_date, periods=10) - - with pytest.raises(ValueError): - bdate_range(end=badly_formed_date, periods=10) - - with pytest.raises(ValueError): - bdate_range(badly_formed_date, badly_formed_date) - - def test_daterange_bug_456(self): - # GH #456 - rng1 = bdate_range('12/5/2011', '12/5/2011') - rng2 = bdate_range('12/2/2011', '12/5/2011') - rng2.freq = BDay() - - result = rng1.union(rng2) - assert isinstance(result, DatetimeIndex) - def test_error_with_zero_monthends(self): msg = r'Offset <0 \* MonthEnds> did not increment date' with tm.assert_raises_regex(ValueError, msg): @@ -658,6 +492,184 @@ def test_freq_divides_end_in_nanos(self): tm.assert_index_equal(result_1, expected_1) tm.assert_index_equal(result_2, expected_2) + def test_cached_range_bug(self): + rng = date_range('2010-09-01 05:00:00', periods=50, + freq=DateOffset(hours=6)) + assert len(rng) == 50 + assert rng[0] == datetime(2010, 9, 1, 5) + + def test_timezone_comparaison_bug(self): + # smoke test + start = Timestamp('20130220 10:00', tz='US/Eastern') + result = date_range(start, periods=2, tz='US/Eastern') + assert len(result) == 2 + + def test_timezone_comparaison_assert(self): + start = Timestamp('20130220 10:00', tz='US/Eastern') + msg = 'Inferred time zone not equal to passed time zone' + with tm.assert_raises_regex(AssertionError, msg): + date_range(start, periods=2, tz='Europe/Berlin') + + +class TestGenRangeGeneration(object): + + def test_generate(self): + rng1 = list(generate_range(START, END, offset=BDay())) + rng2 = list(generate_range(START, END, time_rule='B')) + assert rng1 == rng2 + + def test_generate_cday(self): + rng1 = list(generate_range(START, END, offset=CDay())) + rng2 = list(generate_range(START, END, time_rule='C')) + assert rng1 == rng2 + + def test_1(self): + rng = list(generate_range(start=datetime(2009, 3, 25), periods=2)) + 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))) + 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))) + expected = [] + assert rng == expected + + def test_precision_finer_than_offset(self): + # GH 9907 + result1 = DatetimeIndex(start='2015-04-15 00:00:03', + end='2016-04-22 00:00:00', freq='Q') + result2 = DatetimeIndex(start='2015-04-15 00:00:03', + end='2015-06-22 00:00:04', freq='W') + expected1_list = ['2015-06-30 00:00:03', '2015-09-30 00:00:03', + '2015-12-31 00:00:03', '2016-03-31 00:00:03'] + expected2_list = ['2015-04-19 00:00:03', '2015-04-26 00:00:03', + '2015-05-03 00:00:03', '2015-05-10 00:00:03', + '2015-05-17 00:00:03', '2015-05-24 00:00:03', + '2015-05-31 00:00:03', '2015-06-07 00:00:03', + '2015-06-14 00:00:03', '2015-06-21 00:00:03'] + expected1 = DatetimeIndex(expected1_list, dtype='datetime64[ns]', + freq='Q-DEC', tz=None) + expected2 = DatetimeIndex(expected2_list, dtype='datetime64[ns]', + freq='W-SUN', tz=None) + tm.assert_index_equal(result1, expected1) + tm.assert_index_equal(result2, expected2) + + dt1, dt2 = '2017-01-01', '2017-01-01' + tz1, tz2 = 'US/Eastern', 'Europe/London' + + @pytest.mark.parametrize("start,end", [ + (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2)), + (pd.Timestamp(dt1), pd.Timestamp(dt2, tz=tz2)), + (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2, tz=tz2)), + (pd.Timestamp(dt1, tz=tz2), pd.Timestamp(dt2, tz=tz1)) + ]) + def test_mismatching_tz_raises_err(self, start, end): + # issue 18488 + with pytest.raises(TypeError): + pd.date_range(start, end) + with pytest.raises(TypeError): + pd.DatetimeIndex(start, end, freq=BDay()) + + +class TestBusinessDateRange(object): + + def test_constructor(self): + bdate_range(START, END, freq=BDay()) + bdate_range(START, periods=20, freq=BDay()) + bdate_range(end=START, periods=20, freq=BDay()) + + msg = 'periods must be a number, got B' + with tm.assert_raises_regex(TypeError, msg): + date_range('2011-1-1', '2012-1-1', 'B') + + with tm.assert_raises_regex(TypeError, msg): + bdate_range('2011-1-1', '2012-1-1', 'B') + + msg = 'freq must be specified for bdate_range; use date_range instead' + with tm.assert_raises_regex(TypeError, msg): + bdate_range(START, END, periods=10, freq=None) + + def test_naive_aware_conflicts(self): + naive = bdate_range(START, END, freq=BDay(), tz=None) + aware = bdate_range(START, END, freq=BDay(), tz="Asia/Hong_Kong") + + msg = 'tz-naive.*tz-aware' + with tm.assert_raises_regex(TypeError, msg): + naive.join(aware) + + with tm.assert_raises_regex(TypeError, msg): + aware.join(naive) + + def test_cached_range(self): + DatetimeIndex._cached_range(START, END, freq=BDay()) + DatetimeIndex._cached_range(START, periods=20, freq=BDay()) + DatetimeIndex._cached_range(end=START, periods=20, freq=BDay()) + + with tm.assert_raises_regex(TypeError, "freq"): + DatetimeIndex._cached_range(START, END) + + with tm.assert_raises_regex(TypeError, "specify period"): + DatetimeIndex._cached_range(START, freq=BDay()) + + with tm.assert_raises_regex(TypeError, "specify period"): + DatetimeIndex._cached_range(end=END, freq=BDay()) + + with tm.assert_raises_regex(TypeError, "start or end"): + DatetimeIndex._cached_range(periods=20, freq=BDay()) + + def test_misc(self): + end = datetime(2009, 5, 13) + dr = bdate_range(end=end, periods=20) + firstDate = end - 19 * BDay() + + assert len(dr) == 20 + assert dr[0] == firstDate + assert dr[-1] == end + + def test_date_parse_failure(self): + badly_formed_date = '2007/100/1' + + with pytest.raises(ValueError): + Timestamp(badly_formed_date) + + with pytest.raises(ValueError): + bdate_range(start=badly_formed_date, periods=10) + + with pytest.raises(ValueError): + bdate_range(end=badly_formed_date, periods=10) + + with pytest.raises(ValueError): + bdate_range(badly_formed_date, badly_formed_date) + + def test_daterange_bug_456(self): + # GH #456 + rng1 = bdate_range('12/5/2011', '12/5/2011') + rng2 = bdate_range('12/2/2011', '12/5/2011') + rng2.freq = BDay() + + result = rng1.union(rng2) + assert isinstance(result, DatetimeIndex) + + @pytest.mark.parametrize('closed', ['left', 'right']) + def test_bdays_and_open_boundaries(self, closed): + # GH 6673 + start = '2018-07-21' # Saturday + end = '2018-07-29' # Sunday + result = pd.date_range(start, end, freq='B', closed=closed) + + bday_start = '2018-07-23' # Monday + bday_end = '2018-07-27' # Friday + expected = pd.date_range(bday_start, bday_end, freq='D') + tm.assert_index_equal(result, expected) + class TestCustomDateRange(object):
First contribution so this PR is really light. #6673 is resolved on master, but this PR adds some tests to confirm this behavior.
https://api.github.com/repos/pandas-dev/pandas/pulls/22095
2018-07-28T09:32:56Z
2018-07-31T13:12:53Z
2018-07-31T13:12:53Z
2018-08-01T14:42:19Z
[CLN] parametrize and cleanup a bunch of tests
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index b48395efaf5c8..f72cf8cdaafe9 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -74,29 +74,29 @@ def test_corr_non_numeric(self): tm.assert_frame_equal(result, expected) @td.skip_if_no_scipy - def test_corr_nooverlap(self): + @pytest.mark.parametrize('meth', ['pearson', 'kendall', 'spearman']) + def test_corr_nooverlap(self, meth): # nothing in common - for meth in ['pearson', 'kendall', 'spearman']: - df = DataFrame({'A': [1, 1.5, 1, np.nan, np.nan, np.nan], - 'B': [np.nan, np.nan, np.nan, 1, 1.5, 1], - 'C': [np.nan, np.nan, np.nan, np.nan, - np.nan, np.nan]}) - rs = df.corr(meth) - assert isna(rs.loc['A', 'B']) - assert isna(rs.loc['B', 'A']) - assert rs.loc['A', 'A'] == 1 - assert rs.loc['B', 'B'] == 1 - assert isna(rs.loc['C', 'C']) + df = DataFrame({'A': [1, 1.5, 1, np.nan, np.nan, np.nan], + 'B': [np.nan, np.nan, np.nan, 1, 1.5, 1], + 'C': [np.nan, np.nan, np.nan, np.nan, + np.nan, np.nan]}) + rs = df.corr(meth) + assert isna(rs.loc['A', 'B']) + assert isna(rs.loc['B', 'A']) + assert rs.loc['A', 'A'] == 1 + assert rs.loc['B', 'B'] == 1 + assert isna(rs.loc['C', 'C']) @td.skip_if_no_scipy - def test_corr_constant(self): + @pytest.mark.parametrize('meth', ['pearson', 'spearman']) + def test_corr_constant(self, meth): # constant --> all NA - for meth in ['pearson', 'spearman']: - df = DataFrame({'A': [1, 1, 1, np.nan, np.nan, np.nan], - 'B': [np.nan, np.nan, np.nan, 1, 1, 1]}) - rs = df.corr(meth) - assert isna(rs.values).all() + df = DataFrame({'A': [1, 1, 1, np.nan, np.nan, np.nan], + 'B': [np.nan, np.nan, np.nan, 1, 1, 1]}) + rs = df.corr(meth) + assert isna(rs.values).all() def test_corr_int(self): # dtypes other than float64 #1761 @@ -658,21 +658,21 @@ def test_numeric_only_flag(self, meth): pytest.raises(TypeError, lambda: getattr(df2, meth)( axis=1, numeric_only=False)) - def test_mixed_ops(self): + @pytest.mark.parametrize('op', ['mean', 'std', 'var', + 'skew', 'kurt', 'sem']) + def test_mixed_ops(self, op): # GH 16116 df = DataFrame({'int': [1, 2, 3, 4], 'float': [1., 2., 3., 4.], 'str': ['a', 'b', 'c', 'd']}) - for op in ['mean', 'std', 'var', 'skew', - 'kurt', 'sem']: + result = getattr(df, op)() + assert len(result) == 2 + + with pd.option_context('use_bottleneck', False): result = getattr(df, op)() assert len(result) == 2 - with pd.option_context('use_bottleneck', False): - result = getattr(df, op)() - assert len(result) == 2 - def test_cumsum(self): self.tsframe.loc[5:10, 0] = nan self.tsframe.loc[10:15, 1] = nan diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index e038588b76ffd..46c33000fb9ce 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -120,16 +120,15 @@ def test_apply_standard_nonunique(self): rs = df.T.apply(lambda s: s[0], axis=0) assert_series_equal(rs, xp) - def test_with_string_args(self): - - for arg in ['sum', 'mean', 'min', 'max', 'std']: - result = self.frame.apply(arg) - expected = getattr(self.frame, arg)() - tm.assert_series_equal(result, expected) + @pytest.mark.parametrize('arg', ['sum', 'mean', 'min', 'max', 'std']) + def test_with_string_args(self, arg): + result = self.frame.apply(arg) + expected = getattr(self.frame, arg)() + tm.assert_series_equal(result, expected) - result = self.frame.apply(arg, axis=1) - expected = getattr(self.frame, arg)(axis=1) - tm.assert_series_equal(result, expected) + result = self.frame.apply(arg, axis=1) + expected = getattr(self.frame, arg)(axis=1) + tm.assert_series_equal(result, expected) def test_apply_broadcast_deprecated(self): with tm.assert_produces_warning(FutureWarning): diff --git a/pandas/tests/frame/test_axis_select_reindex.py b/pandas/tests/frame/test_axis_select_reindex.py index 004fb4eb0c128..0bc74c6890ee9 100644 --- a/pandas/tests/frame/test_axis_select_reindex.py +++ b/pandas/tests/frame/test_axis_select_reindex.py @@ -674,29 +674,12 @@ def _check_align(self, a, b, axis, fill_axis, how, method, limit=None): assert_frame_equal(aa, ea) assert_frame_equal(ab, eb) - def test_align_fill_method_inner(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('inner', meth, ax, fax) - - def test_align_fill_method_outer(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('outer', meth, ax, fax) - - def test_align_fill_method_left(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('left', meth, ax, fax) - - def test_align_fill_method_right(self): - for meth in ['pad', 'bfill']: - for ax in [0, 1, None]: - for fax in [0, 1]: - self._check_align_fill('right', meth, ax, fax) + @pytest.mark.parametrize('meth', ['pad', 'bfill']) + @pytest.mark.parametrize('ax', [0, 1, None]) + @pytest.mark.parametrize('fax', [0, 1]) + @pytest.mark.parametrize('how', ['inner', 'outer', 'left', 'right']) + def test_align_fill_method(self, how, meth, ax, fax): + self._check_align_fill(how, meth, ax, fax) def _check_align_fill(self, kind, meth, ax, fax): left = self.frame.iloc[0:4, :10] diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index fdf50805ad818..1702b2e7d29a4 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -72,18 +72,18 @@ def test_operators(self): assert (df + df).equals(df) assert_frame_equal(df + df, df) - def test_ops_np_scalar(self): - vals, xs = np.random.rand(5, 3), [nan, 7, -23, 2.718, -3.14, np.inf] + @pytest.mark.parametrize('other', [nan, 7, -23, 2.718, -3.14, np.inf]) + def test_ops_np_scalar(self, other): + vals = np.random.randn(5, 3) f = lambda x: DataFrame(x, index=list('ABCDE'), columns=['jim', 'joe', 'jolie']) df = f(vals) - for x in xs: - assert_frame_equal(df / np.array(x), f(vals / x)) - assert_frame_equal(np.array(x) * df, f(vals * x)) - assert_frame_equal(df + np.array(x), f(vals + x)) - assert_frame_equal(np.array(x) - df, f(x - vals)) + assert_frame_equal(df / np.array(other), f(vals / other)) + assert_frame_equal(np.array(other) * df, f(vals * other)) + assert_frame_equal(df + np.array(other), f(vals + other)) + assert_frame_equal(np.array(other) - df, f(other - vals)) def test_operators_boolean(self): @@ -116,41 +116,40 @@ def test_operators_boolean(self): True, index=[1], columns=['A']) assert_frame_equal(result, DataFrame(1, index=[1], columns=['A'])) - def f(): - DataFrame(1.0, index=[1], columns=['A']) | DataFrame( - True, index=[1], columns=['A']) - pytest.raises(TypeError, f) + df1 = DataFrame(1.0, index=[1], columns=['A']) + df2 = DataFrame(True, index=[1], columns=['A']) + with pytest.raises(TypeError): + df1 | df2 - def f(): - DataFrame('foo', index=[1], columns=['A']) | DataFrame( - True, index=[1], columns=['A']) - pytest.raises(TypeError, f) + df1 = DataFrame('foo', index=[1], columns=['A']) + df2 = DataFrame(True, index=[1], columns=['A']) + with pytest.raises(TypeError): + df1 | df2 - def test_operators_none_as_na(self): + @pytest.mark.parametrize('op', [operator.add, operator.sub, + operator.mul, operator.truediv]) + def test_operators_none_as_na(self, op): df = DataFrame({"col1": [2, 5.0, 123, None], "col2": [1, 2, 3, 4]}, dtype=object) - ops = [operator.add, operator.sub, operator.mul, operator.truediv] - # since filling converts dtypes from object, changed expected to be # object - for op in ops: - filled = df.fillna(np.nan) - result = op(df, 3) - expected = op(filled, 3).astype(object) - expected[com.isna(expected)] = None - assert_frame_equal(result, expected) + filled = df.fillna(np.nan) + result = op(df, 3) + expected = op(filled, 3).astype(object) + expected[com.isna(expected)] = None + assert_frame_equal(result, expected) - result = op(df, df) - expected = op(filled, filled).astype(object) - expected[com.isna(expected)] = None - assert_frame_equal(result, expected) + result = op(df, df) + expected = op(filled, filled).astype(object) + expected[com.isna(expected)] = None + assert_frame_equal(result, expected) - result = op(df, df.fillna(7)) - assert_frame_equal(result, expected) + result = op(df, df.fillna(7)) + assert_frame_equal(result, expected) - result = op(df.fillna(7), df) - assert_frame_equal(result, expected, check_dtype=False) + result = op(df.fillna(7), df) + assert_frame_equal(result, expected, check_dtype=False) def test_comparison_invalid(self): @@ -978,8 +977,11 @@ def test_boolean_comparison(self): result = df.values > b_r assert_numpy_array_equal(result, expected.values) - pytest.raises(ValueError, df.__gt__, b_c) - pytest.raises(ValueError, df.values.__gt__, b_c) + with pytest.raises(ValueError): + df > b_c + + with pytest.raises(ValueError): + df.values > b_c # == expected = DataFrame([[False, False], [True, False], [False, False]]) @@ -998,7 +1000,9 @@ def test_boolean_comparison(self): result = df.values == b_r assert_numpy_array_equal(result, expected.values) - pytest.raises(ValueError, lambda: df == b_c) + with pytest.raises(ValueError): + df == b_c + assert df.values.shape != b_c.shape # with alignment diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index a226f8de3c8bd..a02f78bfaf8a5 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -1029,11 +1029,10 @@ def test_bool_arith_expr(self, parser, engine): expect = self.frame.a[self.frame.a < 1] + self.frame.b assert_series_equal(res, expect) - def test_invalid_type_for_operator_raises(self, parser, engine): + @pytest.mark.parametrize('op', ['+', '-', '*', '/']) + def test_invalid_type_for_operator_raises(self, parser, engine, op): df = DataFrame({'a': [1, 2], 'b': ['c', 'd']}) - ops = '+', '-', '*', '/' - for op in ops: - with tm.assert_raises_regex(TypeError, - r"unsupported operand type\(s\) " - "for .+: '.+' and '.+'"): - df.eval('a {0} b'.format(op), engine=engine, parser=parser) + with tm.assert_raises_regex(TypeError, + r"unsupported operand type\(s\) " + "for .+: '.+' and '.+'"): + df.eval('a {0} b'.format(op), engine=engine, parser=parser) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index dd83a94b7062a..68d799c55637c 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -547,14 +547,12 @@ def test_regex_replace_numeric_to_object_conversion(self): assert_frame_equal(res, expec) assert res.a.dtype == np.object_ - def test_replace_regex_metachar(self): - metachars = '[]', '()', r'\d', r'\w', r'\s' - - for metachar in metachars: - df = DataFrame({'a': [metachar, 'else']}) - result = df.replace({'a': {metachar: 'paren'}}) - expected = DataFrame({'a': ['paren', 'else']}) - assert_frame_equal(result, expected) + @pytest.mark.parametrize('metachar', ['[]', '()', r'\d', r'\w', r'\s']) + def test_replace_regex_metachar(self, metachar): + df = DataFrame({'a': [metachar, 'else']}) + result = df.replace({'a': {metachar: 'paren'}}) + expected = DataFrame({'a': ['paren', 'else']}) + assert_frame_equal(result, expected) def test_replace(self): self.tsframe['A'][:5] = nan diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index ebf6c5e37b916..2f90d24f652ca 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -855,21 +855,21 @@ def _test_stack_with_multiindex(multiindex): dtype=df.dtypes[0]) assert_frame_equal(result, expected) - def test_stack_preserve_categorical_dtype(self): + @pytest.mark.parametrize('ordered', [False, True]) + @pytest.mark.parametrize('labels', [list("yxz"), list("yxy")]) + def test_stack_preserve_categorical_dtype(self, ordered, labels): # GH13854 - for ordered in [False, True]: - for labels in [list("yxz"), list("yxy")]: - cidx = pd.CategoricalIndex(labels, categories=list("xyz"), - ordered=ordered) - df = DataFrame([[10, 11, 12]], columns=cidx) - result = df.stack() - - # `MutliIndex.from_product` preserves categorical dtype - - # it's tested elsewhere. - midx = pd.MultiIndex.from_product([df.index, cidx]) - expected = Series([10, 11, 12], index=midx) - - tm.assert_series_equal(result, expected) + cidx = pd.CategoricalIndex(labels, categories=list("xyz"), + ordered=ordered) + df = DataFrame([[10, 11, 12]], columns=cidx) + result = df.stack() + + # `MutliIndex.from_product` preserves categorical dtype - + # it's tested elsewhere. + midx = pd.MultiIndex.from_product([df.index, cidx]) + expected = Series([10, 11, 12], index=midx) + + tm.assert_series_equal(result, expected) @pytest.mark.parametrize("level", [0, 'baz']) def test_unstack_swaplevel_sortlevel(self, level): diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index eccd86a888fb9..0e0ea51479e81 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1038,9 +1038,10 @@ def test_add_raises(self): dt1 + dt2 boxes = [lambda x: x, lambda x: pd.Series([x]), lambda x: pd.Index([x])] + ids = ['identity', 'Series', 'Index'] - @pytest.mark.parametrize('lbox', boxes) - @pytest.mark.parametrize('rbox', boxes) + @pytest.mark.parametrize('lbox', boxes, ids=ids) + @pytest.mark.parametrize('rbox', boxes, ids=ids) def test_add_timestamp_raises(self, rbox, lbox): # GH # 17983 ts = pd.Timestamp('2017') diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 840c80d6775a5..ed3191cf849c0 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -237,6 +237,23 @@ def test_rename_axis_inplace(self): assert no_return is None assert_series_equal(result, expected) + def test_set_axis_inplace_axes(self, axis_series): + # GH14636 + ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype='int64') + + expected = ser.copy() + expected.index = list('abcd') + + # inplace=True + # The FutureWarning comes from the fact that we would like to have + # inplace default to False some day + for inplace, warn in [(None, FutureWarning), (True, None)]: + result = ser.copy() + kwargs = {'inplace': inplace} + with tm.assert_produces_warning(warn): + result.set_axis(list('abcd'), axis=axis_series, **kwargs) + tm.assert_series_equal(result, expected) + def test_set_axis_inplace(self): # GH14636 @@ -245,17 +262,6 @@ def test_set_axis_inplace(self): expected = s.copy() expected.index = list('abcd') - for axis in 0, 'index': - # inplace=True - # The FutureWarning comes from the fact that we would like to have - # inplace default to False some day - for inplace, warn in (None, FutureWarning), (True, None): - result = s.copy() - kwargs = {'inplace': inplace} - with tm.assert_produces_warning(warn): - result.set_axis(list('abcd'), axis=axis, **kwargs) - tm.assert_series_equal(result, expected) - # inplace=False result = s.set_axis(list('abcd'), axis=0, inplace=False) tm.assert_series_equal(expected, result) @@ -266,7 +272,7 @@ def test_set_axis_inplace(self): tm.assert_series_equal(result, expected) # wrong values for the "axis" parameter - for axis in 2, 'foo': + for axis in [2, 'foo']: with tm.assert_raises_regex(ValueError, 'No axis named'): s.set_axis(list('abcd'), axis=axis, inplace=False) @@ -276,7 +282,7 @@ def test_set_axis_prior_to_deprecation_signature(self): expected = s.copy() expected.index = list('abcd') - for axis in 0, 'index': + for axis in [0, 'index']: with tm.assert_produces_warning(FutureWarning): result = s.set_axis(0, list('abcd'), inplace=False) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index 47798d0ddd7f5..7a02ce3a1fb2e 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -255,12 +255,9 @@ def get_dir(s): # trying to set a copy with pd.option_context('chained_assignment', 'raise'): - - def f(): + with pytest.raises(com.SettingWithCopyError): s.dt.hour[0] = 5 - pytest.raises(com.SettingWithCopyError, f) - def test_dt_namespace_accessor_categorical(self): # GH 19468 dti = DatetimeIndex(['20171111', '20181212']).repeat(2) @@ -420,12 +417,14 @@ def test_dt_accessor_api(self): s = Series(date_range('2000-01-01', periods=3)) assert isinstance(s.dt, DatetimeProperties) - for s in [Series(np.arange(5)), Series(list('abcde')), - Series(np.random.randn(5))]: - with tm.assert_raises_regex(AttributeError, - "only use .dt accessor"): - s.dt - assert not hasattr(s, 'dt') + @pytest.mark.parametrize('ser', [Series(np.arange(5)), + Series(list('abcde')), + Series(np.random.randn(5))]) + def test_dt_accessor_invalid(self, ser): + # GH#9322 check that series with incorrect dtypes don't have attr + with tm.assert_raises_regex(AttributeError, "only use .dt accessor"): + ser.dt + assert not hasattr(ser, 'dt') def test_between(self): s = Series(bdate_range('1/1/2000', periods=20).astype(object)) diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index ecb74622edf10..fad2b025dd3e4 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -136,10 +136,14 @@ def test_categorical_comparisons(self): assert ((~(f == a) == (f != a)).all()) # non-equality is not comparable - pytest.raises(TypeError, lambda: a < b) - pytest.raises(TypeError, lambda: b < a) - pytest.raises(TypeError, lambda: a > b) - pytest.raises(TypeError, lambda: b > a) + with pytest.raises(TypeError): + a < b + with pytest.raises(TypeError): + b < a + with pytest.raises(TypeError): + a > b + with pytest.raises(TypeError): + b > a def test_comparison_tuples(self): # GH11339 @@ -204,20 +208,21 @@ def test_comparison_operators_with_nas(self): # expected = f(val, s.dropna()).reindex(s.index) # assert_series_equal(result, expected) - # boolean &, |, ^ should work with object arrays and propagate NAs + @pytest.mark.parametrize('bool_op', [operator.and_, + operator.or_, operator.xor]) + def test_bool_operators_with_nas(self, bool_op): + # boolean &, |, ^ should work with object arrays and propagate NAs + ser = Series(bdate_range('1/1/2000', periods=10), dtype=object) + ser[::2] = np.nan - ops = ['and_', 'or_', 'xor'] mask = ser.isna() - for bool_op in ops: - func = getattr(operator, bool_op) - - filled = ser.fillna(ser[0]) + filled = ser.fillna(ser[0]) - result = func(ser < ser[9], ser > ser[3]) + result = bool_op(ser < ser[9], ser > ser[3]) - expected = func(filled < filled[9], filled > filled[3]) - expected[mask] = False - assert_series_equal(result, expected) + expected = bool_op(filled < filled[9], filled > filled[3]) + expected[mask] = False + assert_series_equal(result, expected) def test_comparison_object_numeric_nas(self): ser = Series(np.random.randn(10), dtype=object) @@ -248,27 +253,26 @@ def test_comparison_invalid(self): def test_unequal_categorical_comparison_raises_type_error(self): # unequal comparison should raise for unordered cats cat = Series(Categorical(list("abc"))) - - def f(): + with pytest.raises(TypeError): cat > "b" - pytest.raises(TypeError, f) cat = Series(Categorical(list("abc"), ordered=False)) - - def f(): + with pytest.raises(TypeError): cat > "b" - pytest.raises(TypeError, f) - # https://github.com/pandas-dev/pandas/issues/9836#issuecomment-92123057 # and following comparisons with scalars not in categories should raise # for unequal comps, but not for equal/not equal cat = Series(Categorical(list("abc"), ordered=True)) - pytest.raises(TypeError, lambda: cat < "d") - pytest.raises(TypeError, lambda: cat > "d") - pytest.raises(TypeError, lambda: "d" < cat) - pytest.raises(TypeError, lambda: "d" > cat) + with pytest.raises(TypeError): + cat < "d" + with pytest.raises(TypeError): + cat > "d" + with pytest.raises(TypeError): + "d" < cat + with pytest.raises(TypeError): + "d" > cat tm.assert_series_equal(cat == "d", Series([False, False, False])) tm.assert_series_equal(cat != "d", Series([True, True, True])) @@ -365,11 +369,13 @@ def test_nat_comparisons_scalar(self, dtype, data): def test_comparison_different_length(self): a = Series(['a', 'b', 'c']) b = Series(['b', 'a']) - pytest.raises(ValueError, a.__lt__, b) + with pytest.raises(ValueError): + a < b a = Series([1, 2]) b = Series([2, 3, 4]) - pytest.raises(ValueError, a.__eq__, b) + with pytest.raises(ValueError): + a == b def test_comparison_label_based(self): @@ -448,7 +454,8 @@ def test_comparison_label_based(self): assert_series_equal(result, expected) for v in [np.nan, 'foo']: - pytest.raises(TypeError, lambda: t | v) + with pytest.raises(TypeError): + t | v for v in [False, 0]: result = Series([True, False, True], index=index) | v @@ -465,7 +472,8 @@ def test_comparison_label_based(self): expected = Series([False, False, False], index=index) assert_series_equal(result, expected) for v in [np.nan]: - pytest.raises(TypeError, lambda: t & v) + with pytest.raises(TypeError): + t & v def test_comparison_flex_basic(self): left = pd.Series(np.random.randn(10)) @@ -930,12 +938,14 @@ def test_operators_datetimelike_with_timezones(self): result = dt1 - td1[0] exp = (dt1.dt.tz_localize(None) - td1[0]).dt.tz_localize(tz) assert_series_equal(result, exp) - pytest.raises(TypeError, lambda: td1[0] - dt1) + with pytest.raises(TypeError): + td1[0] - dt1 result = dt2 - td2[0] exp = (dt2.dt.tz_localize(None) - td2[0]).dt.tz_localize(tz) assert_series_equal(result, exp) - pytest.raises(TypeError, lambda: td2[0] - dt2) + with pytest.raises(TypeError): + td2[0] - dt2 result = dt1 + td1 exp = (dt1.dt.tz_localize(None) + td1).dt.tz_localize(tz) @@ -953,8 +963,10 @@ def test_operators_datetimelike_with_timezones(self): exp = (dt2.dt.tz_localize(None) - td2).dt.tz_localize(tz) assert_series_equal(result, exp) - pytest.raises(TypeError, lambda: td1 - dt1) - pytest.raises(TypeError, lambda: td2 - dt2) + with pytest.raises(TypeError): + td1 - dt1 + with pytest.raises(TypeError): + td2 - dt2 def test_sub_single_tz(self): # GH12290 @@ -1483,11 +1495,16 @@ def test_operators_bitwise(self): expected = Series([1, 1, 3, 3], dtype='int32') assert_series_equal(res, expected) - pytest.raises(TypeError, lambda: s_1111 & 'a') - pytest.raises(TypeError, lambda: s_1111 & ['a', 'b', 'c', 'd']) - pytest.raises(TypeError, lambda: s_0123 & np.NaN) - pytest.raises(TypeError, lambda: s_0123 & 3.14) - pytest.raises(TypeError, lambda: s_0123 & [0.1, 4, 3.14, 2]) + with pytest.raises(TypeError): + s_1111 & 'a' + with pytest.raises(TypeError): + s_1111 & ['a', 'b', 'c', 'd'] + with pytest.raises(TypeError): + s_0123 & np.NaN + with pytest.raises(TypeError): + s_0123 & 3.14 + with pytest.raises(TypeError): + s_0123 & [0.1, 4, 3.14, 2] # s_0123 will be all false now because of reindexing like s_tft if compat.PY3: @@ -1530,14 +1547,16 @@ def test_scalar_na_cmp_corners(self): def tester(a, b): return a & b - pytest.raises(TypeError, tester, s, datetime(2005, 1, 1)) + with pytest.raises(TypeError): + s & datetime(2005, 1, 1) s = Series([2, 3, 4, 5, 6, 7, 8, 9, datetime(2005, 1, 1)]) s[::2] = np.nan expected = Series(True, index=s.index) expected[::2] = False - assert_series_equal(tester(s, list(s)), expected) + result = s & list(s) + assert_series_equal(result, expected) d = DataFrame({'A': s}) # TODO: Fix this exception - needs to be fixed! (see GH5035) @@ -1587,7 +1606,25 @@ def test_operators_reverse_object(self, op): expected = op(1., arr.astype(float)) assert_series_equal(result.astype(float), expected) - def test_operators_combine(self): + pairings = [] + for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']: + fv = 0 + lop = getattr(Series, op) + lequiv = getattr(operator, op) + rop = getattr(Series, 'r' + op) + # bind op at definition time... + requiv = lambda x, y, op=op: getattr(operator, op)(y, x) + pairings.append((lop, lequiv, fv)) + pairings.append((rop, requiv, fv)) + if compat.PY3: + pairings.append((Series.div, operator.truediv, 1)) + pairings.append((Series.rdiv, lambda x, y: operator.truediv(y, x), 1)) + else: + pairings.append((Series.div, operator.div, 1)) + pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1)) + + @pytest.mark.parametrize('op, equiv_op, fv', pairings) + def test_operators_combine(self, op, equiv_op, fv): def _check_fill(meth, op, a, b, fill_value=0): exp_index = a.index.union(b.index) a = a.reindex(exp_index) @@ -1619,32 +1656,12 @@ def _check_fill(meth, op, a, b, fill_value=0): a = Series([nan, 1., 2., 3., nan], index=np.arange(5)) b = Series([nan, 1, nan, 3, nan, 4.], index=np.arange(6)) - pairings = [] - for op in ['add', 'sub', 'mul', 'pow', 'truediv', 'floordiv']: - fv = 0 - lop = getattr(Series, op) - lequiv = getattr(operator, op) - rop = getattr(Series, 'r' + op) - # bind op at definition time... - requiv = lambda x, y, op=op: getattr(operator, op)(y, x) - pairings.append((lop, lequiv, fv)) - pairings.append((rop, requiv, fv)) - - if compat.PY3: - pairings.append((Series.div, operator.truediv, 1)) - pairings.append((Series.rdiv, lambda x, y: operator.truediv(y, x), - 1)) - else: - pairings.append((Series.div, operator.div, 1)) - pairings.append((Series.rdiv, lambda x, y: operator.div(y, x), 1)) - - for op, equiv_op, fv in pairings: - result = op(a, b) - exp = equiv_op(a, b) - assert_series_equal(result, exp) - _check_fill(op, equiv_op, a, b, fill_value=fv) - # should accept axis=0 or axis='rows' - op(a, b, axis=0) + result = op(a, b) + exp = equiv_op(a, b) + assert_series_equal(result, exp) + _check_fill(op, equiv_op, a, b, fill_value=fv) + # should accept axis=0 or axis='rows' + op(a, b, axis=0) def test_operators_na_handling(self): from decimal import Decimal diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index 63726f27914f3..62b59b5d405c9 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd import pandas.util.testing as tm @@ -72,22 +73,23 @@ def test_between(self): # --------------------------------------------------------------------- # NaT support - """ - # ToDo: Enable when support period dtype + @pytest.mark.xfail(reason="PeriodDtype Series not supported yet", + strict=True) def test_NaT_scalar(self): - series = Series([0, 1000, 2000, iNaT], dtype='period[D]') + series = Series([0, 1000, 2000, pd._libs.iNaT], dtype='period[D]') val = series[3] - assert isna(val) + assert pd.isna(val) series[2] = val - assert isna(series[2]) + assert pd.isna(series[2]) + @pytest.mark.xfail(reason="PeriodDtype Series not supported yet", + strict=True) def test_NaT_cast(self): result = Series([np.nan]).astype('period[D]') - expected = Series([NaT]) + expected = Series([pd.NaT]) tm.assert_series_equal(result, expected) - """ def test_set_none_nan(self): # currently Period is stored as object dtype, not as NaT diff --git a/pandas/tests/series/test_quantile.py b/pandas/tests/series/test_quantile.py index 3c93ff1d3f31e..df8799cf5c900 100644 --- a/pandas/tests/series/test_quantile.py +++ b/pandas/tests/series/test_quantile.py @@ -1,6 +1,8 @@ # coding=utf-8 # pylint: disable-msg=E1101,W0612 +import pytest + import numpy as np import pandas as pd @@ -113,31 +115,30 @@ def test_quantile_nan(self): tm.assert_series_equal(res, pd.Series([np.nan, np.nan], index=[0.2, 0.3])) - def test_quantile_box(self): - cases = [[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), - pd.Timestamp('2011-01-03')], - [pd.Timestamp('2011-01-01', tz='US/Eastern'), - pd.Timestamp('2011-01-02', tz='US/Eastern'), - pd.Timestamp('2011-01-03', tz='US/Eastern')], - [pd.Timedelta('1 days'), pd.Timedelta('2 days'), - pd.Timedelta('3 days')], - # NaT - [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), - pd.Timestamp('2011-01-03'), pd.NaT], - [pd.Timestamp('2011-01-01', tz='US/Eastern'), - pd.Timestamp('2011-01-02', tz='US/Eastern'), - pd.Timestamp('2011-01-03', tz='US/Eastern'), pd.NaT], - [pd.Timedelta('1 days'), pd.Timedelta('2 days'), - pd.Timedelta('3 days'), pd.NaT]] - - for case in cases: - s = pd.Series(case, name='XXX') - res = s.quantile(0.5) - assert res == case[1] + @pytest.mark.parametrize('case', [ + [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), + pd.Timestamp('2011-01-03')], + [pd.Timestamp('2011-01-01', tz='US/Eastern'), + pd.Timestamp('2011-01-02', tz='US/Eastern'), + pd.Timestamp('2011-01-03', tz='US/Eastern')], + [pd.Timedelta('1 days'), pd.Timedelta('2 days'), + pd.Timedelta('3 days')], + # NaT + [pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), + pd.Timestamp('2011-01-03'), pd.NaT], + [pd.Timestamp('2011-01-01', tz='US/Eastern'), + pd.Timestamp('2011-01-02', tz='US/Eastern'), + pd.Timestamp('2011-01-03', tz='US/Eastern'), pd.NaT], + [pd.Timedelta('1 days'), pd.Timedelta('2 days'), + pd.Timedelta('3 days'), pd.NaT]]) + def test_quantile_box(self, case): + s = pd.Series(case, name='XXX') + res = s.quantile(0.5) + assert res == case[1] - res = s.quantile([0.5]) - exp = pd.Series([case[1]], index=[0.5], name='XXX') - tm.assert_series_equal(res, exp) + res = s.quantile([0.5]) + exp = pd.Series([case[1]], index=[0.5], name='XXX') + tm.assert_series_equal(res, exp) def test_datetime_timedelta_quantiles(self): # covers #9694 diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 376b4d71f81e8..72492de4b1247 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -78,7 +78,8 @@ def test_shift(self): assert_series_equal(shifted2, shifted3) assert_series_equal(ps, shifted2.shift(-1, 'B')) - pytest.raises(ValueError, ps.shift, freq='D') + with pytest.raises(ValueError): + ps.shift(freq='D') # legacy support shifted4 = ps.shift(1, freq='B') @@ -109,7 +110,8 @@ def test_shift(self): # incompat tz s2 = Series(date_range('2000-01-01 09:00:00', periods=5, tz='CET'), name='foo') - pytest.raises(TypeError, lambda: s - s2) + with pytest.raises(TypeError): + s - s2 def test_shift2(self): ts = Series(np.random.randn(5), @@ -168,7 +170,8 @@ def test_tshift(self): shifted3 = ps.tshift(freq=BDay()) assert_series_equal(shifted, shifted3) - pytest.raises(ValueError, ps.tshift, freq='M') + with pytest.raises(ValueError): + ps.tshift(freq='M') # DatetimeIndex shifted = self.ts.tshift(1) @@ -187,7 +190,8 @@ def test_tshift(self): assert_series_equal(unshifted, inferred_ts) no_freq = self.ts[[0, 5, 7]] - pytest.raises(ValueError, no_freq.tshift) + with pytest.raises(ValueError): + no_freq.tshift() def test_truncate(self): offset = BDay() @@ -459,7 +463,8 @@ def test_empty_series_ops(self): assert_series_equal(a, a + b) assert_series_equal(a, a - b) assert_series_equal(a, b + a) - pytest.raises(TypeError, lambda x, y: x - y, b, a) + with pytest.raises(TypeError): + b - a def test_contiguous_boolean_preserve_freq(self): rng = date_range('1/1/2000', '3/1/2000', freq='B') @@ -791,16 +796,19 @@ def test_between_time_raises(self): def test_between_time_types(self): # GH11818 rng = date_range('1/1/2000', '1/5/2000', freq='5min') - pytest.raises(ValueError, rng.indexer_between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + with pytest.raises(ValueError): + rng.indexer_between_time(datetime(2010, 1, 2, 1), + datetime(2010, 1, 2, 5)) frame = DataFrame({'A': 0}, index=rng) - pytest.raises(ValueError, frame.between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + with pytest.raises(ValueError): + frame.between_time(datetime(2010, 1, 2, 1), + datetime(2010, 1, 2, 5)) series = Series(0, index=rng) - pytest.raises(ValueError, series.between_time, - datetime(2010, 1, 2, 1), datetime(2010, 1, 2, 5)) + with pytest.raises(ValueError): + series.between_time(datetime(2010, 1, 2, 1), + datetime(2010, 1, 2, 5)) @td.skip_if_has_locale def test_between_time_formats(self): @@ -921,40 +929,40 @@ def test_pickle(self): idx_p = tm.round_trip_pickle(idx) tm.assert_index_equal(idx, idx_p) - def test_setops_preserve_freq(self): - for tz in [None, 'Asia/Tokyo', 'US/Eastern']: - rng = date_range('1/1/2000', '1/1/2002', name='idx', tz=tz) - - result = rng[:50].union(rng[50:100]) - assert result.name == rng.name - assert result.freq == rng.freq - assert result.tz == rng.tz - - result = rng[:50].union(rng[30:100]) - assert result.name == rng.name - assert result.freq == rng.freq - assert result.tz == rng.tz - - result = rng[:50].union(rng[60:100]) - assert result.name == rng.name - assert result.freq is None - assert result.tz == rng.tz - - result = rng[:50].intersection(rng[25:75]) - assert result.name == rng.name - assert result.freqstr == 'D' - assert result.tz == rng.tz - - nofreq = DatetimeIndex(list(rng[25:75]), name='other') - result = rng[:50].union(nofreq) - assert result.name is None - assert result.freq == rng.freq - assert result.tz == rng.tz - - result = rng[:50].intersection(nofreq) - assert result.name is None - assert result.freq == rng.freq - assert result.tz == rng.tz + @pytest.mark.parametrize('tz', [None, 'Asia/Tokyo', 'US/Eastern']) + def test_setops_preserve_freq(self, tz): + rng = date_range('1/1/2000', '1/1/2002', name='idx', tz=tz) + + result = rng[:50].union(rng[50:100]) + assert result.name == rng.name + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].union(rng[30:100]) + assert result.name == rng.name + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].union(rng[60:100]) + assert result.name == rng.name + assert result.freq is None + assert result.tz == rng.tz + + result = rng[:50].intersection(rng[25:75]) + assert result.name == rng.name + assert result.freqstr == 'D' + assert result.tz == rng.tz + + nofreq = DatetimeIndex(list(rng[25:75]), name='other') + result = rng[:50].union(nofreq) + assert result.name is None + assert result.freq == rng.freq + assert result.tz == rng.tz + + result = rng[:50].intersection(nofreq) + assert result.name is None + assert result.freq == rng.freq + assert result.tz == rng.tz def test_min_max(self): rng = date_range('1/1/2000', '12/31/2000')
https://api.github.com/repos/pandas-dev/pandas/pulls/22093
2018-07-28T04:00:58Z
2018-07-31T13:18:11Z
2018-07-31T13:18:11Z
2018-08-08T15:52:53Z
CLN: Remove vbench_to_asv.py
diff --git a/asv_bench/vbench_to_asv.py b/asv_bench/vbench_to_asv.py deleted file mode 100644 index b1179387e65d5..0000000000000 --- a/asv_bench/vbench_to_asv.py +++ /dev/null @@ -1,163 +0,0 @@ -import ast -import vbench -import os -import sys -import astor -import glob - - -def vbench_to_asv_source(bench, kinds=None): - tab = ' ' * 4 - if kinds is None: - kinds = ['time'] - - output = 'class {}(object):\n'.format(bench.name) - output += tab + 'goal_time = 0.2\n\n' - - if bench.setup: - indented_setup = [tab * 2 + '{}\n'.format(x) for x in bench.setup.splitlines()] - output += tab + 'def setup(self):\n' + ''.join(indented_setup) + '\n' - - for kind in kinds: - output += tab + 'def {}_{}(self):\n'.format(kind, bench.name) - for line in bench.code.splitlines(): - output += tab * 2 + line + '\n' - output += '\n\n' - - if bench.cleanup: - output += tab + 'def teardown(self):\n' + tab * 2 + bench.cleanup - - output += '\n\n' - return output - - -class AssignToSelf(ast.NodeTransformer): - def __init__(self): - super(AssignToSelf, self).__init__() - self.transforms = {} - self.imports = [] - - self.in_class_define = False - self.in_setup = False - - def visit_ClassDef(self, node): - self.transforms = {} - self.in_class_define = True - - functions_to_promote = [] - setup_func = None - - for class_func in ast.iter_child_nodes(node): - if isinstance(class_func, ast.FunctionDef): - if class_func.name == 'setup': - setup_func = class_func - for anon_func in ast.iter_child_nodes(class_func): - if isinstance(anon_func, ast.FunctionDef): - functions_to_promote.append(anon_func) - - if setup_func: - for func in functions_to_promote: - setup_func.body.remove(func) - func.args.args.insert(0, ast.Name(id='self', ctx=ast.Load())) - node.body.append(func) - self.transforms[func.name] = 'self.' + func.name - - ast.fix_missing_locations(node) - - self.generic_visit(node) - - return node - - def visit_TryExcept(self, node): - if any(isinstance(x, (ast.Import, ast.ImportFrom)) for x in node.body): - self.imports.append(node) - else: - self.generic_visit(node) - return node - - def visit_Assign(self, node): - for target in node.targets: - if isinstance(target, ast.Name) and not isinstance(target.ctx, ast.Param) and not self.in_class_define: - self.transforms[target.id] = 'self.' + target.id - self.generic_visit(node) - - return node - - def visit_Name(self, node): - new_node = node - if node.id in self.transforms: - if not isinstance(node.ctx, ast.Param): - new_node = ast.Attribute(value=ast.Name(id='self', ctx=node.ctx), attr=node.id, ctx=node.ctx) - - self.generic_visit(node) - - return ast.copy_location(new_node, node) - - def visit_Import(self, node): - self.imports.append(node) - - def visit_ImportFrom(self, node): - self.imports.append(node) - - def visit_FunctionDef(self, node): - """Delete functions that are empty due to imports being moved""" - self.in_class_define = False - - self.generic_visit(node) - - if node.body: - return node - - -def translate_module(target_module): - g_vars = {} - l_vars = {} - exec('import ' + target_module) in g_vars - - print(target_module) - module = eval(target_module, g_vars) - - benchmarks = [] - for obj_str in dir(module): - obj = getattr(module, obj_str) - if isinstance(obj, vbench.benchmark.Benchmark): - benchmarks.append(obj) - - if not benchmarks: - return - - rewritten_output = '' - for bench in benchmarks: - rewritten_output += vbench_to_asv_source(bench) - - with open('rewrite.py', 'w') as f: - f.write(rewritten_output) - - ast_module = ast.parse(rewritten_output) - - transformer = AssignToSelf() - transformed_module = transformer.visit(ast_module) - - unique_imports = {astor.to_source(node): node for node in transformer.imports} - - transformed_module.body = unique_imports.values() + transformed_module.body - - transformed_source = astor.to_source(transformed_module) - - with open('benchmarks/{}.py'.format(target_module), 'w') as f: - f.write(transformed_source) - - -if __name__ == '__main__': - cwd = os.getcwd() - new_dir = os.path.join(os.path.dirname(__file__), '../vb_suite') - sys.path.insert(0, new_dir) - - for module in glob.glob(os.path.join(new_dir, '*.py')): - mod = os.path.basename(module) - if mod in ['make.py', 'measure_memory_consumption.py', 'perf_HEAD.py', 'run_suite.py', 'test_perf.py', 'generate_rst_files.py', 'test.py', 'suite.py']: - continue - print('') - print(mod) - - translate_module(mod.replace('.py', ''))
Since pandas has been using ASV for performance benchmarking, and artifacts of vbench are gone, there doesn't appear a need for this script anymore.
https://api.github.com/repos/pandas-dev/pandas/pulls/22089
2018-07-28T00:09:26Z
2018-07-28T13:16:48Z
2018-07-28T13:16:48Z
2018-07-28T18:51:07Z
Remove unused cimports, fix #22067
diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx index 4489847518a1d..ff92ee306288a 100644 --- a/pandas/_libs/hashing.pyx +++ b/pandas/_libs/hashing.pyx @@ -3,7 +3,7 @@ # at https://github.com/veorq/SipHash import cython -cimport numpy as cnp + import numpy as np from numpy cimport ndarray, uint8_t, uint32_t, uint64_t diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index 7803595badee1..5c8efa8c03712 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -2,8 +2,6 @@ # cython: profile=False import re -cimport cython - cimport numpy as cnp cnp.import_array() diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 580d155f87fa8..ffa3d8df44be8 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -14,9 +14,7 @@ from cpython.datetime cimport datetime import time import numpy as np -cimport numpy as cnp -from numpy cimport int64_t, ndarray -cnp.import_array() +from numpy cimport ndarray # Avoid import from outside _libs if sys.version_info.major == 2: diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 4054154cd285b..65fb0f331d039 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1920,8 +1920,8 @@ class Period(_Period): return cls._from_ordinal(ordinal, freq) -cdef int64_t _ordinal_from_fields(year, month, quarter, day, - hour, minute, second, freq): +cdef int64_t _ordinal_from_fields(int year, int month, quarter, int day, + int hour, int minute, int second, freq): base, mult = get_freq_code(freq) if quarter is not None: year, month = quarter_to_myear(year, quarter, freq) diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 4b90c669eebba..0659e2a553e7e 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -5,9 +5,7 @@ cimport cython from cython cimport Py_ssize_t import numpy as np -cimport numpy as cnp from numpy cimport ndarray, int64_t, int32_t -cnp.import_array() from util cimport is_string_object, get_nat diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index a843a8e2b5612..de2b7440156a7 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -25,8 +25,6 @@ import pytz from cython cimport Py_ssize_t from cpython cimport PyFloat_Check -cimport cython - import numpy as np from numpy cimport ndarray, int64_t diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index 6453b5ed2ab3a..efc8a02014bc0 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -9,7 +9,7 @@ from libc.stdlib cimport malloc, free import numpy as np cimport numpy as cnp -from numpy cimport ndarray, double_t, int64_t, float64_t +from numpy cimport ndarray, double_t, int64_t, float64_t, float32_t cnp.import_array() @@ -25,11 +25,11 @@ from skiplist cimport (skiplist_t, skiplist_init, skiplist_destroy, skiplist_get, skiplist_insert, skiplist_remove) -cdef cnp.float32_t MINfloat32 = np.NINF -cdef cnp.float64_t MINfloat64 = np.NINF +cdef float32_t MINfloat32 = np.NINF +cdef float64_t MINfloat64 = np.NINF -cdef cnp.float32_t MAXfloat32 = np.inf -cdef cnp.float64_t MAXfloat64 = np.inf +cdef float32_t MAXfloat32 = np.inf +cdef float64_t MAXfloat64 = np.inf cdef double NaN = <double> np.NaN diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx index 77d8ca81258a0..041eb59812ae3 100644 --- a/pandas/_libs/writers.pyx +++ b/pandas/_libs/writers.pyx @@ -12,9 +12,7 @@ except ImportError: from cpython cimport PyUnicode_GET_SIZE as PyString_GET_SIZE import numpy as np -cimport numpy as cnp from numpy cimport ndarray, uint8_t -cnp.import_array() ctypedef fused pandas_string: diff --git a/pandas/io/msgpack/_packer.pyx b/pandas/io/msgpack/_packer.pyx index c81069c8e04c0..d67c632188e62 100644 --- a/pandas/io/msgpack/_packer.pyx +++ b/pandas/io/msgpack/_packer.pyx @@ -1,10 +1,16 @@ # coding: utf-8 # cython: embedsignature=True -from cpython cimport * -from libc.stdlib cimport * -from libc.string cimport * -from libc.limits cimport * +from cpython cimport ( + PyFloat_Check, PyLong_Check, PyInt_Check, + PyDict_CheckExact, PyDict_Check, + PyTuple_Check, PyList_Check, + PyCallable_Check, + PyUnicode_Check, PyBytes_Check, + PyBytes_AsString, + PyBytes_FromStringAndSize, + PyUnicode_AsEncodedString) +from libc.stdlib cimport free, malloc from pandas.io.msgpack.exceptions import PackValueError from pandas.io.msgpack import ExtType @@ -74,7 +80,7 @@ cdef class Packer(object): cdef object _berrors cdef char *encoding cdef char *unicode_errors - cdef bool use_float + cdef bint use_float cdef bint autoreset def __cinit__(self): diff --git a/pandas/io/msgpack/_unpacker.pyx b/pandas/io/msgpack/_unpacker.pyx index 427414b80dfe4..0c50aa5e68103 100644 --- a/pandas/io/msgpack/_unpacker.pyx +++ b/pandas/io/msgpack/_unpacker.pyx @@ -1,15 +1,23 @@ # coding: utf-8 # cython: embedsignature=True -from cpython cimport * +from cython cimport Py_ssize_t + +from cpython cimport ( + PyCallable_Check, + PyBUF_SIMPLE, PyObject_GetBuffer, PyBuffer_Release, + PyBytes_Size, + PyBytes_FromStringAndSize, + PyBytes_AsString) + cdef extern from "Python.h": ctypedef struct PyObject cdef int PyObject_AsReadBuffer(object o, const void** buff, Py_ssize_t* buf_len) except -1 -from libc.stdlib cimport * -from libc.string cimport * -from libc.limits cimport * +from libc.stdlib cimport free, malloc +from libc.string cimport memcpy, memmove +from libc.limits cimport INT_MAX from pandas.io.msgpack.exceptions import (BufferFull, OutOfData, UnpackValueError, ExtraData) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 1a5f12103595c..2adf09924a509 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -1,4 +1,5 @@ import warnings +import sys import pytest @@ -126,6 +127,16 @@ def test_map(self): exp = Index([f(x) for x in rng], dtype='<U8') tm.assert_index_equal(result, exp) + @tm.capture_stderr + def test_map_fallthrough(self): + # GH#22067, check we don't get warnings about silently ignored errors + dti = date_range('2017-01-01', '2018-01-01', freq='B') + + dti.map(lambda x: pd.Period(year=x.year, month=x.month, freq='M')) + + cv = sys.stderr.getvalue() + assert cv == '' + def test_iteration_preserves_tz(self): # see gh-8890 index = date_range("2012-01-01", periods=3, freq='H', tz='US/Eastern')
Fixes #22067, but no clear way to test it. - [x] closes #22067
https://api.github.com/repos/pandas-dev/pandas/pulls/22087
2018-07-27T23:10:42Z
2018-07-30T10:31:36Z
2018-07-30T10:31:36Z
2018-08-08T15:53:42Z
BUG: maximum recursion error when replacing empty lists
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index ea0677a0edf28..7c46a1c7b7f27 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -667,6 +667,7 @@ Reshaping - Bug in :meth:`DataFrame.replace` raises RecursionError when converting OutOfBounds ``datetime64[ns, tz]`` (:issue:`20380`) - :func:`pandas.core.groupby.GroupBy.rank` now raises a ``ValueError`` when an invalid value is passed for argument ``na_option`` (:issue:`22124`) - Bug in :func:`get_dummies` with Unicode attributes in Python 2 (:issue:`22084`) +- Bug in :meth:`DataFrame.replace` raises ``RecursionError`` when replacing empty lists (:issue:`22083`) - Build Changes diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8ee91ded4ab7a..be80a605f08fd 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -777,10 +777,9 @@ def copy(self, deep=True, mgr=None): def replace(self, to_replace, value, inplace=False, filter=None, regex=False, convert=True, mgr=None): - """ replace the to_replace value with value, possible to create new + """replace the to_replace value with value, possible to create new blocks here this is just a call to putmask. regex is not used here. - It is used in ObjectBlocks. It is here for API - compatibility. + It is used in ObjectBlocks. It is here for API compatibility. """ inplace = validate_bool_kwarg(inplace, 'inplace') @@ -802,6 +801,11 @@ def replace(self, to_replace, value, inplace=False, filter=None, copy=not inplace) for b in blocks] return blocks except (TypeError, ValueError): + # GH 22083, TypeError or ValueError occurred within error handling + # causes infinite loop. Cast and retry only if not objectblock. + if is_object_dtype(self): + raise + # try again with a compatible block block = self.astype(object) return block.replace(to_replace=original_to_replace, diff --git a/pandas/core/missing.py b/pandas/core/missing.py index a46c19e2d399c..b2daec327d618 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -68,6 +68,10 @@ def mask_missing(arr, values_to_mask): else: mask |= isna(arr) + # GH 21977 + if mask is None: + mask = np.zeros(arr.shape, dtype=bool) + return mask diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index 227484abb82c1..49dba1c769572 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -603,6 +603,20 @@ def test_replace_list(self): assert_frame_equal(res, expec) + def test_replace_with_empty_list(self): + # GH 21977 + s = pd.Series([['a', 'b'], [], np.nan, [1]]) + df = pd.DataFrame({'col': s}) + expected = df + result = df.replace([], np.nan) + assert_frame_equal(result, expected) + + # GH 19266 + with tm.assert_raises_regex(ValueError, "cannot assign mismatch"): + df.replace({np.nan: []}) + with tm.assert_raises_regex(ValueError, "cannot assign mismatch"): + df.replace({np.nan: ['dummy', 'alt']}) + def test_replace_series_dict(self): # from GH 3064 df = DataFrame({'zero': {'a': 0.0, 'b': 1}, 'one': {'a': 2.0, 'b': 0}}) diff --git a/pandas/tests/series/test_replace.py b/pandas/tests/series/test_replace.py index a3b92798879f5..d495fd9c83c24 100644 --- a/pandas/tests/series/test_replace.py +++ b/pandas/tests/series/test_replace.py @@ -130,6 +130,19 @@ def test_replace_with_single_list(self): s.replace([1, 2, 3], inplace=True, method='crash_cymbal') tm.assert_series_equal(s, ser) + def test_replace_with_empty_list(self): + # GH 21977 + s = pd.Series([[1], [2, 3], [], np.nan, [4]]) + expected = s + result = s.replace([], np.nan) + tm.assert_series_equal(result, expected) + + # GH 19266 + with tm.assert_raises_regex(ValueError, "cannot assign mismatch"): + s.replace({np.nan: []}) + with tm.assert_raises_regex(ValueError, "cannot assign mismatch"): + s.replace({np.nan: ['dummy', 'alt']}) + def test_replace_mixed_types(self): s = pd.Series(np.arange(5), dtype='int64')
- [x] closes #21977 - [x] closes #19266 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Internal mechanism in replace method is intertwined and can cause RecursionError (not very helpful). Discussed in #21977, there doesn't appear to be first class support for ExtensionArray yet and this issue is right now treated as error handling, having investigated treating it as new use case but not easily co-exist without large change. The RecursionError is caused by `Block.replace` and `ObjectBlock.replace` calling each other under certain circumstances such as in the linked issues. New approach is now to prevent re-casting of blocks to object blocks if it is already an ObjectBlock and instead raise the error caught as it is, because if it's an ObjectBlock already then ValueError and TypeError raised won't go away when re-casted to object and re-try, resulting in infinite loop and RecursionError.
https://api.github.com/repos/pandas-dev/pandas/pulls/22083
2018-07-27T14:01:38Z
2018-08-07T15:55:44Z
2018-08-07T15:55:44Z
2018-08-07T16:00:15Z
DOC: clarify default behavior for categories ordering
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 4584e4694cdc5..bf5b28205b57d 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -241,10 +241,14 @@ class Categorical(ExtensionArray, PandasObject): categories will be replaced with NaN. categories : Index-like (unique), optional The unique categories for this categorical. If not given, the - categories are assumed to be the unique values of values. + categories are assumed to be the unique values of `values` (sorted, if + possible, otherwise in the order in which they appear). ordered : boolean, (default False) Whether or not this categorical is treated as a ordered categorical. - If not given, the resulting categorical will not be ordered. + If True, the resulting categorical will be ordered. + An ordered categorical respects, when sorted, the order of its + `categories` attribute (which in turn is the `categories` argument, if + provided). dtype : CategoricalDtype An instance of ``CategoricalDtype`` to use for this categorical
- [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Just a doc clarification on default categories ordering, which can be pretty confusing when handling mixed dtypes (see also #22080 ).
https://api.github.com/repos/pandas-dev/pandas/pulls/22081
2018-07-27T10:40:11Z
2018-08-01T14:43:15Z
2018-08-01T14:43:15Z
2018-08-01T14:43:44Z
CLN/STYLE: Lint comprehensions
diff --git a/ci/environment-dev.yaml b/ci/environment-dev.yaml index 797506547b773..8d516a6214f95 100644 --- a/ci/environment-dev.yaml +++ b/ci/environment-dev.yaml @@ -6,6 +6,7 @@ dependencies: - Cython>=0.28.2 - NumPy - flake8 + - flake8-comprehensions - moto - pytest>=3.1 - python-dateutil>=2.5.0 diff --git a/ci/lint.sh b/ci/lint.sh index 9bcee55e1344c..9fc283c04f09e 100755 --- a/ci/lint.sh +++ b/ci/lint.sh @@ -10,42 +10,42 @@ if [ "$LINT" ]; then # pandas/_libs/src is C code, so no need to search there. echo "Linting *.py" - flake8 pandas --filename=*.py --exclude pandas/_libs/src + flake8 pandas --filename=*.py --exclude pandas/_libs/src --ignore=C405,C406,C408,C409,C410,E402,E731,E741,W503 if [ $? -ne "0" ]; then RET=1 fi echo "Linting *.py DONE" echo "Linting setup.py" - flake8 setup.py + flake8 setup.py --ignore=C405,C406,C408,C409,C410,E402,E731,E741,W503 if [ $? -ne "0" ]; then RET=1 fi echo "Linting setup.py DONE" echo "Linting asv_bench/benchmarks/" - flake8 asv_bench/benchmarks/ --exclude=asv_bench/benchmarks/*.py --ignore=F811 + flake8 asv_bench/benchmarks/ --exclude=asv_bench/benchmarks/*.py --ignore=F811,C405,C406,C408,C409,C410 if [ $? -ne "0" ]; then RET=1 fi echo "Linting asv_bench/benchmarks/*.py DONE" echo "Linting scripts/*.py" - flake8 scripts --filename=*.py + flake8 scripts --filename=*.py --ignore=C405,C406,C408,C409,C410,E402,E731,E741,W503 if [ $? -ne "0" ]; then RET=1 fi echo "Linting scripts/*.py DONE" echo "Linting doc scripts" - flake8 doc/make.py doc/source/conf.py + flake8 doc/make.py doc/source/conf.py --ignore=C405,C406,C408,C409,C410,E402,E731,E741,W503 if [ $? -ne "0" ]; then RET=1 fi echo "Linting doc scripts DONE" echo "Linting *.pyx" - flake8 pandas --filename=*.pyx --select=E501,E302,E203,E111,E114,E221,E303,E128,E231,E126,E265,E305,E301,E127,E261,E271,E129,W291,E222,E241,E123,F403 + flake8 pandas --filename=*.pyx --select=E501,E302,E203,E111,E114,E221,E303,E128,E231,E126,E265,E305,E301,E127,E261,E271,E129,W291,E222,E241,E123,F403,C400,C401,C402,C403,C404,C407,C411 if [ $? -ne "0" ]; then RET=1 fi @@ -131,19 +131,6 @@ if [ "$LINT" ]; then fi echo "Check for non-standard imports DONE" - echo "Check for use of lists instead of generators in built-in Python functions" - - # Example: Avoid `any([i for i in some_iterator])` in favor of `any(i for i in some_iterator)` - # - # Check the following functions: - # any(), all(), sum(), max(), min(), list(), dict(), set(), frozenset(), tuple(), str.join() - grep -R --include="*.py*" -E "[^_](any|all|sum|max|min|list|dict|set|frozenset|tuple|join)\(\[.* for .* in .*\]\)" pandas - - if [ $? = "0" ]; then - RET=1 - fi - echo "Check for use of lists instead of generators in built-in Python functions DONE" - echo "Check for incorrect sphinx directives" SPHINX_DIRECTIVES=$(echo \ "autosummary|contents|currentmodule|deprecated|function|image|"\ diff --git a/ci/travis-27.yaml b/ci/travis-27.yaml index 9cb20734dc63d..3e94f334174e6 100644 --- a/ci/travis-27.yaml +++ b/ci/travis-27.yaml @@ -9,6 +9,7 @@ dependencies: - fastparquet - feather-format - flake8=3.4.1 + - flake8-comprehensions - gcsfs - html5lib - ipython diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 5ecc79e030f56..b1fe8d7f09eb9 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -601,7 +601,7 @@ def _concat_same_type(cls, to_concat): ------- IntervalArray """ - closed = set(interval.closed for interval in to_concat) + closed = {interval.closed for interval in to_concat} if len(closed) != 1: raise ValueError("Intervals must all be closed on the same side.") closed = closed.pop() diff --git a/pandas/core/common.py b/pandas/core/common.py index 0350b338f2bee..a3fba762509f1 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -307,8 +307,7 @@ def dict_compat(d): dict """ - return dict((maybe_box_datetimelike(key), value) - for key, value in iteritems(d)) + return {maybe_box_datetimelike(key): value for key, value in iteritems(d)} def standardize_mapping(into): diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 355bf58540219..905073645fcb3 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -21,9 +21,9 @@ is_named_tuple, is_array_like, is_decimal, is_complex, is_interval) -_POSSIBLY_CAST_DTYPES = set([np.dtype(t).name - for t in ['O', 'int8', 'uint8', 'int16', 'uint16', - 'int32', 'uint32', 'int64', 'uint64']]) +_POSSIBLY_CAST_DTYPES = {np.dtype(t).name + for t in ['O', 'int8', 'uint8', 'int16', 'uint16', + 'int32', 'uint32', 'int64', 'uint64']} _NS_DTYPE = conversion.NS_DTYPE _TD_DTYPE = conversion.TD_DTYPE diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 376700f1418f6..4d4c51c636638 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8833,7 +8833,7 @@ def describe_1d(data): ldesc = [describe_1d(s) for _, s in data.iteritems()] # set a convenient order for rows names = [] - ldesc_indexes = sorted([x.index for x in ldesc], key=len) + ldesc_indexes = sorted((x.index for x in ldesc), key=len) for idxnames in ldesc_indexes: for name in idxnames: if name not in names: diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index b2c5a8cff9c1b..96c74f7fd4d75 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -43,8 +43,7 @@ def _gotitem(self, key, ndim, subset=None): # we need to make a shallow copy of ourselves # with the same groupby - kwargs = dict([(attr, getattr(self, attr)) - for attr in self._attributes]) + kwargs = {attr: getattr(self, attr) for attr in self._attributes} self = self.__class__(subset, groupby=self._groupby[key], parent=self, diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 3f3448d104165..e50a4b099a8e1 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -147,8 +147,8 @@ def _get_consensus_names(indexes): # find the non-none names, need to tupleify to make # the set hashable, then reverse on return - consensus_names = set(tuple(i.names) for i in indexes - if com._any_not_none(*i.names)) + consensus_names = {tuple(i.names) for i in indexes + if com._any_not_none(*i.names)} if len(consensus_names) == 1: return list(list(consensus_names)[0]) return [None] * indexes[0].nlevels diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 4912014b43773..2a97c37449e12 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -903,8 +903,8 @@ def f(k, stringify): if stringify and not isinstance(k, compat.string_types): k = str(k) return k - key = tuple([f(k, stringify) - for k, stringify in zip(key, self._have_mixed_levels)]) + key = tuple(f(k, stringify) + for k, stringify in zip(key, self._have_mixed_levels)) return hash_tuple(key) @Appender(Index.duplicated.__doc__) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 4eeeb069d7142..5a3f11525acf8 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -378,7 +378,7 @@ def is_uniform_reindex(join_units): return ( # TODO: should this be ju.block._can_hold_na? all(ju.block and ju.block.is_extension for ju in join_units) and - len(set(ju.block.dtype.name for ju in join_units)) == 1 + len({ju.block.dtype.name for ju in join_units}) == 1 ) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index e7b7cb463a27b..32e8372d5c6c9 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -398,10 +398,10 @@ def apply(self, f, axes=None, filter=None, do_integrity_check=False, # TODO(EA): may interfere with ExtensionBlock.setitem for blocks # with a .values attribute. - aligned_args = dict((k, kwargs[k]) - for k in align_keys - if hasattr(kwargs[k], 'values') and - not isinstance(kwargs[k], ABCExtensionArray)) + aligned_args = {k: kwargs[k] + for k in align_keys + if hasattr(kwargs[k], 'values') and + not isinstance(kwargs[k], ABCExtensionArray)} for b in self.blocks: if filter is not None: diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 4ebac55eea137..38b84ab685c3b 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -1429,10 +1429,8 @@ def _extract_axes(self, data, axes, **kwargs): @staticmethod def _extract_axes_for_slice(self, axes): """ return the slice dictionary for these axes """ - return dict((self._AXIS_SLICEMAP[i], a) - for i, a in zip( - self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], - axes)) + return {self._AXIS_SLICEMAP[i]: a for i, a in + zip(self._AXIS_ORDERS[self._AXIS_LEN - len(axes):], axes)} @staticmethod def _prep_ndarray(self, values, copy=True): @@ -1480,11 +1478,10 @@ def _homogenize_dict(self, frames, intersect=True, dtype=None): adj_frames[k] = v axes = self._AXIS_ORDERS[1:] - axes_dict = dict((a, ax) for a, ax in zip(axes, self._extract_axes( - self, adj_frames, axes, intersect=intersect))) + axes_dict = {a: ax for a, ax in zip(axes, self._extract_axes( + self, adj_frames, axes, intersect=intersect))} - reindex_dict = dict( - [(self._AXIS_SLICEMAP[a], axes_dict[a]) for a in axes]) + reindex_dict = {self._AXIS_SLICEMAP[a]: axes_dict[a] for a in axes} reindex_dict['copy'] = False for key, frame in compat.iteritems(adj_frames): if frame is not None: diff --git a/pandas/io/json/normalize.py b/pandas/io/json/normalize.py index 2004a24c2ec5a..03f0905d2023a 100644 --- a/pandas/io/json/normalize.py +++ b/pandas/io/json/normalize.py @@ -194,8 +194,8 @@ def _pull_field(js, spec): data = [data] if record_path is None: - if any([[isinstance(x, dict) - for x in compat.itervalues(y)] for y in data]): + if any([isinstance(x, dict) + for x in compat.itervalues(y)] for y in data): # naive normalization, this is idempotent for flat records # and potentially will inflate the data considerably for # deeply nested structures: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 2ae7622c13548..88358ff392cb6 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -3147,8 +3147,7 @@ def _clean_na_values(na_values, keep_default_na=True): v = set(v) | _NA_VALUES na_values[k] = v - na_fvalues = dict((k, _floatify_na_values(v)) - for k, v in na_values.items()) + na_fvalues = {k: _floatify_na_values(v) for k, v in na_values.items()} else: if not is_list_like(na_values): na_values = [na_values] diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index ddee4894456ea..2aa875d1e095a 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -15,7 +15,7 @@ def check(self, namespace, expected, ignored=None): # ignored ones # compare vs the expected - result = sorted([f for f in dir(namespace) if not f.startswith('_')]) + result = sorted(f for f in dir(namespace) if not f.startswith('_')) if ignored is not None: result = sorted(list(set(result) - set(ignored))) diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 34c397252a8bb..980c245d55711 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -160,7 +160,7 @@ def unique(self): # Parent method doesn't work since np.array will try to infer # a 2-dim object. return type(self)([ - dict(x) for x in list(set(tuple(d.items()) for d in self.data)) + dict(x) for x in list({tuple(d.items()) for d in self.data}) ]) @classmethod @@ -176,5 +176,5 @@ def _values_for_argsort(self): # Disable NumPy's shape inference by including an empty tuple... # If all the elemnts of self are the same size P, NumPy will # cast them to an (N, P) array, instead of an (N,) array of tuples. - frozen = [()] + list(tuple(x.items()) for x in self) + frozen = [()] + [tuple(x.items()) for x in self] return np.array(frozen, dtype=object)[1:] diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index e038588b76ffd..344838493f0b1 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -319,14 +319,14 @@ def test_apply_differently_indexed(self): df = DataFrame(np.random.randn(20, 10)) result0 = df.apply(Series.describe, axis=0) - expected0 = DataFrame(dict((i, v.describe()) - for i, v in compat.iteritems(df)), + expected0 = DataFrame({i: v.describe() + for i, v in compat.iteritems(df)}, columns=df.columns) assert_frame_equal(result0, expected0) result1 = df.apply(Series.describe, axis=1) - expected1 = DataFrame(dict((i, v.describe()) - for i, v in compat.iteritems(df.T)), + expected1 = DataFrame({i: v.describe() + for i, v in compat.iteritems(df.T)}, columns=df.index).T assert_frame_equal(result1, expected1) diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 30a670ead3aa0..3b3ab3d03dce9 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -397,8 +397,8 @@ def test_select_dtypes_typecodes(self): def test_dtypes_gh8722(self): self.mixed_frame['bool'] = self.mixed_frame['A'] > 0 result = self.mixed_frame.dtypes - expected = Series(dict((k, v.dtype) - for k, v in compat.iteritems(self.mixed_frame)), + expected = Series({k: v.dtype + for k, v in compat.iteritems(self.mixed_frame)}, index=result.index) assert_series_equal(result, expected) @@ -439,8 +439,8 @@ def test_astype(self): # mixed casting def _check_cast(df, v): - assert (list(set(s.dtype.name for - _, s in compat.iteritems(df)))[0] == v) + assert (list({s.dtype.name for + _, s in compat.iteritems(df)})[0] == v) mn = self.all_mixed._get_numeric_data().copy() mn['little_float'] = np.array(12345., dtype='float16') diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 3e5c13208f164..5f229aca5c25b 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -276,8 +276,8 @@ def test_getitem_boolean(self): data = df._get_numeric_data() bif = df[df > 0] - bifw = DataFrame(dict((c, np.where(data[c] > 0, data[c], np.nan)) - for c in data.columns), + bifw = DataFrame({c: np.where(data[c] > 0, data[c], np.nan) + for c in data.columns}, index=data.index, columns=data.columns) # add back other columns to compare @@ -2506,9 +2506,9 @@ def _check_get(df, cond, check_dtypes=True): _check_get(df, cond) # upcasting case (GH # 2794) - df = DataFrame(dict((c, Series([1] * 3, dtype=c)) - for c in ['float32', 'float64', - 'int32', 'int64'])) + df = DataFrame({c: Series([1] * 3, dtype=c) + for c in ['float32', 'float64', + 'int32', 'int64']}) df.iloc[1, :] = 0 result = df.where(df >= 0).get_dtype_counts() diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 8b2b74802556d..9affd0241d028 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -519,8 +519,8 @@ def test_groupby_multiple_columns(df, op): for n1, gp1 in data.groupby('A'): for n2, gp2 in gp1.groupby('B'): expected[n1][n2] = op(gp2.loc[:, ['C', 'D']]) - expected = dict((k, DataFrame(v)) - for k, v in compat.iteritems(expected)) + expected = {k: DataFrame(v) + for k, v in compat.iteritems(expected)} expected = Panel.fromDict(expected).swapaxes(0, 1) expected.major_axis.name, expected.minor_axis.name = 'A', 'B' diff --git a/pandas/tests/indexes/multi/test_copy.py b/pandas/tests/indexes/multi/test_copy.py index f6c5c0c5eb346..786b90e8f13a2 100644 --- a/pandas/tests/indexes/multi/test_copy.py +++ b/pandas/tests/indexes/multi/test_copy.py @@ -83,4 +83,4 @@ def test_copy_method_kwargs(deep, kwarg, value): if kwarg == 'names': assert getattr(idx_copy, kwarg) == value else: - assert list(list(i) for i in getattr(idx_copy, kwarg)) == value + assert [list(i) for i in getattr(idx_copy, kwarg)] == value diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 293dadd19031d..bcfd3cbb739ff 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -250,11 +250,11 @@ def test_apply_subset(self): for slice_ in slices: result = self.df.style.apply(self.h, axis=ax, subset=slice_, foo='baz')._compute().ctx - expected = dict(((r, c), ['color: baz']) - for r, row in enumerate(self.df.index) - for c, col in enumerate(self.df.columns) - if row in self.df.loc[slice_].index and - col in self.df.loc[slice_].columns) + expected = {(r, c): ['color: baz'] + for r, row in enumerate(self.df.index) + for c, col in enumerate(self.df.columns) + if row in self.df.loc[slice_].index and + col in self.df.loc[slice_].columns} assert result == expected def test_applymap_subset(self): @@ -267,11 +267,11 @@ def f(x): for slice_ in slices: result = self.df.style.applymap(f, subset=slice_)._compute().ctx - expected = dict(((r, c), ['foo: bar']) - for r, row in enumerate(self.df.index) - for c, col in enumerate(self.df.columns) - if row in self.df.loc[slice_].index and - col in self.df.loc[slice_].columns) + expected = {(r, c): ['foo: bar'] + for r, row in enumerate(self.df.index) + for c, col in enumerate(self.df.columns) + if row in self.df.loc[slice_].index and + col in self.df.loc[slice_].columns} assert result == expected def test_where_with_one_style(self): @@ -282,10 +282,9 @@ def f(x): style1 = 'foo: bar' result = self.df.style.where(f, style1)._compute().ctx - expected = dict(((r, c), - [style1 if f(self.df.loc[row, col]) else '']) - for r, row in enumerate(self.df.index) - for c, col in enumerate(self.df.columns)) + expected = {(r, c): [style1 if f(self.df.loc[row, col]) else ''] + for r, row in enumerate(self.df.index) + for c, col in enumerate(self.df.columns)} assert result == expected def test_where_subset(self): @@ -303,12 +302,12 @@ def f(x): for slice_ in slices: result = self.df.style.where(f, style1, style2, subset=slice_)._compute().ctx - expected = dict(((r, c), - [style1 if f(self.df.loc[row, col]) else style2]) - for r, row in enumerate(self.df.index) - for c, col in enumerate(self.df.columns) - if row in self.df.loc[slice_].index and - col in self.df.loc[slice_].columns) + expected = {(r, c): + [style1 if f(self.df.loc[row, col]) else style2] + for r, row in enumerate(self.df.index) + for c, col in enumerate(self.df.columns) + if row in self.df.loc[slice_].index and + col in self.df.loc[slice_].columns} assert result == expected def test_where_subset_compare_with_applymap(self): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index bcbac4400c953..fd6eba81f5913 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -21,8 +21,8 @@ _frame = DataFrame(_seriesd) _frame2 = DataFrame(_seriesd, columns=['D', 'C', 'B', 'A']) -_intframe = DataFrame(dict((k, v.astype(np.int64)) - for k, v in compat.iteritems(_seriesd))) +_intframe = DataFrame({k: v.astype(np.int64) + for k, v in compat.iteritems(_seriesd)}) _tsframe = DataFrame(_tsd) _cat_frame = _frame.copy() diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index e2243b8087a5b..f6a31008bca5c 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -197,4 +197,4 @@ def test_read_csv_chunked_download(self, s3_resource, caplog): with caplog.at_level(logging.DEBUG, logger='s3fs.core'): read_csv("s3://pandas-test/large-file.csv", nrows=5) # log of fetch_range (start, stop) - assert ((0, 5505024) in set(x.args[-2:] for x in caplog.records)) + assert ((0, 5505024) in {x.args[-2:] for x in caplog.records}) diff --git a/pandas/tests/io/test_pytables.py b/pandas/tests/io/test_pytables.py index 9b624ab78a406..db8306d6dcb77 100644 --- a/pandas/tests/io/test_pytables.py +++ b/pandas/tests/io/test_pytables.py @@ -2104,9 +2104,9 @@ def test_table_values_dtypes_roundtrip(self): assert df1.dtypes[0] == 'float32' # check with mixed dtypes - df1 = DataFrame(dict((c, Series(np.random.randint(5), dtype=c)) - for c in ['float32', 'float64', 'int32', - 'int64', 'int16', 'int8'])) + df1 = DataFrame({c: Series(np.random.randint(5), dtype=c) + for c in ['float32', 'float64', 'int32', + 'int64', 'int16', 'int8']}) df1['string'] = 'foo' df1['float322'] = 1. df1['float322'] = df1['float322'].astype('float32') diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index f1ea847e76091..db10ea15f6e9c 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1126,10 +1126,10 @@ def test_if_hexbin_xaxis_label_is_visible(self): 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 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 diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index d05fd689ed754..a59836eb70d24 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1542,14 +1542,13 @@ def df(): return DataFrame(np.random.randn(index, cols), index=["I%s" % i for i in range(index)], columns=["C%s" % i for i in range(cols)]) - return Panel(dict(("Item%s" % x, df()) - for x in ['A', 'B', 'C'])) + return Panel({"Item%s" % x: df() for x in ['A', 'B', 'C']}) panel1 = make_panel() panel2 = make_panel() - panel2 = panel2.rename_axis(dict((x, "%s_1" % x) - for x in panel2.major_axis), + panel2 = panel2.rename_axis({x: "%s_1" % x + for x in panel2.major_axis}, axis=1) panel3 = panel2.rename_axis(lambda x: '%s_1' % x, axis=1) diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 14966177978f4..397da2fa40cd8 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -2521,8 +2521,8 @@ def test_flex_binary_frame(self, method): 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)) + exp = DataFrame({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): diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index dd4356aac1cd5..60981f41ec716 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -2375,7 +2375,7 @@ def generate_range(start=None, end=None, periods=None, cur = next_date -prefix_mapping = dict((offset._prefix, offset) for offset in [ +prefix_mapping = {offset._prefix: offset for offset in [ YearBegin, # 'AS' YearEnd, # 'A' BYearBegin, # 'BAS' @@ -2407,4 +2407,4 @@ def generate_range(start=None, end=None, periods=None, WeekOfMonth, # 'WOM' FY5253, FY5253Quarter, -]) +]} diff --git a/scripts/find_commits_touching_func.py b/scripts/find_commits_touching_func.py index 29eb4161718ff..8f0c554b8aa9d 100755 --- a/scripts/find_commits_touching_func.py +++ b/scripts/find_commits_touching_func.py @@ -91,7 +91,7 @@ def get_hits(defname, files=()): # remove comment lines lines = [x for x in lines if not re.search("^\w+\s*\(.+\)\s*#", x)] hits = set(map(lambda x: x.split(" ")[0], lines)) - cs.update(set(Hit(commit=c, path=f) for c in hits)) + cs.update({Hit(commit=c, path=f) for c in hits}) return cs
- [x] closes #18464 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Using flake8-comprehensions (xref https://github.com/pandas-dev/pandas/issues/20588#issuecomment-405057018) to lint for unnecessary comprehensions. I just added this to the 2.7-travis build since it appears to be our linting build.
https://api.github.com/repos/pandas-dev/pandas/pulls/22075
2018-07-27T05:24:09Z
2018-07-29T15:33:43Z
2018-07-29T15:33:43Z
2018-07-29T18:17:16Z
[Bug] Fix various DatetimeIndex comparison bugs
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index d2d5d40393b62..643ecfe70d433 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -496,6 +496,9 @@ Datetimelike - Fixed bug where two :class:`DateOffset` objects with different ``normalize`` attributes could evaluate as equal (:issue:`21404`) - Fixed bug where :meth:`Timestamp.resolution` incorrectly returned 1-microsecond ``timedelta`` instead of 1-nanosecond :class:`Timedelta` (:issue:`21336`,:issue:`21365`) - Bug in :func:`to_datetime` that did not consistently return an :class:`Index` when ``box=True`` was specified (:issue:`21864`) +- Bug in :class:`DatetimeIndex` comparisons where string comparisons incorrectly raises ``TypeError`` (:issue:`22074`) +- Bug in :class:`DatetimeIndex` comparisons when comparing against ``timedelta64[ns]`` dtyped arrays; in some cases ``TypeError`` was incorrectly raised, in others it incorrectly failed to raise (:issue:`22074`) +- Bug in :class:`DatetimeIndex` comparisons when comparing against object-dtyped arrays (:issue:`22074`) Timedelta ^^^^^^^^^ @@ -518,6 +521,7 @@ Timezones - Bug in :class:`Index` with ``datetime64[ns, tz]`` dtype that did not localize integer data correctly (:issue:`20964`) - Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`) - Fixed bug where :meth:`DataFrame.describe` and :meth:`Series.describe` on tz-aware datetimes did not show `first` and `last` result (:issue:`21328`) +- Bug in :class:`DatetimeIndex` comparisons failing to raise ``TypeError`` when comparing timezone-aware ``DatetimeIndex`` against ``np.datetime64`` (:issue:`22074`) Offsets ^^^^^^^ @@ -535,6 +539,7 @@ Numeric - Bug in :meth:`DataFrame.agg`, :meth:`DataFrame.transform` and :meth:`DataFrame.apply` where, when supplied with a list of functions and ``axis=1`` (e.g. ``df.apply(['sum', 'mean'], axis=1)``), a ``TypeError`` was wrongly raised. For all three methods such calculation are now done correctly. (:issue:`16679`). +- Bug in :class:`Series` comparison against datetime-like scalars and arrays (:issue:`22074`) - Strings diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 00d53ad82b2dc..31ffde0ea12d7 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -5,7 +5,7 @@ import numpy as np from pytz import utc -from pandas._libs import tslib +from pandas._libs import lib, tslib from pandas._libs.tslib import Timestamp, NaT, iNaT from pandas._libs.tslibs import ( normalize_date, @@ -18,7 +18,7 @@ from pandas.core.dtypes.common import ( _NS_DTYPE, - is_datetimelike, + is_object_dtype, is_datetime64tz_dtype, is_datetime64_dtype, is_timedelta64_dtype, @@ -29,6 +29,7 @@ import pandas.core.common as com from pandas.core.algorithms import checked_add_with_arr +from pandas.core import ops from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import Tick, Day, generate_range @@ -99,31 +100,40 @@ def wrapper(self, other): meth = getattr(dtl.DatetimeLikeArrayMixin, opname) if isinstance(other, (datetime, np.datetime64, compat.string_types)): - if isinstance(other, datetime): + if isinstance(other, (datetime, np.datetime64)): # GH#18435 strings get a pass from tzawareness compat self._assert_tzawareness_compat(other) - other = _to_m8(other, tz=self.tz) + try: + other = _to_m8(other, tz=self.tz) + except ValueError: + # string that cannot be parsed to Timestamp + return ops.invalid_comparison(self, other, op) + result = meth(self, other) if isna(other): result.fill(nat_result) + elif lib.is_scalar(other): + return ops.invalid_comparison(self, other, op) else: if isinstance(other, list): + # FIXME: This can break for object-dtype with mixed types other = type(self)(other) elif not isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)): # Following Timestamp convention, __eq__ is all-False # and __ne__ is all True, others raise TypeError. - if opname == '__eq__': - return np.zeros(shape=self.shape, dtype=bool) - elif opname == '__ne__': - return np.ones(shape=self.shape, dtype=bool) - raise TypeError('%s type object %s' % - (type(other), str(other))) - - if is_datetimelike(other): + return ops.invalid_comparison(self, other, op) + + if is_object_dtype(other): + result = op(self.astype('O'), np.array(other)) + elif not (is_datetime64_dtype(other) or + is_datetime64tz_dtype(other)): + # e.g. is_timedelta64_dtype(other) + return ops.invalid_comparison(self, other, op) + else: self._assert_tzawareness_compat(other) + result = meth(self, np.asarray(other)) - result = meth(self, np.asarray(other)) result = com.values_from_object(result) # Make sure to pass an array to result[...]; indexing with @@ -152,6 +162,10 @@ class DatetimeArrayMixin(dtl.DatetimeLikeArrayMixin): 'is_year_end', 'is_leap_year'] _object_ops = ['weekday_name', 'freq', 'tz'] + # dummy attribute so that datetime.__eq__(DatetimeArray) defers + # by returning NotImplemented + timetuple = None + # ----------------------------------------------------------------- # Constructors diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 6d407c41daea6..f7d863bba82a7 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -788,6 +788,35 @@ def mask_cmp_op(x, y, op, allowed_types): return result +def invalid_comparison(left, right, op): + """ + If a comparison has mismatched types and is not necessarily meaningful, + follow python3 conventions by: + + - returning all-False for equality + - returning all-True for inequality + - raising TypeError otherwise + + Parameters + ---------- + left : array-like + right : scalar, array-like + op : operator.{eq, ne, lt, le, gt} + + Raises + ------ + TypeError : on inequality comparisons + """ + if op is operator.eq: + res_values = np.zeros(left.shape, dtype=bool) + elif op is operator.ne: + res_values = np.ones(left.shape, dtype=bool) + else: + raise TypeError("Invalid comparison between dtype={dtype} and {typ}" + .format(dtype=left.dtype, typ=type(right).__name__)) + return res_values + + # ----------------------------------------------------------------------------- # Functions that add arithmetic methods to objects, given arithmetic factory # methods @@ -1259,7 +1288,7 @@ def na_op(x, y): result = _comp_method_OBJECT_ARRAY(op, x, y) elif is_datetimelike_v_numeric(x, y): - raise TypeError("invalid type comparison") + return invalid_comparison(x, y, op) else: diff --git a/pandas/tests/frame/test_operators.py b/pandas/tests/frame/test_operators.py index fdf50805ad818..b6b783134b424 100644 --- a/pandas/tests/frame/test_operators.py +++ b/pandas/tests/frame/test_operators.py @@ -157,8 +157,20 @@ def test_comparison_invalid(self): def check(df, df2): for (x, y) in [(df, df2), (df2, df)]: - pytest.raises(TypeError, lambda: x == y) - pytest.raises(TypeError, lambda: x != y) + # we expect the result to match Series comparisons for + # == and !=, inequalities should raise + result = x == y + expected = DataFrame({col: x[col] == y[col] + for col in x.columns}, + index=x.index, columns=x.columns) + assert_frame_equal(result, expected) + + result = x != y + expected = DataFrame({col: x[col] != y[col] + for col in x.columns}, + index=x.index, columns=x.columns) + assert_frame_equal(result, expected) + pytest.raises(TypeError, lambda: x >= y) pytest.raises(TypeError, lambda: x > y) pytest.raises(TypeError, lambda: x < y) diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index a226f8de3c8bd..92035850806cb 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -463,9 +463,13 @@ def test_date_query_with_non_date(self): df = DataFrame({'dates': date_range('1/1/2012', periods=n), 'nondate': np.arange(n)}) - ops = '==', '!=', '<', '>', '<=', '>=' + result = df.query('dates == nondate', parser=parser, engine=engine) + assert len(result) == 0 - for op in ops: + result = df.query('dates != nondate', parser=parser, engine=engine) + assert_frame_equal(result, df) + + for op in ['<', '>', '<=', '>=']: with pytest.raises(TypeError): df.query('dates %s nondate' % op, parser=parser, engine=engine) diff --git a/pandas/tests/indexes/datetimes/test_arithmetic.py b/pandas/tests/indexes/datetimes/test_arithmetic.py index 1e54e6563d598..f54cb32b0a036 100644 --- a/pandas/tests/indexes/datetimes/test_arithmetic.py +++ b/pandas/tests/indexes/datetimes/test_arithmetic.py @@ -275,6 +275,20 @@ def test_comparison_tzawareness_compat(self, op): with pytest.raises(TypeError): op(ts, dz) + @pytest.mark.parametrize('op', [operator.eq, operator.ne, + operator.gt, operator.ge, + operator.lt, operator.le]) + @pytest.mark.parametrize('other', [datetime(2016, 1, 1), + Timestamp('2016-01-01'), + np.datetime64('2016-01-01')]) + def test_scalar_comparison_tzawareness(self, op, other, tz_aware_fixture): + tz = tz_aware_fixture + dti = pd.date_range('2016-01-01', periods=2, tz=tz) + with pytest.raises(TypeError): + op(dti, other) + with pytest.raises(TypeError): + op(other, dti) + @pytest.mark.parametrize('op', [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le]) @@ -290,12 +304,60 @@ def test_nat_comparison_tzawareness(self, op): result = op(dti.tz_localize('US/Pacific'), pd.NaT) tm.assert_numpy_array_equal(result, expected) - def test_dti_cmp_int_raises(self): - rng = date_range('1/1/2000', periods=10) + def test_dti_cmp_str(self, tz_naive_fixture): + # GH#22074 + # regardless of tz, we expect these comparisons are valid + tz = tz_naive_fixture + rng = date_range('1/1/2000', periods=10, tz=tz) + other = '1/1/2000' + + result = rng == other + expected = np.array([True] + [False] * 9) + tm.assert_numpy_array_equal(result, expected) + + result = rng != other + expected = np.array([False] + [True] * 9) + tm.assert_numpy_array_equal(result, expected) + + result = rng < other + expected = np.array([False] * 10) + tm.assert_numpy_array_equal(result, expected) + + result = rng <= other + expected = np.array([True] + [False] * 9) + tm.assert_numpy_array_equal(result, expected) + + result = rng > other + expected = np.array([False] + [True] * 9) + tm.assert_numpy_array_equal(result, expected) + + result = rng >= other + expected = np.array([True] * 10) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('other', ['foo', 99, 4.0, + object(), timedelta(days=2)]) + def test_dti_cmp_scalar_invalid(self, other, tz_naive_fixture): + # GH#22074 + tz = tz_naive_fixture + rng = date_range('1/1/2000', periods=10, tz=tz) + + result = rng == other + expected = np.array([False] * 10) + tm.assert_numpy_array_equal(result, expected) + + result = rng != other + expected = np.array([True] * 10) + tm.assert_numpy_array_equal(result, expected) - # raise TypeError for now with pytest.raises(TypeError): - rng < rng[3].value + rng < other + with pytest.raises(TypeError): + rng <= other + with pytest.raises(TypeError): + rng > other + with pytest.raises(TypeError): + rng >= other def test_dti_cmp_list(self): rng = date_range('1/1/2000', periods=10) @@ -304,6 +366,57 @@ def test_dti_cmp_list(self): expected = rng == rng tm.assert_numpy_array_equal(result, expected) + @pytest.mark.parametrize('other', [ + pd.timedelta_range('1D', periods=10), + pd.timedelta_range('1D', periods=10).to_series(), + pd.timedelta_range('1D', periods=10).asi8.view('m8[ns]') + ], ids=lambda x: type(x).__name__) + def test_dti_cmp_tdi_tzawareness(self, other): + # GH#22074 + # reversion test that we _don't_ call _assert_tzawareness_compat + # when comparing against TimedeltaIndex + dti = date_range('2000-01-01', periods=10, tz='Asia/Tokyo') + + result = dti == other + expected = np.array([False] * 10) + tm.assert_numpy_array_equal(result, expected) + + result = dti != other + expected = np.array([True] * 10) + tm.assert_numpy_array_equal(result, expected) + + with pytest.raises(TypeError): + dti < other + with pytest.raises(TypeError): + dti <= other + with pytest.raises(TypeError): + dti > other + with pytest.raises(TypeError): + dti >= other + + def test_dti_cmp_object_dtype(self): + # GH#22074 + dti = date_range('2000-01-01', periods=10, tz='Asia/Tokyo') + + other = dti.astype('O') + + result = dti == other + expected = np.array([True] * 10) + tm.assert_numpy_array_equal(result, expected) + + other = dti.tz_localize(None) + with pytest.raises(TypeError): + # tzawareness failure + dti != other + + other = np.array(list(dti[:5]) + [Timedelta(days=1)] * 5) + result = dti == other + expected = np.array([True] * 5 + [False] * 5) + tm.assert_numpy_array_equal(result, expected) + + with pytest.raises(TypeError): + dti >= other + class TestDatetimeIndexArithmetic(object): diff --git a/pandas/tests/series/test_operators.py b/pandas/tests/series/test_operators.py index ecb74622edf10..fb6e7c412d884 100644 --- a/pandas/tests/series/test_operators.py +++ b/pandas/tests/series/test_operators.py @@ -238,8 +238,15 @@ def test_comparison_invalid(self): s2 = Series(date_range('20010101', periods=5)) for (x, y) in [(s, s2), (s2, s)]: - pytest.raises(TypeError, lambda: x == y) - pytest.raises(TypeError, lambda: x != y) + + result = x == y + expected = Series([False] * 5) + assert_series_equal(result, expected) + + result = x != y + expected = Series([True] * 5) + assert_series_equal(result, expected) + pytest.raises(TypeError, lambda: x >= y) pytest.raises(TypeError, lambda: x > y) pytest.raises(TypeError, lambda: x < y)
Will have to see which issues this closes. This is also a precursor to upcoming PR that dispatches DataFrame ops to Series (which in turn dispatches to Index). Fixes #7830 (the OP's example is already fixed, this fixes examples in the comments to that issue) Fixes DTI half of #19804 - [x] closes #7830 - [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/22074
2018-07-27T03:17:30Z
2018-08-01T09:19:44Z
2018-08-01T09:19:44Z
2018-08-08T15:52:15Z
fix for TypeError: unorderable types" in when using set_index with multiple column names
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index f26d3d76592d0..2ddfba6d01a1b 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -626,7 +626,7 @@ MultiIndex - Removed compatibility for :class:`MultiIndex` pickles prior to version 0.8.0; compatibility with :class:`MultiIndex` pickles from version 0.13 forward is maintained (:issue:`21654`) - :meth:`MultiIndex.get_loc_level` (and as a consequence, ``.loc`` on a :class:``MultiIndex``ed object) will now raise a ``KeyError``, rather than returning an empty ``slice``, if asked a label which is present in the ``levels`` but is unused (:issue:`22221`) -- +- Fix ``TypeError`` in Python 3 when creating :class:`MultiIndex` in which some levels have mixed types, e.g. when some labels are tuples (:issue:`15457`) I/O ^^^ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 003ba7608dea4..c4144d2e8b086 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2538,7 +2538,10 @@ def _factorize_from_iterable(values): ordered=values.ordered) codes = values.codes else: - cat = Categorical(values, ordered=True) + # The value of ordered is irrelevant since we don't use cat as such, + # but only the resulting categories, the order of which is independent + # from ordered. Set ordered to False as default. See GH #15457 + cat = Categorical(values, ordered=False) categories = cat.categories codes = cat.codes return codes, categories diff --git a/pandas/tests/indexes/multi/test_constructor.py b/pandas/tests/indexes/multi/test_constructor.py index 4b8d0553886b2..ab2e4c1d863a7 100644 --- a/pandas/tests/indexes/multi/test_constructor.py +++ b/pandas/tests/indexes/multi/test_constructor.py @@ -463,3 +463,12 @@ def test_tuples_with_name_string(): pd.Index(li, name='abc') with pytest.raises(ValueError): pd.Index(li, name='a') + + +def test_from_tuples_with_tuple_label(): + # GH 15457 + expected = pd.DataFrame([[2, 1, 2], [4, (1, 2), 3]], + columns=['a', 'b', 'c']).set_index(['a', 'b']) + idx = pd.MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=('a', 'b')) + result = pd.DataFrame([2, 3], columns=['c'], index=idx) + tm.assert_frame_equal(expected, result)
- closes #15457
https://api.github.com/repos/pandas-dev/pandas/pulls/22072
2018-07-27T00:50:45Z
2018-08-12T08:16:21Z
2018-08-12T08:16:21Z
2018-08-12T08:35:26Z
Remove unused, avoid uses of deprecated api
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index ecfc7355dddfc..124792638e3df 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -129,7 +129,7 @@ def is_lexsorted(list list_of_arrays): for i in range(nlevels): arr = list_of_arrays[i] assert arr.dtype.name == 'int64' - vecs[i] = <int64_t*> arr.data + vecs[i] = <int64_t*> cnp.PyArray_DATA(arr) # Assume uniqueness?? with nogil: diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 5e4a431caca00..5681d01c6bb25 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -7,10 +7,12 @@ from cython cimport Py_ssize_t from libc.stdlib cimport malloc, free import numpy as np +cimport numpy as cnp from numpy cimport (ndarray, double_t, int8_t, int16_t, int32_t, int64_t, uint8_t, uint16_t, uint32_t, uint64_t, float32_t, float64_t) +cnp.import_array() from util cimport numeric, get_nat @@ -118,7 +120,7 @@ def group_median_float64(ndarray[float64_t, ndim=2] out, counts[:] = _counts[1:] data = np.empty((K, N), dtype=np.float64) - ptr = <float64_t*> data.data + ptr = <float64_t*> cnp.PyArray_DATA(data) take_2d_axis1_float64_float64(values.T, indexer, out=data) diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 31ef4b7a3e807..5918560cf1436 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -37,7 +37,7 @@ cdef inline bint is_definitely_invalid_key(object val): return True # we have a _data, means we are a NDFrame - return (PySlice_Check(val) or cnp.PyArray_Check(val) + return (PySlice_Check(val) or util.is_array(val) or PyList_Check(val) or hasattr(val, '_data')) @@ -104,7 +104,7 @@ cdef class IndexEngine: void* data_ptr loc = self.get_loc(key) - if PySlice_Check(loc) or cnp.PyArray_Check(loc): + if PySlice_Check(loc) or util.is_array(loc): return arr[loc] else: return get_value_at(arr, loc, tz=tz) @@ -120,7 +120,7 @@ cdef class IndexEngine: loc = self.get_loc(key) value = convert_scalar(arr, value) - if PySlice_Check(loc) or cnp.PyArray_Check(loc): + if PySlice_Check(loc) or util.is_array(loc): arr[loc] = value else: util.set_value_at(arr, loc, value) diff --git a/pandas/_libs/src/numpy_helper.h b/pandas/_libs/src/numpy_helper.h index 98eca92fd1ab2..753cba6ce62aa 100644 --- a/pandas/_libs/src/numpy_helper.h +++ b/pandas/_libs/src/numpy_helper.h @@ -16,8 +16,6 @@ The full license is in the LICENSE file, distributed with this software. #include "numpy/arrayscalars.h" -PANDAS_INLINE npy_int64 get_nat(void) { return NPY_MIN_INT64; } - PANDAS_INLINE int assign_value_1d(PyArrayObject* ap, Py_ssize_t _i, PyObject* v) { npy_intp i = (npy_intp)_i; @@ -40,16 +38,10 @@ PANDAS_INLINE const char* get_c_string(PyObject* obj) { #endif } -PANDAS_INLINE PyObject* char_to_string(const char* data) { -#if PY_VERSION_HEX >= 0x03000000 - return PyUnicode_FromString(data); -#else - return PyString_FromString(data); -#endif -} - void set_array_not_contiguous(PyArrayObject* ao) { - ao->flags &= ~(NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); + // Numpy>=1.8-compliant equivalent to: + // ao->flags &= ~(NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS); + PyArray_CLEARFLAGS(ao, (NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS)); } #endif // PANDAS__LIBS_SRC_NUMPY_HELPER_H_ diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 7621ac912d4d5..4335e7baeafe9 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -888,7 +888,7 @@ def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None, trans, deltas, typ = get_dst_info(tz) - tdata = <int64_t*> trans.data + tdata = <int64_t*> cnp.PyArray_DATA(trans) ntrans = len(trans) result_a = np.empty(n, dtype=np.int64) diff --git a/pandas/_libs/tslibs/util.pxd b/pandas/_libs/tslibs/util.pxd index efdb1570ed878..624ed7ced2654 100644 --- a/pandas/_libs/tslibs/util.pxd +++ b/pandas/_libs/tslibs/util.pxd @@ -1,10 +1,18 @@ -from numpy cimport ndarray -cimport numpy as cnp -cnp.import_array() -cimport cpython from cpython cimport PyTypeObject +cdef extern from *: + """ + PyObject* char_to_string(const char* data) { + #if PY_VERSION_HEX >= 0x03000000 + return PyUnicode_FromString(data); + #else + return PyString_FromString(data); + #endif + } + """ + object char_to_string(const char* data) + cdef extern from "Python.h": # Note: importing extern-style allows us to declare these as nogil @@ -19,6 +27,8 @@ cdef extern from "Python.h": cdef extern from "numpy/arrayobject.h": PyTypeObject PyFloatingArrType_Type + ctypedef signed long long int64_t + int _import_array() except -1 cdef extern from "numpy/ndarrayobject.h": PyTypeObject PyTimedeltaArrType_Type @@ -29,142 +39,177 @@ cdef extern from "numpy/ndarrayobject.h": bint PyArray_IsIntegerScalar(obj) nogil bint PyArray_Check(obj) nogil +cdef extern from "numpy/npy_common.h": + int64_t NPY_MIN_INT64 + + +cdef extern from "../src/headers/stdint.h": + enum: UINT8_MAX + enum: UINT16_MAX + enum: UINT32_MAX + enum: UINT64_MAX + enum: INT8_MIN + enum: INT8_MAX + enum: INT16_MIN + enum: INT16_MAX + enum: INT32_MAX + enum: INT32_MIN + enum: INT64_MAX + enum: INT64_MIN + + +cdef inline int64_t get_nat(): + return NPY_MIN_INT64 + + +cdef inline int import_array() except -1: + _import_array() + + # -------------------------------------------------------------------- # Type Checking cdef inline bint is_string_object(object obj) nogil: + """ + Cython equivalent of `isinstance(val, compat.string_types)` + + Parameters + ---------- + val : object + + Returns + ------- + is_string : bool + """ return PyString_Check(obj) or PyUnicode_Check(obj) cdef inline bint is_integer_object(object obj) nogil: + """ + Cython equivalent of + + `isinstance(val, (int, long, np.integer)) and not isinstance(val, bool)` + + Parameters + ---------- + val : object + + Returns + ------- + is_integer : bool + + Notes + ----- + This counts np.timedelta64 objects as integers. + """ return not PyBool_Check(obj) and PyArray_IsIntegerScalar(obj) cdef inline bint is_float_object(object obj) nogil: + """ + Cython equivalent of `isinstance(val, (float, np.complex_))` + + Parameters + ---------- + val : object + + Returns + ------- + is_float : bool + """ return (PyFloat_Check(obj) or (PyObject_TypeCheck(obj, &PyFloatingArrType_Type))) cdef inline bint is_complex_object(object obj) nogil: + """ + Cython equivalent of `isinstance(val, (complex, np.complex_))` + + Parameters + ---------- + val : object + + Returns + ------- + is_complex : bool + """ return (PyComplex_Check(obj) or PyObject_TypeCheck(obj, &PyComplexFloatingArrType_Type)) cdef inline bint is_bool_object(object obj) nogil: + """ + Cython equivalent of `isinstance(val, (bool, np.bool_))` + + Parameters + ---------- + val : object + + Returns + ------- + is_bool : bool + """ return (PyBool_Check(obj) or PyObject_TypeCheck(obj, &PyBoolArrType_Type)) cdef inline bint is_timedelta64_object(object obj) nogil: - return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) - - -cdef inline bint is_datetime64_object(object obj) nogil: - return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) - -# -------------------------------------------------------------------- - -cdef extern from "../src/numpy_helper.h": - void set_array_not_contiguous(ndarray ao) - - int assign_value_1d(ndarray, Py_ssize_t, object) except -1 - cnp.int64_t get_nat() - object get_value_1d(ndarray, Py_ssize_t) - const char *get_c_string(object) except NULL - object char_to_string(char*) - -ctypedef fused numeric: - cnp.int8_t - cnp.int16_t - cnp.int32_t - cnp.int64_t - - cnp.uint8_t - cnp.uint16_t - cnp.uint32_t - cnp.uint64_t - - cnp.float32_t - cnp.float64_t - -cdef extern from "../src/headers/stdint.h": - enum: UINT8_MAX - enum: UINT16_MAX - enum: UINT32_MAX - enum: UINT64_MAX - enum: INT8_MIN - enum: INT8_MAX - enum: INT16_MIN - enum: INT16_MAX - enum: INT32_MAX - enum: INT32_MIN - enum: INT64_MAX - enum: INT64_MIN - - -cdef inline object get_value_at(ndarray arr, object loc): - cdef: - Py_ssize_t i, sz - int casted + """ + Cython equivalent of `isinstance(val, np.timedelta64)` - if is_float_object(loc): - casted = int(loc) - if casted == loc: - loc = casted - i = <Py_ssize_t> loc - sz = cnp.PyArray_SIZE(arr) + Parameters + ---------- + val : object - if i < 0 and sz > 0: - i += sz - elif i >= sz or sz == 0: - raise IndexError('index out of bounds') + Returns + ------- + is_timedelta64 : bool + """ + return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type) - return get_value_1d(arr, i) +cdef inline bint is_datetime64_object(object obj) nogil: + """ + Cython equivalent of `isinstance(val, np.datetime64)` -cdef inline set_value_at_unsafe(ndarray arr, object loc, object value): - """Sets a value into the array without checking the writeable flag. + Parameters + ---------- + val : object - This should be used when setting values in a loop, check the writeable - flag above the loop and then eschew the check on each iteration. + Returns + ------- + is_datetime64 : bool """ - cdef: - Py_ssize_t i, sz - if is_float_object(loc): - casted = int(loc) - if casted == loc: - loc = casted - i = <Py_ssize_t> loc - sz = cnp.PyArray_SIZE(arr) - - if i < 0: - i += sz - elif i >= sz: - raise IndexError('index out of bounds') + return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type) - assign_value_1d(arr, i, value) -cdef inline set_value_at(ndarray arr, object loc, object value): - """Sets a value into the array after checking that the array is mutable. +cdef inline bint is_array(object val): """ - if not cnp.PyArray_ISWRITEABLE(arr): - raise ValueError('assignment destination is read-only') - - set_value_at_unsafe(arr, loc, value) + Cython equivalent of `isinstance(val, np.ndarray)` + Parameters + ---------- + val : object -cdef inline is_array(object o): - return cnp.PyArray_Check(o) + Returns + ------- + is_ndarray : bool + """ + return PyArray_Check(val) -cdef inline bint _checknull(object val): - try: - return val is None or (cpython.PyFloat_Check(val) and val != val) - except ValueError: - return False +cdef inline bint is_period_object(object val): + """ + Cython equivalent of `isinstance(val, pd.Period)` + Parameters + ---------- + val : object -cdef inline bint is_period_object(object val): + Returns + ------- + is_period : bool + """ return getattr(val, '_typ', '_typ') == 'period' @@ -181,3 +226,7 @@ cdef inline bint is_offset_object(object val): is_date_offset : bool """ return getattr(val, '_typ', None) == "dateoffset" + + +cdef inline bint _checknull(object val): + return val is None or (PyFloat_Check(val) and val != val) diff --git a/pandas/_libs/util.pxd b/pandas/_libs/util.pxd index 0b7e66902cbb1..134f34330d8aa 100644 --- a/pandas/_libs/util.pxd +++ b/pandas/_libs/util.pxd @@ -1 +1,81 @@ from tslibs.util cimport * + +from cython cimport Py_ssize_t + +cimport numpy as cnp +from numpy cimport ndarray + + +cdef extern from "src/numpy_helper.h": + void set_array_not_contiguous(ndarray ao) + + int assign_value_1d(ndarray, Py_ssize_t, object) except -1 + object get_value_1d(ndarray, Py_ssize_t) + const char *get_c_string(object) except NULL + + +ctypedef fused numeric: + cnp.int8_t + cnp.int16_t + cnp.int32_t + cnp.int64_t + + cnp.uint8_t + cnp.uint16_t + cnp.uint32_t + cnp.uint64_t + + cnp.float32_t + cnp.float64_t + + +cdef inline object get_value_at(ndarray arr, object loc): + cdef: + Py_ssize_t i, sz + int casted + + if is_float_object(loc): + casted = int(loc) + if casted == loc: + loc = casted + i = <Py_ssize_t> loc + sz = cnp.PyArray_SIZE(arr) + + if i < 0 and sz > 0: + i += sz + elif i >= sz or sz == 0: + raise IndexError('index out of bounds') + + return get_value_1d(arr, i) + + +cdef inline set_value_at_unsafe(ndarray arr, object loc, object value): + """Sets a value into the array without checking the writeable flag. + + This should be used when setting values in a loop, check the writeable + flag above the loop and then eschew the check on each iteration. + """ + cdef: + Py_ssize_t i, sz + if is_float_object(loc): + casted = int(loc) + if casted == loc: + loc = casted + i = <Py_ssize_t> loc + sz = cnp.PyArray_SIZE(arr) + + if i < 0: + i += sz + elif i >= sz: + raise IndexError('index out of bounds') + + assign_value_1d(arr, i, value) + + +cdef inline set_value_at(ndarray arr, object loc, object value): + """Sets a value into the array after checking that the array is mutable. + """ + if not cnp.PyArray_ISWRITEABLE(arr): + raise ValueError('assignment destination is read-only') + + set_value_at_unsafe(arr, loc, value)
`core.dtypes.common.is_period` is confusingly named and never used. This PR gets rid of it. The deprecated numpy API that causes zillions of warnings includes `ndarray.data`, so this replaces the old usage with the encouraged usage. A bunch of `tslibs.util` isn't actually used in tslibs.util, so the relevant functions are moved up to `_libs.util`. Docstrings for most of what's left in tslibs.util. Simplify util._checknull by removing an unnecessary try/except.
https://api.github.com/repos/pandas-dev/pandas/pulls/22071
2018-07-27T00:18:38Z
2018-07-31T13:24:33Z
2018-07-31T13:24:33Z
2018-07-31T16:00:22Z
Split fastpath IntegerArray constructor and general purpose constructor
diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index 9132c74091410..29f258bf1b29e 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -7,4 +7,4 @@ from .period import PeriodArrayMixin # noqa from .timedeltas import TimedeltaArrayMixin # noqa from .integer import ( # noqa - IntegerArray, to_integer_array) + IntegerArray, integer_array) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index c126117060c3d..48a5db7793921 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -11,6 +11,7 @@ from pandas.core.dtypes.generic import ABCSeries, ABCIndexClass from pandas.core.dtypes.common import ( is_integer, is_scalar, is_float, + is_bool_dtype, is_float_dtype, is_integer_dtype, is_object_dtype, @@ -76,7 +77,7 @@ def construct_from_string(cls, string): "'{}'".format(cls, string)) -def to_integer_array(values, dtype=None): +def integer_array(values, dtype=None, copy=False): """ Infer and return an integer array of the values. @@ -85,6 +86,7 @@ def to_integer_array(values, dtype=None): values : 1D list-like dtype : dtype, optional dtype to coerce + copy : boolean, default False Returns ------- @@ -94,7 +96,8 @@ def to_integer_array(values, dtype=None): ------ TypeError if incompatible types """ - return IntegerArray(values, dtype=dtype, copy=False) + values, mask = coerce_to_array(values, dtype=dtype, copy=copy) + return IntegerArray(values, mask) def safe_cast(values, dtype, copy): @@ -133,6 +136,11 @@ def coerce_to_array(values, dtype, mask=None, copy=False): ------- tuple of (values, mask) """ + # if values is integer numpy array, preserve it's dtype + if dtype is None and hasattr(values, 'dtype'): + if is_integer_dtype(values.dtype): + dtype = values.dtype + if dtype is not None: if not issubclass(type(dtype), _IntegerDtype): try: @@ -174,10 +182,7 @@ def coerce_to_array(values, dtype, mask=None, copy=False): # infer dtype if needed if dtype is None: - if is_integer_dtype(values): - dtype = values.dtype - else: - dtype = np.dtype('int64') + dtype = np.dtype('int64') else: dtype = dtype.type @@ -197,47 +202,62 @@ def coerce_to_array(values, dtype, mask=None, copy=False): class IntegerArray(ExtensionArray, ExtensionOpsMixin): """ - We represent an IntegerArray with 2 numpy arrays + Array of integer (optional missing) values. + + We represent an IntegerArray with 2 numpy arrays: + - data: contains a numpy integer array of the appropriate dtype - - mask: a boolean array holding a mask on the data, False is missing + - mask: a boolean array holding a mask on the data, True is missing + + To construct an IntegerArray from generic array-like input, use + ``integer_array`` function instead. + + Parameters + ---------- + values : integer 1D numpy array + mask : boolean 1D numpy array + copy : bool, default False + + Returns + ------- + IntegerArray + """ @cache_readonly def dtype(self): return _dtypes[str(self._data.dtype)] - def __init__(self, values, mask=None, dtype=None, copy=False): - """ - Parameters - ---------- - values : 1D list-like / IntegerArray - mask : 1D list-like, optional - dtype : subclass of _IntegerDtype, optional - copy : bool, default False + def __init__(self, values, mask, copy=False): + if not (isinstance(values, np.ndarray) + and is_integer_dtype(values.dtype)): + raise TypeError("values should be integer numpy array. Use " + "the 'integer_array' function instead") + if not (isinstance(mask, np.ndarray) and is_bool_dtype(mask.dtype)): + raise TypeError("mask should be boolean numpy array. Use " + "the 'integer_array' function instead") - Returns - ------- - IntegerArray - """ - self._data, self._mask = coerce_to_array( - values, dtype=dtype, mask=mask, copy=copy) + if copy: + values = values.copy() + mask = mask.copy() + + self._data = values + self._mask = mask @classmethod def _from_sequence(cls, scalars, dtype=None, copy=False): - return cls(scalars, dtype=dtype, copy=copy) + return integer_array(scalars, dtype=dtype, copy=copy) @classmethod def _from_factorized(cls, values, original): - return cls(values, dtype=original.dtype) + return integer_array(values, dtype=original.dtype) def __getitem__(self, item): if is_integer(item): if self._mask[item]: return self.dtype.na_value return self._data[item] - return type(self)(self._data[item], - mask=self._mask[item], - dtype=self.dtype) + return type(self)(self._data[item], self._mask[item]) def _coerce_to_ndarray(self): """ @@ -294,7 +314,7 @@ def take(self, indexer, allow_fill=False, fill_value=None): result[fill_mask] = fill_value mask = mask ^ fill_mask - return type(self)(result, mask=mask, dtype=self.dtype, copy=False) + return type(self)(result, mask, copy=False) def copy(self, deep=False): data, mask = self._data, self._mask @@ -304,7 +324,7 @@ def copy(self, deep=False): else: data = data.copy() mask = mask.copy() - return type(self)(data, mask, dtype=self.dtype, copy=False) + return type(self)(data, mask, copy=False) def __setitem__(self, key, value): _is_scalar = is_scalar(value) @@ -356,7 +376,7 @@ def _na_value(self): def _concat_same_type(cls, to_concat): data = np.concatenate([x._data for x in to_concat]) mask = np.concatenate([x._mask for x in to_concat]) - return cls(data, mask=mask, dtype=to_concat[0].dtype) + return cls(data, mask) def astype(self, dtype, copy=True): """Cast to a NumPy array or IntegerArray with 'dtype'. @@ -386,8 +406,7 @@ def astype(self, dtype, copy=True): if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dtype, casting='same_kind', copy=False) - return type(self)(result, mask=self._mask, - dtype=dtype, copy=False) + return type(self)(result, mask=self._mask, copy=False) # coerce data = self._coerce_to_ndarray() @@ -523,7 +542,7 @@ def _maybe_mask_result(self, result, mask, other, op_name): result[mask] = np.nan return result - return type(self)(result, mask=mask, dtype=self.dtype, copy=False) + return type(self)(result, mask, copy=False) @classmethod def _create_arithmetic_method(cls, op): diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index bfa669a0ca164..5a026fe19a952 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -300,7 +300,7 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, if not (dtype is None or is_object_dtype(dtype)): # coerce to the provided dtype - data = dtype.construct_array_type()( + data = dtype.construct_array_type()._from_sequence( data, dtype=dtype, copy=False) # coerce to the object dtype diff --git a/pandas/core/series.py b/pandas/core/series.py index 4b4fccccda4a0..090a63dd0cb9f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4111,7 +4111,7 @@ def _try_cast(arr, take_fast_path): ordered=dtype.ordered) elif is_extension_array_dtype(dtype): # create an extension array from its dtype - array_type = dtype.construct_array_type() + array_type = dtype.construct_array_type()._from_sequence subarr = array_type(subarr, dtype=dtype, copy=copy) elif dtype is not None and raise_cast_failure: diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 886a0f66b5f66..22b21102fa4ae 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -213,7 +213,7 @@ def test_take_series(self, data): s = pd.Series(data) result = s.take([0, -1]) expected = pd.Series( - data._from_sequence([data[0], data[len(data) - 1]]), + data._from_sequence([data[0], data[len(data) - 1]], dtype=s.dtype), index=[0, len(data) - 1]) self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index 43b2702c72193..2fe547e50a34b 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -77,8 +77,8 @@ def test_fillna_series(self, data_missing): ser = pd.Series(data_missing) result = ser.fillna(fill_value) - expected = pd.Series( - data_missing._from_sequence([fill_value, fill_value])) + expected = pd.Series(data_missing._from_sequence( + [fill_value, fill_value], dtype=data_missing.dtype)) self.assert_series_equal(result, expected) # Fill with a series @@ -94,11 +94,11 @@ def test_fillna_series_method(self, data_missing, method): fill_value = data_missing[1] if method == 'ffill': - data_missing = type(data_missing)(data_missing[::-1]) + data_missing = data_missing[::-1] result = pd.Series(data_missing).fillna(method=method) - expected = pd.Series( - data_missing._from_sequence([fill_value, fill_value])) + expected = pd.Series(data_missing._from_sequence( + [fill_value, fill_value], dtype=data_missing.dtype)) self.assert_series_equal(result, expected) @@ -111,7 +111,8 @@ def test_fillna_frame(self, data_missing): }).fillna(fill_value) expected = pd.DataFrame({ - "A": data_missing._from_sequence([fill_value, fill_value]), + "A": data_missing._from_sequence([fill_value, fill_value], + dtype=data_missing.dtype), "B": [1, 2], }) diff --git a/pandas/tests/extension/integer/test_integer.py b/pandas/tests/extension/integer/test_integer.py index 5e0f5bf0a5dcf..e3bba3f275b73 100644 --- a/pandas/tests/extension/integer/test_integer.py +++ b/pandas/tests/extension/integer/test_integer.py @@ -9,7 +9,7 @@ from pandas.core.dtypes.generic import ABCIndexClass from pandas.core.arrays import ( - to_integer_array, IntegerArray) + integer_array, IntegerArray) from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, Int32Dtype, Int64Dtype, UInt8Dtype, UInt16Dtype, UInt32Dtype, UInt64Dtype) @@ -31,12 +31,12 @@ def dtype(request): @pytest.fixture def data(dtype): - return IntegerArray(make_data(), dtype=dtype) + return integer_array(make_data(), dtype=dtype) @pytest.fixture def data_missing(dtype): - return IntegerArray([np.nan, 1], dtype=dtype) + return integer_array([np.nan, 1], dtype=dtype) @pytest.fixture @@ -49,12 +49,12 @@ def gen(count): @pytest.fixture def data_for_sorting(dtype): - return IntegerArray([1, 2, 0], dtype=dtype) + return integer_array([1, 2, 0], dtype=dtype) @pytest.fixture def data_missing_for_sorting(dtype): - return IntegerArray([1, np.nan, 0], dtype=dtype) + return integer_array([1, np.nan, 0], dtype=dtype) @pytest.fixture @@ -74,7 +74,7 @@ def data_for_grouping(dtype): a = 0 c = 2 na = np.nan - return IntegerArray([b, b, na, na, a, a, b, c], dtype=dtype) + return integer_array([b, b, na, na, a, a, b, c], dtype=dtype) def test_dtypes(dtype): @@ -494,8 +494,7 @@ def test_construct_index(self, all_data, dropna): else: other = all_data - result = pd.Index(IntegerArray(other, - dtype=all_data.dtype)) + result = pd.Index(integer_array(other, dtype=all_data.dtype)) expected = pd.Index(other, dtype=object) self.assert_index_equal(result, expected) @@ -584,14 +583,14 @@ def test_construct_cast_invalid(self, dtype): msg = "cannot safely" arr = [1.2, 2.3, 3.7] with tm.assert_raises_regex(TypeError, msg): - IntegerArray(arr, dtype=dtype) + integer_array(arr, dtype=dtype) with tm.assert_raises_regex(TypeError, msg): pd.Series(arr).astype(dtype) arr = [1.2, 2.3, 3.7, np.nan] with tm.assert_raises_regex(TypeError, msg): - IntegerArray(arr, dtype=dtype) + integer_array(arr, dtype=dtype) with tm.assert_raises_regex(TypeError, msg): pd.Series(arr).astype(dtype) @@ -650,10 +649,45 @@ def test_conversions(data_missing): assert type(r) == type(e) +def test_integer_array_constructor(): + values = np.array([1, 2, 3, 4], dtype='int64') + mask = np.array([False, False, False, True], dtype='bool') + + result = IntegerArray(values, mask) + expected = integer_array([1, 2, 3, np.nan], dtype='int64') + tm.assert_extension_array_equal(result, expected) + + with pytest.raises(TypeError): + IntegerArray(values.tolist(), mask) + + with pytest.raises(TypeError): + IntegerArray(values, mask.tolist()) + + with pytest.raises(TypeError): + IntegerArray(values.astype(float), mask) + + with pytest.raises(TypeError): + IntegerArray(values) + + +def test_integer_array_constructor_copy(): + values = np.array([1, 2, 3, 4], dtype='int64') + mask = np.array([False, False, False, True], dtype='bool') + + result = IntegerArray(values, mask) + assert result._data is values + assert result._mask is mask + + result = IntegerArray(values, mask, copy=True) + assert result._data is not values + assert result._mask is not mask + + @pytest.mark.parametrize( 'values', [ ['foo', 'bar'], + ['1', '2'], 'foo', 1, 1.0, @@ -662,7 +696,41 @@ def test_conversions(data_missing): def test_to_integer_array_error(values): # error in converting existing arrays to IntegerArrays with pytest.raises(TypeError): - to_integer_array(values) + integer_array(values) + + +def test_to_integer_array_inferred_dtype(): + # if values has dtype -> respect it + result = integer_array(np.array([1, 2], dtype='int8')) + assert result.dtype == Int8Dtype() + result = integer_array(np.array([1, 2], dtype='int32')) + assert result.dtype == Int32Dtype() + + # if values have no dtype -> always int64 + result = integer_array([1, 2]) + assert result.dtype == Int64Dtype() + + +def test_to_integer_array_dtype_keyword(): + result = integer_array([1, 2], dtype='int8') + assert result.dtype == Int8Dtype() + + # if values has dtype -> override it + result = integer_array(np.array([1, 2], dtype='int8'), dtype='int32') + assert result.dtype == Int32Dtype() + + +def test_to_integer_array_float(): + result = integer_array([1., 2.]) + expected = integer_array([1, 2]) + tm.assert_extension_array_equal(result, expected) + + with pytest.raises(TypeError, match="cannot safely cast non-equivalent"): + integer_array([1.5, 2.]) + + # for float dtypes, the itemsize is not preserved + result = integer_array(np.array([1., 2.], dtype='float32')) + assert result.dtype == Int64Dtype() @pytest.mark.parametrize( @@ -673,8 +741,9 @@ def test_to_integer_array_error(values): (np.array([1, np.nan]), 'int8', Int8Dtype)]) def test_to_integer_array(values, to_dtype, result_dtype): # convert existing arrays to IntegerArrays - result = to_integer_array(values, dtype=to_dtype) - expected = IntegerArray(values, dtype=result_dtype()) + result = integer_array(values, dtype=to_dtype) + assert result.dtype == result_dtype() + expected = integer_array(values, dtype=result_dtype()) tm.assert_extension_array_equal(result, expected)
Related to the discussion we were having on the PR: https://github.com/pandas-dev/pandas/pull/21160/#discussion_r201209246 (@jreback @shoyer). Opening this PR for discussion, to *show* what I meant there, to hopefully make it more concrete discussion. Briefly the changes / rationale: - Separate the "fastpath" and general purpose constructor (in master everything is passed through `coerce_to_array`: - `IntegerArray` is the fastpath if you know you have a proper `values` and `mask` - `integer_array` as general purpose constructor function, that eg parses lists, detects NaNs etc (exact API to discuss of course) - IMO this clear separation makes the code cleaner (in all internal usage we know what we want). In the past we often added a `fastpath` keyword to the constructor, but IMO we should not repeat that pattern in new code (it is overloading the main constructor by combining things). - This also has the benefit of improved performance. Eg on an array of 1e5 values, the current constructor has an overhead of ca 80 µs, not much of course but that means that a simple slice is 82 instead of 2 µs (of course, this improvement does not need the exact proposal in this PR, you could certainly do a PR adding a fastpath keyword that achieves the same boost). Note that this is not yet a fully implemented PR: - Docstrings still need to be updated - Tests for new behaviour needs to be added - `coerce_to_array` can be simplified a little bit, as currently the `mask` argument is nowhere used (unless we foresee use cases for that?)
https://api.github.com/repos/pandas-dev/pandas/pulls/22070
2018-07-26T21:10:33Z
2018-08-20T10:53:52Z
2018-08-20T10:53:52Z
2018-08-20T11:14:21Z
De-duplicate dispatch code, remove unreachable branches
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 811f0d25c3838..dc631503754f5 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1545,7 +1545,7 @@ cdef class _Period(object): See Also -------- Period.year : Return the calendar year of the period. - + Examples -------- If the natural and fiscal year are the same, `qyear` and `year` will diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 9e7f1d94934ba..c5279ad262f28 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -929,7 +929,7 @@ cdef class _Timedelta(timedelta): def nanoseconds(self): """ Return the number of nanoseconds (n), where 0 <= n < 1 microsecond. - + Returns ------- int diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ebd35cb1a6a1a..719488a50ca40 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4906,20 +4906,7 @@ def _arith_op(left, right): if this._is_mixed_type or other._is_mixed_type: # iterate over columns - if this.columns.is_unique: - # unique columns - result = {col: _arith_op(this[col], other[col]) - for col in this} - result = self._constructor(result, index=new_index, - columns=new_columns, copy=False) - else: - # non-unique columns - result = {i: _arith_op(this.iloc[:, i], other.iloc[:, i]) - for i, col in enumerate(this.columns)} - result = self._constructor(result, index=new_index, copy=False) - result.columns = new_columns - return result - + return ops.dispatch_to_series(this, other, _arith_op) else: result = _arith_op(this.values, other.values) @@ -4953,27 +4940,16 @@ def _compare_frame(self, other, func, str_rep): # compare_frame assumes self._indexed_same(other) import pandas.core.computation.expressions as expressions - # unique - if self.columns.is_unique: - - def _compare(a, b): - return {col: func(a[col], b[col]) for col in a.columns} - new_data = expressions.evaluate(_compare, str_rep, self, other) - return self._constructor(data=new_data, index=self.index, - columns=self.columns, copy=False) - # non-unique - else: - - def _compare(a, b): - return {i: func(a.iloc[:, i], b.iloc[:, i]) - for i, col in enumerate(a.columns)} + def _compare(a, b): + return {i: func(a.iloc[:, i], b.iloc[:, i]) + for i in range(len(a.columns))} - new_data = expressions.evaluate(_compare, str_rep, self, other) - result = self._constructor(data=new_data, index=self.index, - copy=False) - result.columns = self.columns - return result + new_data = expressions.evaluate(_compare, str_rep, self, other) + result = self._constructor(data=new_data, index=self.index, + copy=False) + result.columns = self.columns + return result def combine(self, other, func, fill_value=None, overwrite=True): """ diff --git a/pandas/core/ops.py b/pandas/core/ops.py index f7d863bba82a7..9bf952633ccff 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -1143,6 +1143,7 @@ def na_op(x, y): result[mask] = op(x[mask], com.values_from_object(y[mask])) else: assert isinstance(x, np.ndarray) + assert is_scalar(y) result = np.empty(len(x), dtype=x.dtype) mask = notna(x) result[mask] = op(x[mask], y) @@ -1189,6 +1190,7 @@ def wrapper(left, right): elif (is_extension_array_dtype(left) or is_extension_array_dtype(right)): + # TODO: should this include `not is_scalar(right)`? return dispatch_to_extension_op(op, left, right) elif is_datetime64_dtype(left) or is_datetime64tz_dtype(left): @@ -1278,13 +1280,11 @@ def na_op(x, y): # should have guarantess on what x, y can be type-wise # Extension Dtypes are not called here - # dispatch to the categorical if we have a categorical - # in either operand - if is_categorical_dtype(y) and not is_scalar(y): - # The `not is_scalar(y)` check excludes the string "category" - return op(y, x) + # Checking that cases that were once handled here are no longer + # reachable. + assert not (is_categorical_dtype(y) and not is_scalar(y)) - elif is_object_dtype(x.dtype): + if is_object_dtype(x.dtype): result = _comp_method_OBJECT_ARRAY(op, x, y) elif is_datetimelike_v_numeric(x, y): @@ -1342,7 +1342,7 @@ def wrapper(self, other, axis=None): return self._constructor(res_values, index=self.index, name=res_name) - if is_datetime64_dtype(self) or is_datetime64tz_dtype(self): + elif is_datetime64_dtype(self) or is_datetime64tz_dtype(self): # Dispatch to DatetimeIndex to ensure identical # Series/Index behavior if (isinstance(other, datetime.date) and @@ -1384,8 +1384,9 @@ def wrapper(self, other, axis=None): name=res_name) elif (is_extension_array_dtype(self) or - (is_extension_array_dtype(other) and - not is_scalar(other))): + (is_extension_array_dtype(other) and not is_scalar(other))): + # Note: the `not is_scalar(other)` condition rules out + # e.g. other == "category" return dispatch_to_extension_op(op, self, other) elif isinstance(other, ABCSeries): @@ -1408,13 +1409,6 @@ def wrapper(self, other, axis=None): # is not. return result.__finalize__(self).rename(res_name) - elif isinstance(other, pd.Categorical): - # ordering of checks matters; by this point we know - # that not is_categorical_dtype(self) - res_values = op(self.values, other) - return self._constructor(res_values, index=self.index, - name=res_name) - elif is_scalar(other) and isna(other): # numpy does not like comparisons vs None if op is operator.ne: @@ -1544,6 +1538,41 @@ def flex_wrapper(self, other, level=None, fill_value=None, axis=0): # ----------------------------------------------------------------------------- # DataFrame +def dispatch_to_series(left, right, func): + """ + Evaluate the frame operation func(left, right) by evaluating + column-by-column, dispatching to the Series implementation. + + Parameters + ---------- + left : DataFrame + right : scalar or DataFrame + func : arithmetic or comparison operator + + Returns + ------- + DataFrame + """ + # Note: we use iloc to access columns for compat with cases + # with non-unique columns. + if lib.is_scalar(right): + new_data = {i: func(left.iloc[:, i], right) + for i in range(len(left.columns))} + elif isinstance(right, ABCDataFrame): + assert right._indexed_same(left) + new_data = {i: func(left.iloc[:, i], right.iloc[:, i]) + for i in range(len(left.columns))} + else: + # Remaining cases have less-obvious dispatch rules + raise NotImplementedError + + result = left._constructor(new_data, index=left.index, copy=False) + # Pin columns instead of passing to constructor for compat with + # non-unique columns case + result.columns = left.columns + return result + + def _combine_series_frame(self, other, func, fill_value=None, axis=None, level=None, try_cast=True): """
There are a couple of `DataFrame` methods that operate column-wise, dispatching to `Series` implementations. This de-duplicates that code by implementing `ops.dispatch_to_series`. Importantly, this function is going to be used a few more times as we move towards getting rid of `BlockManager.eval` and `Block.eval`, so putting it in place now makes for a more focused diff later. Also removes a couple of no-longer-reachable cases in comparison ops. - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/22068
2018-07-26T16:47:34Z
2018-08-08T10:17:37Z
2018-08-08T10:17:37Z
2018-08-08T15:50:04Z
DOC: consistent docstring for compression kwarg
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 16332738ce610..869f33c213422 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1750,9 +1750,9 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, encoding : string, optional A string representing the encoding to use in the output file, defaults to 'ascii' on Python 2 and 'utf-8' on Python 3. - compression : {'infer', 'gzip', 'bz2', 'xz', None}, default None + compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default None If 'infer' and `path_or_buf` is path-like, then detect compression - from the following extensions: '.gz', '.bz2' or '.xz' + from the following extensions: '.gz', '.bz2', '.zip' or '.xz' (otherwise no compression). line_terminator : string, default ``'\n'`` The newline character or character sequence to use in the output diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 16105014bf74e..cbe8d15065881 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1999,7 +1999,7 @@ def to_json(self, path_or_buf=None, orient=None, date_format=None, .. versionadded:: 0.19.0 - compression : {'infer', 'gzip', 'bz2', 'xz', None}, default None + compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default None A string representing the compression to use in the output file, only used when the first argument is a filename.
- [x] closes #17900 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` https://github.com/pandas-dev/pandas/pull/17900#discussion_r147927074 removed zip from docstring. But the support to write zip compression was added during March and April this year (mainly https://github.com/pandas-dev/pandas/pull/20394 and a few patches) and now in functional and in production. Because #17900 started when there is no zip writing and merged after zip writing support is added, it appears to have inadvertently changed docstring. This PR disambiguates and reflects production. ``` import os import pandas as pd a = pd.DataFrame(10000 * [[123, 234, 435]], columns=['A', 'B', 'C']) a.to_csv('test_compressed', index=False, compression='zip') b = pd.read_csv('test_compressed', compression='zip') assert a.equals(b) os.remove('test_compressed') >>> pd.__version__ '0.23.3' ```
https://api.github.com/repos/pandas-dev/pandas/pulls/22066
2018-07-26T13:33:29Z
2018-07-28T13:16:25Z
2018-07-28T13:16:25Z
2018-07-28T14:50:31Z
TST: suppress deprecation warnings for compress
diff --git a/pandas/core/series.py b/pandas/core/series.py index b84179875db1f..15a58afc66b1e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -518,7 +518,8 @@ def compress(self, condition, *args, **kwargs): numpy.ndarray.compress """ msg = ("Series.compress(condition) is deprecated. " - "Use Series[condition] instead.") + "Use 'Series[condition]' or " + "'np.asarray(series).compress(condition)' instead.") warnings.warn(msg, FutureWarning, stacklevel=2) nv.validate_compress(args, kwargs) return self[condition] diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 09e89115e120e..6710b90effb2f 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -595,15 +595,17 @@ def test_numpy_compress(self): index=list('abcde'), name='foo') expected = Series(s.values.compress(cond), index=list('ac'), name='foo') - tm.assert_series_equal(np.compress(cond, s), expected) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + tm.assert_series_equal(np.compress(cond, s), expected) - msg = "the 'axis' parameter is not supported" - tm.assert_raises_regex(ValueError, msg, np.compress, - cond, s, axis=1) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + msg = "the 'axis' parameter is not supported" + tm.assert_raises_regex(ValueError, msg, np.compress, + cond, s, axis=1) - msg = "the 'out' parameter is not supported" - tm.assert_raises_regex(ValueError, msg, np.compress, - cond, s, out=s) + msg = "the 'out' parameter is not supported" + tm.assert_raises_regex(ValueError, msg, np.compress, + cond, s, out=s) def test_round(self): self.ts.index.name = "index_name" diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index f7f1ea019a3f0..da9b03e81994d 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -424,19 +424,23 @@ def f(x): # compress # GH 6658 s = Series([0, 1., -1], index=list('abc')) - result = np.compress(s > 0, s) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = np.compress(s > 0, s) tm.assert_series_equal(result, Series([1.], index=['b'])) - result = np.compress(s < -1, s) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = np.compress(s < -1, s) # result empty Index(dtype=object) as the same as original exp = Series([], dtype='float64', index=Index([], dtype='object')) tm.assert_series_equal(result, exp) s = Series([0, 1., -1], index=[.1, .2, .3]) - result = np.compress(s > 0, s) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = np.compress(s > 0, s) tm.assert_series_equal(result, Series([1.], index=[.2])) - result = np.compress(s < -1, s) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + result = np.compress(s < -1, s) # result empty Float64Index as the same as original exp = Series([], dtype='float64', index=Index([], dtype='float64')) tm.assert_series_equal(result, exp)
xref https://github.com/pandas-dev/pandas/pull/21930#issuecomment-408068861 In case we find it OK `np.compress` with Series is also deprecated, this PR makes sure the warnings are catched in the tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/22064
2018-07-26T11:51:11Z
2018-08-15T08:06:40Z
2018-08-15T08:06:40Z
2018-08-15T08:06:44Z
TST: Parameterize more tests
diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 6cc34770a65e0..e082629a5433d 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -256,36 +256,40 @@ def test_constructor_with_generator(self): cat = Categorical([0, 1, 2], categories=xrange(3)) tm.assert_categorical_equal(cat, exp) - def test_constructor_with_datetimelike(self): - - # 12077 - # constructor wwth a datetimelike and NaT - - for dtl in [date_range('1995-01-01 00:00:00', periods=5, freq='s'), - date_range('1995-01-01 00:00:00', periods=5, - freq='s', tz='US/Eastern'), - timedelta_range('1 day', periods=5, freq='s')]: - - s = Series(dtl) - c = Categorical(s) - expected = type(dtl)(s) - expected.freq = None - tm.assert_index_equal(c.categories, expected) - tm.assert_numpy_array_equal(c.codes, np.arange(5, dtype='int8')) - - # with NaT - s2 = s.copy() - s2.iloc[-1] = NaT - c = Categorical(s2) - expected = type(dtl)(s2.dropna()) - expected.freq = None - tm.assert_index_equal(c.categories, expected) - - exp = np.array([0, 1, 2, 3, -1], dtype=np.int8) - tm.assert_numpy_array_equal(c.codes, exp) - - result = repr(c) - assert 'NaT' in result + @pytest.mark.parametrize("dtl", [ + date_range("1995-01-01 00:00:00", periods=5, freq="s"), + date_range("1995-01-01 00:00:00", periods=5, + freq="s", tz="US/Eastern"), + timedelta_range("1 day", periods=5, freq="s") + ]) + def test_constructor_with_datetimelike(self, dtl): + # see gh-12077 + # constructor with a datetimelike and NaT + + s = Series(dtl) + c = Categorical(s) + + expected = type(dtl)(s) + expected.freq = None + + tm.assert_index_equal(c.categories, expected) + tm.assert_numpy_array_equal(c.codes, np.arange(5, dtype="int8")) + + # with NaT + s2 = s.copy() + s2.iloc[-1] = NaT + c = Categorical(s2) + + expected = type(dtl)(s2.dropna()) + expected.freq = None + + tm.assert_index_equal(c.categories, expected) + + exp = np.array([0, 1, 2, 3, -1], dtype=np.int8) + tm.assert_numpy_array_equal(c.codes, exp) + + result = repr(c) + assert "NaT" in result def test_constructor_from_index_series_datetimetz(self): idx = date_range('2015-01-01 10:00', freq='D', periods=3, diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index edabc177535fc..a7a9faa9e77eb 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -82,25 +82,18 @@ def test_dtype_equal(name1, dtype1, name2, dtype2): assert not com.is_dtype_equal(dtype1, dtype2) -def test_dtype_equal_strict(): - - # we are strict on kind equality - for dtype in [np.int8, np.int16, np.int32]: - assert not com.is_dtype_equal(np.int64, dtype) - - for dtype in [np.float32]: - assert not com.is_dtype_equal(np.float64, dtype) - - # strict w.r.t. PeriodDtype - assert not com.is_dtype_equal(PeriodDtype('D'), PeriodDtype('2D')) - - # strict w.r.t. datetime64 - assert not com.is_dtype_equal( - com.pandas_dtype('datetime64[ns, US/Eastern]'), - com.pandas_dtype('datetime64[ns, CET]')) - - # see gh-15941: no exception should be raised - assert not com.is_dtype_equal(None, None) +@pytest.mark.parametrize("dtype1,dtype2", [ + (np.int8, np.int64), + (np.int16, np.int64), + (np.int32, np.int64), + (np.float32, np.float64), + (PeriodDtype("D"), PeriodDtype("2D")), # PeriodType + (com.pandas_dtype("datetime64[ns, US/Eastern]"), + com.pandas_dtype("datetime64[ns, CET]")), # Datetime + (None, None) # gh-15941: no exception should be raised. +]) +def test_dtype_equal_strict(dtype1, dtype2): + assert not com.is_dtype_equal(dtype1, dtype2) def get_is_dtype_funcs(): diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 2eed6b47df9e3..3e5c13208f164 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -85,12 +85,15 @@ def test_get(self): assert self.frame.get('foo') is None assert_series_equal(self.frame.get('foo', self.frame['B']), self.frame['B']) - # None - # GH 5652 - for df in [DataFrame(), DataFrame(columns=list('AB')), - DataFrame(columns=list('AB'), index=range(3))]: - result = df.get(None) - assert result is None + + @pytest.mark.parametrize("df", [ + DataFrame(), + DataFrame(columns=list("AB")), + DataFrame(columns=list("AB"), index=range(3)) + ]) + def test_get_none(self, df): + # see gh-5652 + assert df.get(None) is None def test_loc_iterable(self): idx = iter(['A', 'B', 'C']) @@ -472,11 +475,6 @@ def f(): assert smaller['col10'].dtype == np.object_ assert (smaller['col10'] == ['1', '2']).all() - # with a dtype - for dtype in ['int32', 'int64', 'float32', 'float64']: - self.frame[dtype] = np.array(arr, dtype=dtype) - assert self.frame[dtype].dtype.name == dtype - # dtype changing GH4204 df = DataFrame([[0, 0]]) df.iloc[0] = np.nan @@ -487,6 +485,13 @@ def f(): df.loc[0] = np.nan assert_frame_equal(df, expected) + @pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"]) + def test_setitem_dtype(self, dtype): + arr = randn(len(self.frame)) + + self.frame[dtype] = np.array(arr, dtype=dtype) + assert self.frame[dtype].dtype.name == dtype + def test_setitem_tuple(self): self.frame['A', 'B'] = self.frame['A'] assert_series_equal(self.frame['A', 'B'], self.frame[ @@ -746,18 +751,20 @@ def test_setitem_empty(self): result.loc[result.b.isna(), 'a'] = result.a assert_frame_equal(result, df) - def test_setitem_empty_frame_with_boolean(self): - # Test for issue #10126 + @pytest.mark.parametrize("dtype", ["float", "int64"]) + @pytest.mark.parametrize("kwargs", [ + dict(), + dict(index=[1]), + dict(columns=["A"]) + ]) + def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): + # see gh-10126 + kwargs["dtype"] = dtype + df = DataFrame(**kwargs) - for dtype in ('float', 'int64'): - for df in [ - pd.DataFrame(dtype=dtype), - pd.DataFrame(dtype=dtype, index=[1]), - pd.DataFrame(dtype=dtype, columns=['A']), - ]: - df2 = df.copy() - df[df > df2] = 47 - assert_frame_equal(df, df2) + df2 = df.copy() + df[df > df2] = 47 + assert_frame_equal(df, df2) def test_setitem_scalars_no_index(self): # GH16823 / 17894 @@ -2007,48 +2014,54 @@ def test_nested_exception(self): except Exception as e: assert type(e) != UnboundLocalError - def test_reindex_methods(self): - df = pd.DataFrame({'x': list(range(5))}) + @pytest.mark.parametrize("method,expected_values", [ + ("nearest", [0, 1, 1, 2]), + ("pad", [np.nan, 0, 1, 1]), + ("backfill", [0, 1, 2, 2]) + ]) + def test_reindex_methods(self, method, expected_values): + df = pd.DataFrame({"x": list(range(5))}) + target = np.array([-0.1, 0.9, 1.1, 1.5]) + + expected = pd.DataFrame({'x': expected_values}, index=target) + actual = df.reindex(target, method=method) + assert_frame_equal(expected, actual) + + actual = df.reindex_like(df, method=method, tolerance=0) + assert_frame_equal(df, actual) + actual = df.reindex_like(df, method=method, tolerance=[0, 0, 0, 0]) + assert_frame_equal(df, actual) + + actual = df.reindex(target, method=method, tolerance=1) + assert_frame_equal(expected, actual) + actual = df.reindex(target, method=method, tolerance=[1, 1, 1, 1]) + assert_frame_equal(expected, actual) + + e2 = expected[::-1] + actual = df.reindex(target[::-1], method=method) + assert_frame_equal(e2, actual) + + new_order = [3, 0, 2, 1] + e2 = expected.iloc[new_order] + actual = df.reindex(target[new_order], method=method) + assert_frame_equal(e2, actual) + + switched_method = ('pad' if method == 'backfill' + else 'backfill' if method == 'pad' + else method) + actual = df[::-1].reindex(target, method=switched_method) + assert_frame_equal(expected, actual) + + def test_reindex_methods_nearest_special(self): + df = pd.DataFrame({"x": list(range(5))}) target = np.array([-0.1, 0.9, 1.1, 1.5]) - for method, expected_values in [('nearest', [0, 1, 1, 2]), - ('pad', [np.nan, 0, 1, 1]), - ('backfill', [0, 1, 2, 2])]: - expected = pd.DataFrame({'x': expected_values}, index=target) - actual = df.reindex(target, method=method) - assert_frame_equal(expected, actual) - - actual = df.reindex_like(df, method=method, tolerance=0) - assert_frame_equal(df, actual) - actual = df.reindex_like(df, method=method, tolerance=[0, 0, 0, 0]) - assert_frame_equal(df, actual) - - actual = df.reindex(target, method=method, tolerance=1) - assert_frame_equal(expected, actual) - actual = df.reindex(target, method=method, tolerance=[1, 1, 1, 1]) - assert_frame_equal(expected, actual) - - e2 = expected[::-1] - actual = df.reindex(target[::-1], method=method) - assert_frame_equal(e2, actual) - - new_order = [3, 0, 2, 1] - e2 = expected.iloc[new_order] - actual = df.reindex(target[new_order], method=method) - assert_frame_equal(e2, actual) - - switched_method = ('pad' if method == 'backfill' - else 'backfill' if method == 'pad' - else method) - actual = df[::-1].reindex(target, method=switched_method) - assert_frame_equal(expected, actual) - - expected = pd.DataFrame({'x': [0, 1, 1, np.nan]}, index=target) - actual = df.reindex(target, method='nearest', tolerance=0.2) + expected = pd.DataFrame({"x": [0, 1, 1, np.nan]}, index=target) + actual = df.reindex(target, method="nearest", tolerance=0.2) assert_frame_equal(expected, actual) - expected = pd.DataFrame({'x': [0, np.nan, 1, np.nan]}, index=target) - actual = df.reindex(target, method='nearest', + expected = pd.DataFrame({"x": [0, np.nan, 1, np.nan]}, index=target) + actual = df.reindex(target, method="nearest", tolerance=[0.5, 0.01, 0.4, 0.1]) assert_frame_equal(expected, actual) @@ -2599,59 +2612,56 @@ def _check_set(df, cond, check_dtypes=True): expected = df[df['a'] == 1].reindex(df.index) assert_frame_equal(result, expected) - def test_where_array_like(self): + @pytest.mark.parametrize("klass", [list, tuple, np.array]) + def test_where_array_like(self, klass): # see gh-15414 - klasses = [list, tuple, np.array] - - df = DataFrame({'a': [1, 2, 3]}) + df = DataFrame({"a": [1, 2, 3]}) cond = [[False], [True], [True]] - expected = DataFrame({'a': [np.nan, 2, 3]}) + expected = DataFrame({"a": [np.nan, 2, 3]}) - for klass in klasses: - result = df.where(klass(cond)) - assert_frame_equal(result, expected) + result = df.where(klass(cond)) + assert_frame_equal(result, expected) - df['b'] = 2 - expected['b'] = [2, np.nan, 2] + df["b"] = 2 + expected["b"] = [2, np.nan, 2] cond = [[False, True], [True, False], [True, True]] - for klass in klasses: - result = df.where(klass(cond)) - assert_frame_equal(result, expected) + result = df.where(klass(cond)) + assert_frame_equal(result, expected) - def test_where_invalid_input(self): + @pytest.mark.parametrize("cond", [ + [[1], [0], [1]], + Series([[2], [5], [7]]), + DataFrame({"a": [2, 5, 7]}), + [["True"], ["False"], ["True"]], + [[Timestamp("2017-01-01")], + [pd.NaT], [Timestamp("2017-01-02")]] + ]) + def test_where_invalid_input_single(self, cond): # see gh-15414: only boolean arrays accepted - df = DataFrame({'a': [1, 2, 3]}) + df = DataFrame({"a": [1, 2, 3]}) msg = "Boolean array expected for the condition" - conds = [ - [[1], [0], [1]], - Series([[2], [5], [7]]), - DataFrame({'a': [2, 5, 7]}), - [["True"], ["False"], ["True"]], - [[Timestamp("2017-01-01")], - [pd.NaT], [Timestamp("2017-01-02")]] - ] - - for cond in conds: - with tm.assert_raises_regex(ValueError, msg): - df.where(cond) - - df['b'] = 2 - conds = [ - [[0, 1], [1, 0], [1, 1]], - Series([[0, 2], [5, 0], [4, 7]]), - [["False", "True"], ["True", "False"], - ["True", "True"]], - DataFrame({'a': [2, 5, 7], 'b': [4, 8, 9]}), - [[pd.NaT, Timestamp("2017-01-01")], - [Timestamp("2017-01-02"), pd.NaT], - [Timestamp("2017-01-03"), Timestamp("2017-01-03")]] - ] - - for cond in conds: - with tm.assert_raises_regex(ValueError, msg): - df.where(cond) + with tm.assert_raises_regex(ValueError, msg): + df.where(cond) + + @pytest.mark.parametrize("cond", [ + [[0, 1], [1, 0], [1, 1]], + Series([[0, 2], [5, 0], [4, 7]]), + [["False", "True"], ["True", "False"], + ["True", "True"]], + DataFrame({"a": [2, 5, 7], "b": [4, 8, 9]}), + [[pd.NaT, Timestamp("2017-01-01")], + [Timestamp("2017-01-02"), pd.NaT], + [Timestamp("2017-01-03"), Timestamp("2017-01-03")]] + ]) + def test_where_invalid_input_multiple(self, cond): + # see gh-15414: only boolean arrays accepted + df = DataFrame({"a": [1, 2, 3], "b": [2, 2, 2]}) + msg = "Boolean array expected for the condition" + + with tm.assert_raises_regex(ValueError, msg): + df.where(cond) def test_where_dataframe_col_match(self): df = DataFrame([[1, 2, 3], [4, 5, 6]]) @@ -2690,9 +2700,7 @@ def test_where_ndframe_align(self): tm.assert_frame_equal(out, expected) def test_where_bug(self): - - # GH 2793 - + # see gh-2793 df = DataFrame({'a': [1.0, 2.0, 3.0, 4.0], 'b': [ 4.0, 3.0, 2.0, 1.0]}, dtype='float64') expected = DataFrame({'a': [np.nan, np.nan, 3.0, 4.0], 'b': [ @@ -2704,25 +2712,25 @@ def test_where_bug(self): result.where(result > 2, np.nan, inplace=True) assert_frame_equal(result, expected) - # mixed - for dtype in ['int16', 'int8', 'int32', 'int64']: - df = DataFrame({'a': np.array([1, 2, 3, 4], dtype=dtype), - 'b': np.array([4.0, 3.0, 2.0, 1.0], - dtype='float64')}) + def test_where_bug_mixed(self, sint_dtype): + # see gh-2793 + df = DataFrame({"a": np.array([1, 2, 3, 4], dtype=sint_dtype), + "b": np.array([4.0, 3.0, 2.0, 1.0], + dtype="float64")}) - expected = DataFrame({'a': [np.nan, np.nan, 3.0, 4.0], - 'b': [4.0, 3.0, np.nan, np.nan]}, - dtype='float64') + expected = DataFrame({"a": [np.nan, np.nan, 3.0, 4.0], + "b": [4.0, 3.0, np.nan, np.nan]}, + dtype="float64") - result = df.where(df > 2, np.nan) - assert_frame_equal(result, expected) + result = df.where(df > 2, np.nan) + assert_frame_equal(result, expected) - result = df.copy() - result.where(result > 2, np.nan, inplace=True) - assert_frame_equal(result, expected) + result = df.copy() + result.where(result > 2, np.nan, inplace=True) + assert_frame_equal(result, expected) - # transpositional issue - # GH7506 + def test_where_bug_transposition(self): + # see gh-7506 a = DataFrame({0: [1, 2], 1: [3, 4], 2: [5, 6]}) b = DataFrame({0: [np.nan, 8], 1: [9, np.nan], 2: [np.nan, np.nan]}) do_not_replace = b.isna() | (a > b) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 9df362a8e132f..f8a0f1688c64e 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -66,32 +66,38 @@ def test_intercept_builtin_sum(): tm.assert_series_equal(result2, expected) -def test_builtins_apply(): # GH8155 +# @pytest.mark.parametrize("f", [max, min, sum]) +# def test_builtins_apply(f): + +@pytest.mark.parametrize("f", [max, min, sum]) +@pytest.mark.parametrize('keys', [ + "jim", # Single key + ["jim", "joe"] # Multi-key +]) +def test_builtins_apply(keys, f): + # see gh-8155 df = pd.DataFrame(np.random.randint(1, 50, (1000, 2)), - columns=['jim', 'joe']) - df['jolie'] = np.random.randn(1000) + columns=["jim", "joe"]) + df["jolie"] = np.random.randn(1000) + + fname = f.__name__ + result = df.groupby(keys).apply(f) + ngroups = len(df.drop_duplicates(subset=keys)) - for keys in ['jim', ['jim', 'joe']]: # single key & multi-key - if keys == 'jim': - continue - for f in [max, min, sum]: - fname = f.__name__ - result = df.groupby(keys).apply(f) - result.shape - ngroups = len(df.drop_duplicates(subset=keys)) - assert result.shape == (ngroups, 3), 'invalid frame shape: '\ - '{} (expected ({}, 3))'.format(result.shape, ngroups) + assert_msg = ("invalid frame shape: {} " + "(expected ({}, 3))".format(result.shape, ngroups)) + assert result.shape == (ngroups, 3), assert_msg - tm.assert_frame_equal(result, # numpy's equivalent function - df.groupby(keys).apply(getattr(np, fname))) + tm.assert_frame_equal(result, # numpy's equivalent function + df.groupby(keys).apply(getattr(np, fname))) - if f != sum: - expected = df.groupby(keys).agg(fname).reset_index() - expected.set_index(keys, inplace=True, drop=False) - tm.assert_frame_equal(result, expected, check_dtype=False) + if f != sum: + expected = df.groupby(keys).agg(fname).reset_index() + expected.set_index(keys, inplace=True, drop=False) + tm.assert_frame_equal(result, expected, check_dtype=False) - tm.assert_series_equal(getattr(result, fname)(), - getattr(df, fname)()) + tm.assert_series_equal(getattr(result, fname)(), + getattr(df, fname)()) def test_arg_passthru(): @@ -365,34 +371,34 @@ def test_groupby_non_arithmetic_agg_types(dtype, method, data): tm.assert_frame_equal(t, df_out) -def test_groupby_non_arithmetic_agg_intlike_precision(): - # GH9311, GH6620 - c = 24650000000000000 - - inputs = ((Timestamp('2011-01-15 12:50:28.502376'), - Timestamp('2011-01-20 12:50:28.593448')), (1 + c, 2 + c)) +@pytest.mark.parametrize("i", [ + (Timestamp("2011-01-15 12:50:28.502376"), + Timestamp("2011-01-20 12:50:28.593448")), + (24650000000000001, 24650000000000002) +]) +def test_groupby_non_arithmetic_agg_int_like_precision(i): + # see gh-6620, gh-9311 + df = pd.DataFrame([{"a": 1, "b": i[0]}, {"a": 1, "b": i[1]}]) - for i in inputs: - df = pd.DataFrame([{'a': 1, 'b': i[0]}, {'a': 1, 'b': i[1]}]) + grp_exp = {"first": {"expected": i[0]}, + "last": {"expected": i[1]}, + "min": {"expected": i[0]}, + "max": {"expected": i[1]}, + "nth": {"expected": i[1], + "args": [1]}, + "count": {"expected": 2}} - grp_exp = {'first': {'expected': i[0]}, - 'last': {'expected': i[1]}, - 'min': {'expected': i[0]}, - 'max': {'expected': i[1]}, - 'nth': {'expected': i[1], - 'args': [1]}, - 'count': {'expected': 2}} + for method, data in compat.iteritems(grp_exp): + if "args" not in data: + data["args"] = [] - for method, data in compat.iteritems(grp_exp): - if 'args' not in data: - data['args'] = [] + grouped = df.groupby("a") + res = getattr(grouped, method)(*data["args"]) - grpd = df.groupby('a') - res = getattr(grpd, method)(*data['args']) - assert res.iloc[0].b == data['expected'] + assert res.iloc[0].b == data["expected"] -def test_fill_constistency(): +def test_fill_consistency(): # GH9221 # pass thru keyword arguments to the generated wrapper diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 57b04bfd82528..aec51afb99ef0 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -451,23 +451,49 @@ def f(group): assert_frame_equal(res, result.loc[key]) -def test_cython_group_transform_algos(): - # GH 4095 - dtypes = [np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint32, - np.uint64, np.float32, np.float64] +def _check_cython_group_transform_cumulative(pd_op, np_op, dtype): + """ + Check a group transform that executes a cumulative function. + + Parameters + ---------- + pd_op : callable + The pandas cumulative function. + np_op : callable + The analogous one in NumPy. + dtype : type + The specified dtype of the data. + """ + + is_datetimelike = False + + data = np.array([[1], [2], [3], [4]], dtype=dtype) + ans = np.zeros_like(data) - ops = [(groupby.group_cumprod_float64, np.cumproduct, [np.float64]), - (groupby.group_cumsum, np.cumsum, dtypes)] + labels = np.array([0, 0, 0, 0], dtype=np.int64) + pd_op(ans, data, labels, is_datetimelike) + tm.assert_numpy_array_equal(np_op(data), ans[:, 0], + check_dtype=False) + + +def test_cython_group_transform_cumsum(any_real_dtype): + # see gh-4095 + dtype = np.dtype(any_real_dtype).type + pd_op, np_op = groupby.group_cumsum, np.cumsum + _check_cython_group_transform_cumulative(pd_op, np_op, dtype) + + +def test_cython_group_transform_cumprod(): + # see gh-4095 + dtype = np.float64 + pd_op, np_op = groupby.group_cumprod_float64, np.cumproduct + _check_cython_group_transform_cumulative(pd_op, np_op, dtype) + + +def test_cython_group_transform_algos(): + # see gh-4095 is_datetimelike = False - for pd_op, np_op, dtypes in ops: - for dtype in dtypes: - data = np.array([[1], [2], [3], [4]], dtype=dtype) - ans = np.zeros_like(data) - labels = np.array([0, 0, 0, 0], dtype=np.int64) - pd_op(ans, data, labels, is_datetimelike) - tm.assert_numpy_array_equal(np_op(data), ans[:, 0], - check_dtype=False) # with nans labels = np.array([0, 0, 0, 0, 0], dtype=np.int64) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index f4bdb7ba86aaf..bf2308cd8c097 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -157,40 +157,43 @@ def test_dt64ser_cmp_period_scalar(self): expected = Series([x > val for x in ser]) tm.assert_series_equal(result, expected) - def test_timestamp_compare_series(self): - # make sure we can compare Timestamps on the right AND left hand side - # GH#4982 - ser = pd.Series(pd.date_range('20010101', periods=10), name='dates') + @pytest.mark.parametrize("left,right", [ + ("lt", "gt"), + ("le", "ge"), + ("eq", "eq"), + ("ne", "ne"), + ]) + def test_timestamp_compare_series(self, left, right): + # see gh-4982 + # Make sure we can compare Timestamps on the right AND left hand side. + ser = pd.Series(pd.date_range("20010101", periods=10), name="dates") s_nat = ser.copy(deep=True) - ser[0] = pd.Timestamp('nat') - ser[3] = pd.Timestamp('nat') + ser[0] = pd.Timestamp("nat") + ser[3] = pd.Timestamp("nat") - ops = {'lt': 'gt', 'le': 'ge', 'eq': 'eq', 'ne': 'ne'} + left_f = getattr(operator, left) + right_f = getattr(operator, right) - for left, right in ops.items(): - left_f = getattr(operator, left) - right_f = getattr(operator, right) - - # no nats - expected = left_f(ser, pd.Timestamp('20010109')) - result = right_f(pd.Timestamp('20010109'), ser) - tm.assert_series_equal(result, expected) + # No NaT + expected = left_f(ser, pd.Timestamp("20010109")) + result = right_f(pd.Timestamp("20010109"), ser) + tm.assert_series_equal(result, expected) - # nats - expected = left_f(ser, pd.Timestamp('nat')) - result = right_f(pd.Timestamp('nat'), ser) - tm.assert_series_equal(result, expected) + # NaT + expected = left_f(ser, pd.Timestamp("nat")) + result = right_f(pd.Timestamp("nat"), ser) + tm.assert_series_equal(result, expected) - # compare to timestamp with series containing nats - expected = left_f(s_nat, pd.Timestamp('20010109')) - result = right_f(pd.Timestamp('20010109'), s_nat) - tm.assert_series_equal(result, expected) + # Compare to Timestamp with series containing NaT + expected = left_f(s_nat, pd.Timestamp("20010109")) + result = right_f(pd.Timestamp("20010109"), s_nat) + tm.assert_series_equal(result, expected) - # compare to nat with series containing nats - expected = left_f(s_nat, pd.Timestamp('nat')) - result = right_f(pd.Timestamp('nat'), s_nat) - tm.assert_series_equal(result, expected) + # Compare to NaT with series containing NaT + expected = left_f(s_nat, pd.Timestamp("nat")) + result = right_f(pd.Timestamp("nat"), s_nat) + tm.assert_series_equal(result, expected) def test_timestamp_equality(self): # GH#11034 diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py index b3330f866ba1f..2790464e2f811 100644 --- a/pandas/tests/sparse/test_array.py +++ b/pandas/tests/sparse/test_array.py @@ -14,6 +14,11 @@ import pandas.util.testing as tm +@pytest.fixture(params=["integer", "block"]) +def kind(request): + return request.param + + class TestSparseArray(object): def setup_method(self, method): @@ -128,31 +133,32 @@ def test_scalar_with_index_infer_dtype(self, scalar, dtype): assert arr.dtype == dtype assert exp.dtype == dtype - def test_sparseseries_roundtrip(self): - # GH 13999 - for kind in ['integer', 'block']: - for fill in [1, np.nan, 0]: - arr = SparseArray([np.nan, 1, np.nan, 2, 3], kind=kind, - fill_value=fill) - res = SparseArray(SparseSeries(arr)) - tm.assert_sp_array_equal(arr, res) - - arr = SparseArray([0, 0, 0, 1, 1, 2], dtype=np.int64, - kind=kind, fill_value=fill) - res = SparseArray(SparseSeries(arr), dtype=np.int64) - tm.assert_sp_array_equal(arr, res) - - res = SparseArray(SparseSeries(arr)) - tm.assert_sp_array_equal(arr, res) - - for fill in [True, False, np.nan]: - arr = SparseArray([True, False, True, True], dtype=np.bool, - kind=kind, fill_value=fill) - res = SparseArray(SparseSeries(arr)) - tm.assert_sp_array_equal(arr, res) - - res = SparseArray(SparseSeries(arr)) - tm.assert_sp_array_equal(arr, res) + @pytest.mark.parametrize("fill", [1, np.nan, 0]) + def test_sparse_series_round_trip(self, kind, fill): + # see gh-13999 + arr = SparseArray([np.nan, 1, np.nan, 2, 3], + kind=kind, fill_value=fill) + res = SparseArray(SparseSeries(arr)) + tm.assert_sp_array_equal(arr, res) + + arr = SparseArray([0, 0, 0, 1, 1, 2], dtype=np.int64, + kind=kind, fill_value=fill) + res = SparseArray(SparseSeries(arr), dtype=np.int64) + tm.assert_sp_array_equal(arr, res) + + res = SparseArray(SparseSeries(arr)) + tm.assert_sp_array_equal(arr, res) + + @pytest.mark.parametrize("fill", [True, False, np.nan]) + def test_sparse_series_round_trip2(self, kind, fill): + # see gh-13999 + arr = SparseArray([True, False, True, True], dtype=np.bool, + kind=kind, fill_value=fill) + res = SparseArray(SparseSeries(arr)) + tm.assert_sp_array_equal(arr, res) + + res = SparseArray(SparseSeries(arr)) + tm.assert_sp_array_equal(arr, res) def test_get_item(self): @@ -388,18 +394,16 @@ def test_astype(self): with tm.assert_raises_regex(ValueError, msg): arr.astype('i8') - def test_astype_all(self): + def test_astype_all(self, any_real_dtype): vals = np.array([1, 2, 3]) arr = SparseArray(vals, fill_value=1) + typ = np.dtype(any_real_dtype).type - types = [np.float64, np.float32, np.int64, - np.int32, np.int16, np.int8] - for typ in types: - res = arr.astype(typ) - assert res.dtype == typ - assert res.sp_values.dtype == typ + res = arr.astype(typ) + assert res.dtype == typ + assert res.sp_values.dtype == typ - tm.assert_numpy_array_equal(res.values, vals.astype(typ)) + tm.assert_numpy_array_equal(res.values, vals.astype(typ)) def test_set_fill_value(self): arr = SparseArray([1., np.nan, 2.], fill_value=np.nan) @@ -432,11 +436,13 @@ def test_set_fill_value(self): with tm.assert_raises_regex(ValueError, msg): arr.fill_value = np.nan - # invalid + @pytest.mark.parametrize("val", [[1, 2, 3], np.array([1, 2]), (1, 2, 3)]) + def test_set_fill_invalid_non_scalar(self, val): + arr = SparseArray([True, False, True], fill_value=False, dtype=np.bool) msg = "fill_value must be a scalar" - for val in [[1, 2, 3], np.array([1, 2]), (1, 2, 3)]: - with tm.assert_raises_regex(ValueError, msg): - arr.fill_value = val + + with tm.assert_raises_regex(ValueError, msg): + arr.fill_value = val def test_copy_shallow(self): arr2 = self.arr.copy(deep=False) @@ -538,9 +544,13 @@ def test_getslice_tuple(self): # check numpy compat dense[4:, :] - def test_binary_operators(self): + @pytest.mark.parametrize("op", ["add", "sub", "mul", + "truediv", "floordiv", "pow"]) + def test_binary_operators(self, op): + op = getattr(operator, op) data1 = np.random.randn(20) data2 = np.random.randn(20) + data1[::2] = np.nan data2[::3] = np.nan @@ -570,7 +580,7 @@ def _check_op(op, first, second): res4 = op(first, 4) assert isinstance(res4, SparseArray) - # ignore this if the actual op raises (e.g. pow) + # Ignore this if the actual op raises (e.g. pow). try: exp = op(first.values, 4) exp_fv = op(first.fill_value, 4) @@ -579,21 +589,26 @@ def _check_op(op, first, second): except ValueError: pass - def _check_inplace_op(op): - tmp = arr1.copy() - pytest.raises(NotImplementedError, op, tmp, arr2) + with np.errstate(all="ignore"): + for first_arr, second_arr in [(arr1, arr2), (farr1, farr2)]: + _check_op(op, first_arr, second_arr) - with np.errstate(all='ignore'): - bin_ops = [operator.add, operator.sub, operator.mul, - operator.truediv, operator.floordiv, operator.pow] - for op in bin_ops: - _check_op(op, arr1, arr2) - _check_op(op, farr1, farr2) + @pytest.mark.parametrize("op", ["iadd", "isub", "imul", + "ifloordiv", "ipow", + "itruediv"]) + def test_binary_operators_not_implemented(self, op): + data1 = np.random.randn(20) + data2 = np.random.randn(20) - inplace_ops = ['iadd', 'isub', 'imul', 'itruediv', 'ifloordiv', - 'ipow'] - for op in inplace_ops: - _check_inplace_op(getattr(operator, op)) + data1[::2] = np.nan + data2[::3] = np.nan + + arr1 = SparseArray(data1) + arr2 = SparseArray(data2) + + with np.errstate(all="ignore"): + with pytest.raises(NotImplementedError): + getattr(operator, op)(arr1, arr2) def test_pickle(self): def _check_roundtrip(obj): @@ -810,51 +825,26 @@ def test_numpy_sum(self): tm.assert_raises_regex(ValueError, msg, np.sum, SparseArray(data), out=out) - def test_cumsum(self): - non_null_data = np.array([1, 2, 3, 4, 5], dtype=float) - non_null_expected = SparseArray(non_null_data.cumsum()) - - null_data = np.array([1, 2, np.nan, 4, 5], dtype=float) - null_expected = SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0])) - - for data, expected in [ - (null_data, null_expected), - (non_null_data, non_null_expected) - ]: - out = SparseArray(data).cumsum() - tm.assert_sp_array_equal(out, expected) - - out = SparseArray(data, fill_value=np.nan).cumsum() - tm.assert_sp_array_equal(out, expected) - - out = SparseArray(data, fill_value=2).cumsum() - tm.assert_sp_array_equal(out, expected) - - axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid. - msg = "axis\\(={axis}\\) out of bounds".format(axis=axis) - with tm.assert_raises_regex(ValueError, msg): - SparseArray(data).cumsum(axis=axis) - - def test_numpy_cumsum(self): - non_null_data = np.array([1, 2, 3, 4, 5], dtype=float) - non_null_expected = SparseArray(non_null_data.cumsum()) - - null_data = np.array([1, 2, np.nan, 4, 5], dtype=float) - null_expected = SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0])) + @pytest.mark.parametrize("data,expected", [ + (np.array([1, 2, 3, 4, 5], dtype=float), # non-null data + SparseArray(np.array([1.0, 3.0, 6.0, 10.0, 15.0]))), + (np.array([1, 2, np.nan, 4, 5], dtype=float), # null data + SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0]))) + ]) + @pytest.mark.parametrize("numpy", [True, False]) + def test_cumsum(self, data, expected, numpy): + cumsum = np.cumsum if numpy else lambda s: s.cumsum() - for data, expected in [ - (null_data, null_expected), - (non_null_data, non_null_expected) - ]: - out = np.cumsum(SparseArray(data)) - tm.assert_sp_array_equal(out, expected) + out = cumsum(SparseArray(data)) + tm.assert_sp_array_equal(out, expected) - out = np.cumsum(SparseArray(data, fill_value=np.nan)) - tm.assert_sp_array_equal(out, expected) + out = cumsum(SparseArray(data, fill_value=np.nan)) + tm.assert_sp_array_equal(out, expected) - out = np.cumsum(SparseArray(data, fill_value=2)) - tm.assert_sp_array_equal(out, expected) + out = cumsum(SparseArray(data, fill_value=2)) + tm.assert_sp_array_equal(out, expected) + if numpy: # numpy compatibility checks. msg = "the 'dtype' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.cumsum, SparseArray(data), dtype=np.int64) @@ -862,6 +852,11 @@ def test_numpy_cumsum(self): msg = "the 'out' parameter is not supported" tm.assert_raises_regex(ValueError, msg, np.cumsum, SparseArray(data), out=out) + else: + axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid. + msg = "axis\\(={axis}\\) out of bounds".format(axis=axis) + with tm.assert_raises_regex(ValueError, msg): + SparseArray(data).cumsum(axis=axis) def test_mean(self): data = np.arange(10).astype(float) diff --git a/pandas/tests/tools/test_numeric.py b/pandas/tests/tools/test_numeric.py index 5321a5a93fa3d..43c7d0951bf6c 100644 --- a/pandas/tests/tools/test_numeric.py +++ b/pandas/tests/tools/test_numeric.py @@ -161,19 +161,15 @@ def test_all_nan(self): expected = pd.Series([np.nan, np.nan, np.nan]) tm.assert_series_equal(res, expected) - def test_type_check(self): + @pytest.mark.parametrize("errors", [None, "ignore", "raise", "coerce"]) + def test_type_check(self, errors): # see gh-11776 df = pd.DataFrame({"a": [1, -3.14, 7], "b": ["4", "5", "6"]}) + kwargs = dict(errors=errors) if errors is not None else dict() error_ctx = tm.assert_raises_regex(TypeError, "1-d array") - # Check default parameters. with error_ctx: - to_numeric(df) - - # Check each parameter value for `errors`. - for errors in ["ignore", "raise", "coerce"]: - with error_ctx: - to_numeric(df, errors=errors) + to_numeric(df, **kwargs) def test_scalar(self): assert pd.to_numeric(1) == 1
Title is self-explanatory.
https://api.github.com/repos/pandas-dev/pandas/pulls/22061
2018-07-26T08:35:34Z
2018-07-26T12:27:22Z
2018-07-26T12:27:22Z
2018-07-26T23:15:30Z
DOC: Reword doc for filepath_or_buffer in read_csv
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 486040fa52f35..2ae7622c13548 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -60,11 +60,16 @@ Parameters ---------- -filepath_or_buffer : str, pathlib.Path, py._path.local.LocalPath or any \ -object with a read() method (such as a file handle or StringIO) - The string could be a URL. Valid URL schemes include http, ftp, s3, and - file. For file URLs, a host is expected. For instance, a local file could - be file://localhost/path/to/table.csv +filepath_or_buffer : str, path object, or file-like object + Any valid string path is acceptable. The string could be a URL. Valid + URL schemes include http, ftp, s3, and file. For file URLs, a host is + expected. A local file could be: file://localhost/path/to/table.csv. + + If you want to pass in a path object, pandas accepts either + ``pathlib.Path`` or ``py._path.local.LocalPath``. + + By file-like object, we refer to objects with a ``read()`` method, such as + a file handler (e.g. via builtin ``open`` function) or ``StringIO``. %s delim_whitespace : boolean, default False Specifies whether or not whitespace (e.g. ``' '`` or ``'\t'``) will be
Shortens dtype description following colon and moves it to a more expanded parameter description. Closes #22057. cc @WillAyd
https://api.github.com/repos/pandas-dev/pandas/pulls/22058
2018-07-25T23:21:55Z
2018-07-27T08:28:44Z
2018-07-27T08:28:44Z
2018-07-27T08:40:17Z
BUG: fix raise of TypeError when subtracting timedelta array
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 66b6923ef13e4..777cb42080f98 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -642,6 +642,7 @@ Timedelta - Bug in :class:`Series` with numeric dtype when adding or subtracting an an array or ``Series`` with ``timedelta64`` dtype (:issue:`22390`) - Bug in :class:`Index` with numeric dtype when multiplying or dividing an array with dtype ``timedelta64`` (:issue:`22390`) - Bug in :class:`TimedeltaIndex` incorrectly allowing indexing with ``Timestamp`` object (:issue:`20464`) +- Fixed bug where subtracting :class:`Timedelta` from an object-dtyped array would raise ``TypeError`` (:issue:`21980`) - - diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 9b13ef5982396..9c8be1901d1dc 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -541,10 +541,12 @@ def _binary_op_method_timedeltalike(op, name): elif hasattr(other, 'dtype'): # nd-array like - if other.dtype.kind not in ['m', 'M']: - # raise rathering than letting numpy return wrong answer + if other.dtype.kind in ['m', 'M']: + return op(self.to_timedelta64(), other) + elif other.dtype.kind == 'O': + return np.array([op(self, x) for x in other]) + else: return NotImplemented - return op(self.to_timedelta64(), other) elif not _validate_ops_compat(other): return NotImplemented diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 9636c92ec22d5..fce1ef29235cc 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -200,6 +200,57 @@ def test_td_rsub_numeric_raises(self): with pytest.raises(TypeError): 2.0 - td + def test_td_sub_timedeltalike_object_dtype_array(self): + # GH 21980 + arr = np.array([Timestamp('20130101 9:01'), + Timestamp('20121230 9:02')]) + exp = np.array([Timestamp('20121231 9:01'), + Timestamp('20121229 9:02')]) + res = arr - pd.Timedelta('1D') + tm.assert_numpy_array_equal(res, exp) + + def test_td_sub_mixed_most_timedeltalike_object_dtype_array(self): + # GH 21980 + now = pd.Timestamp.now() + arr = np.array([now, + pd.Timedelta('1D'), + np.timedelta64(2, 'h')]) + exp = np.array([now - pd.Timedelta('1D'), + pd.Timedelta('0D'), + np.timedelta64(2, 'h') - pd.Timedelta('1D')]) + res = arr - pd.Timedelta('1D') + tm.assert_numpy_array_equal(res, exp) + + def test_td_rsub_mixed_most_timedeltalike_object_dtype_array(self): + # GH 21980 + now = pd.Timestamp.now() + arr = np.array([now, + pd.Timedelta('1D'), + np.timedelta64(2, 'h')]) + with pytest.raises(TypeError): + pd.Timedelta('1D') - arr + + @pytest.mark.parametrize('op', [operator.add, ops.radd]) + def test_td_add_timedeltalike_object_dtype_array(self, op): + # GH 21980 + arr = np.array([Timestamp('20130101 9:01'), + Timestamp('20121230 9:02')]) + exp = np.array([Timestamp('20130102 9:01'), + Timestamp('20121231 9:02')]) + res = op(arr, pd.Timedelta('1D')) + tm.assert_numpy_array_equal(res, exp) + + @pytest.mark.parametrize('op', [operator.add, ops.radd]) + def test_td_add_mixed_timedeltalike_object_dtype_array(self, op): + # GH 21980 + now = pd.Timestamp.now() + arr = np.array([now, + pd.Timedelta('1D')]) + exp = np.array([now + pd.Timedelta('1D'), + pd.Timedelta('2D')]) + res = op(arr, pd.Timedelta('1D')) + tm.assert_numpy_array_equal(res, exp) + class TestTimedeltaMultiplicationDivision(object): """ @@ -616,3 +667,17 @@ def test_rdivmod_invalid(self): with pytest.raises(TypeError): divmod(np.array([22, 24]), td) + + @pytest.mark.parametrize('op', [ + operator.mul, + ops.rmul, + operator.truediv, + ops.rdiv, + ops.rsub]) + @pytest.mark.parametrize('arr', [ + np.array([Timestamp('20130101 9:01'), Timestamp('20121230 9:02')]), + np.array([pd.Timestamp.now(), pd.Timedelta('1D')]) + ]) + def test_td_op_timedelta_timedeltalike_array(self, op, arr): + with pytest.raises(TypeError): + op(arr, pd.Timedelta('1D'))
closes #21980 - [x] closes #xxxx - [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/22054
2018-07-25T19:49:53Z
2018-09-18T13:25:26Z
2018-09-18T13:25:25Z
2018-09-18T13:25:28Z
BUG: Matplotlib scatter datetime
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 61119089fdb42..ceb03ce06a0ec 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -629,8 +629,8 @@ 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`, :issue:`10678`, and :issue:`20455`) -- +- 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`, :issue:`10678`, and :issue:`20455`) +- Bug in plotting a Series with datetimes using :func:`matplotlib.axes.Axes.scatter` (:issue:`22039`) Groupby/Resample/Rolling ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/plotting/_converter.py b/pandas/plotting/_converter.py index 3bb0b98851234..96ea8a542a451 100644 --- a/pandas/plotting/_converter.py +++ b/pandas/plotting/_converter.py @@ -320,7 +320,11 @@ def try_parse(values): return values elif isinstance(values, compat.string_types): return try_parse(values) - elif isinstance(values, (list, tuple, np.ndarray, Index)): + elif isinstance(values, (list, tuple, np.ndarray, Index, ABCSeries)): + if isinstance(values, ABCSeries): + # https://github.com/matplotlib/matplotlib/issues/11391 + # Series was skipped. Convert to DatetimeIndex to get asi8 + values = Index(values) if isinstance(values, Index): values = values.values if not isinstance(values, np.ndarray): diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index e3d502cd373e4..0abe82d138e5e 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1483,6 +1483,17 @@ def test_add_matplotlib_datetime64(self): l1, l2 = ax.lines tm.assert_numpy_array_equal(l1.get_xydata(), l2.get_xydata()) + def test_matplotlib_scatter_datetime64(self): + # https://github.com/matplotlib/matplotlib/issues/11391 + df = DataFrame(np.random.RandomState(0).rand(10, 2), + columns=["x", "y"]) + df["time"] = date_range("2018-01-01", periods=10, freq="D") + fig, ax = self.plt.subplots() + ax.scatter(x="time", y="y", data=df) + fig.canvas.draw() + label = ax.get_xticklabels()[0] + assert label.get_text() == '2017-12-12' + def _check_plot_works(f, freq=None, series=None, *args, **kwargs): import matplotlib.pyplot as plt
xref https://github.com/matplotlib/matplotlib/issues/11391
https://api.github.com/repos/pandas-dev/pandas/pulls/22039
2018-07-24T15:15:59Z
2018-08-02T10:42:51Z
2018-08-02T10:42:51Z
2018-08-02T10:42:54Z
Raised value error on incorrect na_option
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 38f334762fa88..104f7e0550f60 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7480,6 +7480,10 @@ def rank(self, axis=0, method='average', numeric_only=None, msg = "rank does not make sense when ndim > 2" raise NotImplementedError(msg) + if na_option not in {'keep', 'top', 'bottom'}: + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + raise ValueError(msg) + def ranker(data): ranks = algos.rank(data.values, axis=axis, method=method, ascending=ascending, na_option=na_option, diff --git a/pandas/tests/frame/test_rank.py b/pandas/tests/frame/test_rank.py index a1210f1ed54e4..c5d771f52b6ac 100644 --- a/pandas/tests/frame/test_rank.py +++ b/pandas/tests/frame/test_rank.py @@ -191,6 +191,16 @@ def test_rank_na_option(self): tm.assert_numpy_array_equal(ranks0.values, exp0) tm.assert_numpy_array_equal(ranks1.values, exp1) + # bad values throw error + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + + with tm.assert_raises_regex(ValueError, msg): + self.frame.rank(na_option='bad', ascending=False) + + # invalid type + with tm.assert_raises_regex(ValueError, msg): + self.frame.rank(na_option=True, ascending=False) + def test_rank_axis(self): # check if using axes' names gives the same result df = DataFrame([[2, 1], [4, 3]]) diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index 203c3c73bec94..0628f9c79a154 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -248,6 +248,17 @@ def test_rank_avg_even_vals(): def test_rank_object_raises(ties_method, ascending, na_option, pct, vals): df = DataFrame({'key': ['foo'] * 5, 'val': vals}) + + with tm.assert_raises_regex(TypeError, "not callable"): + df.groupby('key').rank(method=ties_method, + ascending=ascending, + na_option='bad', pct=pct) + + with tm.assert_raises_regex(TypeError, "not callable"): + df.groupby('key').rank(method=ties_method, + ascending=ascending, + na_option=True, pct=pct) + with tm.assert_raises_regex(TypeError, "not callable"): df.groupby('key').rank(method=ties_method, ascending=ascending, diff --git a/pandas/tests/series/test_rank.py b/pandas/tests/series/test_rank.py index 004e42e14cb93..d0e001cbfcd88 100644 --- a/pandas/tests/series/test_rank.py +++ b/pandas/tests/series/test_rank.py @@ -183,6 +183,16 @@ def test_rank_categorical(self): exp_keep ) + # Test invalid values for na_option + msg = "na_option must be one of 'keep', 'top', or 'bottom'" + + with tm.assert_raises_regex(ValueError, msg): + na_ser.rank(na_option='bad', ascending=False) + + # invalid type + with tm.assert_raises_regex(ValueError, msg): + na_ser.rank(na_option=True, ascending=False) + # Test with pct=True na_ser = Series(['first', 'second', 'third', 'fourth', np.NaN]).astype( CategoricalDtype(['first', 'second', 'third', 'fourth'], True))
- [X] closes #19499 - [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/22037
2018-07-24T06:13:29Z
2018-07-25T19:12:54Z
2018-07-25T19:12:54Z
2018-07-25T19:12:58Z
PERF/REF: improve performance of Series.searchsorted, PandasArray.searchsorted, collect functionality
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index f7d0083b86a01..3303483c50e20 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -124,6 +124,25 @@ def time_dropna(self, dtype): self.s.dropna() +class SearchSorted(object): + + goal_time = 0.2 + params = ['int8', 'int16', 'int32', 'int64', + 'uint8', 'uint16', 'uint32', 'uint64', + 'float16', 'float32', 'float64', + 'str'] + param_names = ['dtype'] + + def setup(self, dtype): + N = 10**5 + data = np.array([1] * N + [2] * N + [3] * N).astype(dtype) + self.s = Series(data) + + def time_searchsorted(self, dtype): + key = '2' if dtype == 'str' else 2 + self.s.searchsorted(key) + + class Map(object): params = ['dict', 'Series'] diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 6e225185ecf84..bc4778a3cce2d 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -64,7 +64,8 @@ Performance Improvements - Significant speedup in `SparseArray` initialization that benefits most operations, fixing performance regression introduced in v0.20.0 (:issue:`24985`) - `DataFrame.to_stata()` is now faster when outputting data with any string or non-native endian columns (:issue:`25045`) -- +- Improved performance of :meth:`Series.searchsorted`. The speedup is especially large when the dtype is + int8/int16/int32 and the searched key is within the integer bounds for the dtype (:issue:`22034`) .. _whatsnew_0250.bug_fixes: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index c5c8f47ad6dba..b056a357d0a51 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -19,7 +19,7 @@ ensure_float64, ensure_int64, ensure_object, ensure_platform_int, ensure_uint64, is_array_like, is_bool_dtype, is_categorical_dtype, is_complex_dtype, is_datetime64_any_dtype, is_datetime64tz_dtype, - is_datetimelike, is_extension_array_dtype, is_float_dtype, + is_datetimelike, is_extension_array_dtype, is_float_dtype, is_integer, is_integer_dtype, is_interval_dtype, is_list_like, is_numeric_dtype, is_object_dtype, is_period_dtype, is_scalar, is_signed_integer_dtype, is_sparse, is_timedelta64_dtype, is_unsigned_integer_dtype, @@ -1724,6 +1724,89 @@ def func(arr, indexer, out, fill_value=np.nan): return out +# ------------ # +# searchsorted # +# ------------ # + +def searchsorted(arr, value, side="left", sorter=None): + """ + Find indices where elements should be inserted to maintain order. + + .. versionadded:: 0.25.0 + + Find the indices into a sorted array `arr` (a) such that, if the + corresponding elements in `value` were inserted before the indices, + the order of `arr` would be preserved. + + Assuming that `arr` is sorted: + + ====== ================================ + `side` returned index `i` satisfies + ====== ================================ + left ``arr[i-1] < value <= self[i]`` + right ``arr[i-1] <= value < self[i]`` + ====== ================================ + + Parameters + ---------- + arr: array-like + Input array. If `sorter` is None, then it must be sorted in + ascending order, otherwise `sorter` must be an array of indices + that sort it. + value : array_like + Values to insert into `arr`. + side : {'left', 'right'}, optional + If 'left', the index of the first suitable location found is given. + If 'right', return the last such index. If there is no suitable + index, return either 0 or N (where N is the length of `self`). + sorter : 1-D array_like, optional + Optional array of integer indices that sort array a into ascending + order. They are typically the result of argsort. + + Returns + ------- + array of ints + Array of insertion points with the same shape as `value`. + + See Also + -------- + numpy.searchsorted : Similar method from NumPy. + """ + if sorter is not None: + sorter = ensure_platform_int(sorter) + + if isinstance(arr, np.ndarray) and is_integer_dtype(arr) and ( + is_integer(value) or is_integer_dtype(value)): + from .arrays.array_ import array + # if `arr` and `value` have different dtypes, `arr` would be + # recast by numpy, causing a slow search. + # Before searching below, we therefore try to give `value` the + # same dtype as `arr`, while guarding against integer overflows. + iinfo = np.iinfo(arr.dtype.type) + value_arr = np.array([value]) if is_scalar(value) else np.array(value) + if (value_arr >= iinfo.min).all() and (value_arr <= iinfo.max).all(): + # value within bounds, so no overflow, so can convert value dtype + # to dtype of arr + dtype = arr.dtype + else: + dtype = value_arr.dtype + + if is_scalar(value): + value = dtype.type(value) + else: + value = array(value, dtype=dtype) + elif not (is_object_dtype(arr) or is_numeric_dtype(arr) or + is_categorical_dtype(arr)): + from pandas.core.series import Series + # E.g. if `arr` is an array with dtype='datetime64[ns]' + # and `value` is a pd.Timestamp, we may need to convert value + value_ser = Series(value)._values + value = value_ser[0] if is_scalar(value) else value_ser + + result = arr.searchsorted(value, side=side, sorter=sorter) + return result + + # ---- # # diff # # ---- # diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 7aaefef3d03e5..e770281596134 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -555,17 +555,17 @@ def searchsorted(self, value, side="left", sorter=None): .. versionadded:: 0.24.0 Find the indices into a sorted array `self` (a) such that, if the - corresponding elements in `v` were inserted before the indices, the - order of `self` would be preserved. + corresponding elements in `value` were inserted before the indices, + the order of `self` would be preserved. - Assuming that `a` is sorted: + Assuming that `self` is sorted: - ====== ============================ + ====== ================================ `side` returned index `i` satisfies - ====== ============================ - left ``self[i-1] < v <= self[i]`` - right ``self[i-1] <= v < self[i]`` - ====== ============================ + ====== ================================ + left ``self[i-1] < value <= self[i]`` + right ``self[i-1] <= value < self[i]`` + ====== ================================ Parameters ---------- @@ -581,7 +581,7 @@ def searchsorted(self, value, side="left", sorter=None): Returns ------- - indices : array of ints + array of ints Array of insertion points with the same shape as `value`. See Also diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 791ff44303e96..8e2ab586cacb6 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -4,6 +4,7 @@ from pandas._libs import lib from pandas.compat.numpy import function as nv +from pandas.util._decorators import Appender from pandas.util._validators import validate_fillna_kwargs from pandas.core.dtypes.dtypes import ExtensionDtype @@ -12,6 +13,7 @@ from pandas import compat from pandas.core import nanops +from pandas.core.algorithms import searchsorted from pandas.core.missing import backfill_1d, pad_1d from .base import ExtensionArray, ExtensionOpsMixin @@ -423,6 +425,11 @@ def to_numpy(self, dtype=None, copy=False): return result + @Appender(ExtensionArray.searchsorted.__doc__) + def searchsorted(self, value, side='left', sorter=None): + return searchsorted(self.to_numpy(), value, + side=side, sorter=sorter) + # ------------------------------------------------------------------------ # Ops diff --git a/pandas/core/base.py b/pandas/core/base.py index 7fdc64a8d9f85..f896596dd5216 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1522,11 +1522,11 @@ def factorize(self, sort=False, na_sentinel=-1): array([3]) """) - @Substitution(klass='IndexOpsMixin') + @Substitution(klass='Index') @Appender(_shared_docs['searchsorted']) def searchsorted(self, value, side='left', sorter=None): - # needs coercion on the key (DatetimeIndex does already) - return self._values.searchsorted(value, side=side, sorter=sorter) + return algorithms.searchsorted(self._values, value, + side=side, sorter=sorter) def drop_duplicates(self, keep='first', inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') diff --git a/pandas/core/series.py b/pandas/core/series.py index a5dfe8d43c336..ad7c6af21f637 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2392,12 +2392,8 @@ def __rmatmul__(self, other): @Substitution(klass='Series') @Appender(base._shared_docs['searchsorted']) def searchsorted(self, value, side='left', sorter=None): - if sorter is not None: - sorter = ensure_platform_int(sorter) - result = self._values.searchsorted(Series(value)._values, - side=side, sorter=sorter) - - return result[0] if is_scalar(value) else result + return algorithms.searchsorted(self._values, value, + side=side, sorter=sorter) # ------------------------------------------------------------------- # Combination diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index 9fea1989e46df..b68ec2bf348b4 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -9,6 +9,7 @@ import pandas as pd from pandas.api.extensions import register_extension_dtype +from pandas.api.types import is_scalar from pandas.core.arrays import PandasArray, integer_array, period_array from pandas.tests.extension.decimal import ( DecimalArray, DecimalDtype, to_decimal) @@ -254,3 +255,51 @@ def test_array_not_registered(registry_without_decimal): result = pd.array(data, dtype=DecimalDtype) expected = DecimalArray._from_sequence(data) tm.assert_equal(result, expected) + + +class TestArrayAnalytics(object): + def test_searchsorted(self, string_dtype): + arr = pd.array(['a', 'b', 'c'], dtype=string_dtype) + + result = arr.searchsorted('a', side='left') + assert is_scalar(result) + assert result == 0 + + result = arr.searchsorted('a', side='right') + assert is_scalar(result) + assert result == 1 + + def test_searchsorted_numeric_dtypes_scalar(self, any_real_dtype): + arr = pd.array([1, 3, 90], dtype=any_real_dtype) + result = arr.searchsorted(30) + assert is_scalar(result) + assert result == 2 + + result = arr.searchsorted([30]) + expected = np.array([2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + def test_searchsorted_numeric_dtypes_vector(self, any_real_dtype): + arr = pd.array([1, 3, 90], dtype=any_real_dtype) + result = arr.searchsorted([2, 30]) + expected = np.array([1, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize('arr, val', [ + [pd.date_range('20120101', periods=10, freq='2D'), + pd.Timestamp('20120102')], + [pd.date_range('20120101', periods=10, freq='2D', tz='Asia/Hong_Kong'), + pd.Timestamp('20120102', tz='Asia/Hong_Kong')], + [pd.timedelta_range(start='1 day', end='10 days', periods=10), + pd.Timedelta('2 days')]]) + def test_search_sorted_datetime64_scalar(self, arr, val): + arr = pd.array(arr) + result = arr.searchsorted(val) + assert is_scalar(result) + assert result == 1 + + def test_searchsorted_sorter(self, any_real_dtype): + arr = pd.array([3, 1, 2], dtype=any_real_dtype) + result = arr.searchsorted([0, 3], sorter=np.argsort(arr)) + expected = np.array([0, 2], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected)
- [x] closes #14565 - [x] ASV's added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Numpy's searchsorted doesn't like being given values to search for that aren't of the same type as the array being searched. By ensuring that the input value has the same dtype as the underlying array, the search is sped up significantly. ```python >>> n = 1_000_000 >>> s = pd.Series(([1] * n + [2] * n + [3] * n), dtype='int8') >>> %timeit s.searchsorted(1) # python int 15.2 ms # master 9.75 µs # this PR ``` ## ASV results ``` before after ratio [b9754556] [fd6c117b] - 93.9±9μs 10.9±0μs 0.12 series_methods.SearchSorted.time_searchsorted('int64') - 95.4±0μs 10.9±2μs 0.11 series_methods.SearchSorted.time_searchsorted('float64') - 140±10μs 10.7±0.4μs 0.08 series_methods.SearchSorted.time_searchsorted('str') - 1.34±0.1ms 10.8±0.3μs 0.01 series_methods.SearchSorted.time_searchsorted('uint16') - 1.52±0.03ms 10.7±0μs 0.01 series_methods.SearchSorted.time_searchsorted('int16') - 1.79±0.1ms 12.5±2μs 0.01 series_methods.SearchSorted.time_searchsorted('int8') - 1.46±0.1ms 10.2±0.8μs 0.01 series_methods.SearchSorted.time_searchsorted('int32') - 1.46±0ms 9.54±1μs 0.01 series_methods.SearchSorted.time_searchsorted('uint8') - 1.46±0.1ms 9.38±2μs 0.01 series_methods.SearchSorted.time_searchsorted('float32') - 1.71±0.2ms 10.4±0.9μs 0.01 series_methods.SearchSorted.time_searchsorted('uint32') - 1.82±0.1ms 10.7±0μs 0.01 series_methods.SearchSorted.time_searchsorted('uint64') - 2.14±0.04ms 10.7±0μs 0.00 series_methods.SearchSorted.time_searchsorted('float16') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. ``` The improventents are largest when the dtype isn't int64 or float64, but for those cases the improvement is also significant (10x).
https://api.github.com/repos/pandas-dev/pandas/pulls/22034
2018-07-24T01:15:02Z
2019-02-24T03:40:08Z
2019-02-24T03:40:08Z
2019-02-24T08:14:12Z
REF: move common arithmetic ops from Integer/FloatingArray to NumericArray
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index 4aed39d7edb92..890a0cd5e4a56 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -13,9 +13,7 @@ from pandas.core.dtypes.common import ( is_bool_dtype, is_datetime64_dtype, - is_float, is_float_dtype, - is_integer, is_integer_dtype, is_list_like, is_object_dtype, @@ -28,7 +26,8 @@ from pandas.core.ops import invalid_comparison from pandas.core.tools.numeric import to_numeric -from .masked import BaseMaskedArray, BaseMaskedDtype +from .masked import BaseMaskedDtype +from .numeric import NumericArray if TYPE_CHECKING: import pyarrow @@ -199,7 +198,7 @@ def coerce_to_array( return values, mask -class FloatingArray(BaseMaskedArray): +class FloatingArray(NumericArray): """ Array of floating (optional missing) values. @@ -478,71 +477,6 @@ def _maybe_mask_result(self, result, mask, other, op_name: str): return type(self)(result, mask, copy=False) - def _arith_method(self, other, op): - from pandas.arrays import IntegerArray - - omask = None - - if getattr(other, "ndim", 0) > 1: - raise NotImplementedError("can only perform ops with 1-d structures") - - if isinstance(other, (IntegerArray, FloatingArray)): - other, omask = other._data, other._mask - - elif is_list_like(other): - other = np.asarray(other) - if other.ndim > 1: - raise NotImplementedError("can only perform ops with 1-d structures") - if len(self) != len(other): - raise ValueError("Lengths must match") - if not (is_float_dtype(other) or is_integer_dtype(other)): - raise TypeError("can only perform ops with numeric values") - - else: - if not (is_float(other) or is_integer(other) or other is libmissing.NA): - raise TypeError("can only perform ops with numeric values") - - if omask is None: - mask = self._mask.copy() - if other is libmissing.NA: - mask |= True - else: - mask = self._mask | omask - - if op.__name__ == "pow": - # 1 ** x is 1. - mask = np.where((self._data == 1) & ~self._mask, False, mask) - # x ** 0 is 1. - if omask is not None: - mask = np.where((other == 0) & ~omask, False, mask) - elif other is not libmissing.NA: - mask = np.where(other == 0, False, mask) - - elif op.__name__ == "rpow": - # 1 ** x is 1. - if omask is not None: - mask = np.where((other == 1) & ~omask, False, mask) - elif other is not libmissing.NA: - mask = np.where(other == 1, False, mask) - # x ** 0 is 1. - mask = np.where((self._data == 0) & ~self._mask, False, mask) - - if other is libmissing.NA: - result = np.ones_like(self._data) - else: - with np.errstate(all="ignore"): - result = op(self._data, other) - - # divmod returns a tuple - if op.__name__ == "divmod": - div, mod = result - return ( - self._maybe_mask_result(div, mask, other, "floordiv"), - self._maybe_mask_result(mod, mask, other, "mod"), - ) - - return self._maybe_mask_result(result, mask, other, op.__name__) - _dtype_docstring = """ An ExtensionDtype for {dtype} data. diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 66d92238a9b08..fa427e94fe08f 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -1,11 +1,10 @@ -from datetime import timedelta import numbers from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Type, Union import warnings import numpy as np -from pandas._libs import Timedelta, iNaT, lib, missing as libmissing +from pandas._libs import iNaT, lib, missing as libmissing from pandas._typing import ArrayLike, DtypeObj from pandas.compat.numpy import function as nv from pandas.util._decorators import cache_readonly @@ -16,7 +15,6 @@ is_datetime64_dtype, is_float, is_float_dtype, - is_integer, is_integer_dtype, is_list_like, is_object_dtype, @@ -29,6 +27,7 @@ from pandas.core.tools.numeric import to_numeric from .masked import BaseMaskedArray, BaseMaskedDtype +from .numeric import NumericArray if TYPE_CHECKING: import pyarrow @@ -263,7 +262,7 @@ def coerce_to_array( return values, mask -class IntegerArray(BaseMaskedArray): +class IntegerArray(NumericArray): """ Array of integer (optional missing) values. @@ -494,7 +493,7 @@ def _values_for_argsort(self) -> np.ndarray: return data def _cmp_method(self, other, op): - from pandas.core.arrays import BaseMaskedArray, BooleanArray + from pandas.core.arrays import BooleanArray mask = None @@ -538,75 +537,6 @@ def _cmp_method(self, other, op): return BooleanArray(result, mask) - def _arith_method(self, other, op): - from pandas.core.arrays import FloatingArray - - op_name = op.__name__ - omask = None - - if getattr(other, "ndim", 0) > 1: - raise NotImplementedError("can only perform ops with 1-d structures") - - if isinstance(other, (IntegerArray, FloatingArray)): - other, omask = other._data, other._mask - - elif is_list_like(other): - other = np.asarray(other) - if other.ndim > 1: - raise NotImplementedError("can only perform ops with 1-d structures") - if len(self) != len(other): - raise ValueError("Lengths must match") - if not (is_float_dtype(other) or is_integer_dtype(other)): - raise TypeError("can only perform ops with numeric values") - - elif isinstance(other, (timedelta, np.timedelta64)): - other = Timedelta(other) - - else: - if not (is_float(other) or is_integer(other) or other is libmissing.NA): - raise TypeError("can only perform ops with numeric values") - - if omask is None: - mask = self._mask.copy() - if other is libmissing.NA: - mask |= True - else: - mask = self._mask | omask - - if op_name == "pow": - # 1 ** x is 1. - mask = np.where((self._data == 1) & ~self._mask, False, mask) - # x ** 0 is 1. - if omask is not None: - mask = np.where((other == 0) & ~omask, False, mask) - elif other is not libmissing.NA: - mask = np.where(other == 0, False, mask) - - elif op_name == "rpow": - # 1 ** x is 1. - if omask is not None: - mask = np.where((other == 1) & ~omask, False, mask) - elif other is not libmissing.NA: - mask = np.where(other == 1, False, mask) - # x ** 0 is 1. - mask = np.where((self._data == 0) & ~self._mask, False, mask) - - if other is libmissing.NA: - result = np.ones_like(self._data) - else: - with np.errstate(all="ignore"): - result = op(self._data, other) - - # divmod returns a tuple - if op_name == "divmod": - div, mod = result - return ( - self._maybe_mask_result(div, mask, other, "floordiv"), - self._maybe_mask_result(mod, mask, other, "mod"), - ) - - return self._maybe_mask_result(result, mask, other, op_name) - def sum(self, *, skipna=True, min_count=0, **kwargs): nv.validate_sum((), kwargs) return super()._reduce("sum", skipna=skipna, min_count=min_count) diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py new file mode 100644 index 0000000000000..5447a84c86ac1 --- /dev/null +++ b/pandas/core/arrays/numeric.py @@ -0,0 +1,92 @@ +import datetime + +import numpy as np + +from pandas._libs import Timedelta, missing as libmissing +from pandas.errors import AbstractMethodError + +from pandas.core.dtypes.common import ( + is_float, + is_float_dtype, + is_integer, + is_integer_dtype, + is_list_like, +) + +from .masked import BaseMaskedArray + + +class NumericArray(BaseMaskedArray): + """ + Base class for IntegerArray and FloatingArray. + """ + + def _maybe_mask_result(self, result, mask, other, op_name: str): + raise AbstractMethodError(self) + + def _arith_method(self, other, op): + op_name = op.__name__ + omask = None + + if getattr(other, "ndim", 0) > 1: + raise NotImplementedError("can only perform ops with 1-d structures") + + if isinstance(other, NumericArray): + other, omask = other._data, other._mask + + elif is_list_like(other): + other = np.asarray(other) + if other.ndim > 1: + raise NotImplementedError("can only perform ops with 1-d structures") + if len(self) != len(other): + raise ValueError("Lengths must match") + if not (is_float_dtype(other) or is_integer_dtype(other)): + raise TypeError("can only perform ops with numeric values") + + elif isinstance(other, (datetime.timedelta, np.timedelta64)): + other = Timedelta(other) + + else: + if not (is_float(other) or is_integer(other) or other is libmissing.NA): + raise TypeError("can only perform ops with numeric values") + + if omask is None: + mask = self._mask.copy() + if other is libmissing.NA: + mask |= True + else: + mask = self._mask | omask + + if op_name == "pow": + # 1 ** x is 1. + mask = np.where((self._data == 1) & ~self._mask, False, mask) + # x ** 0 is 1. + if omask is not None: + mask = np.where((other == 0) & ~omask, False, mask) + elif other is not libmissing.NA: + mask = np.where(other == 0, False, mask) + + elif op_name == "rpow": + # 1 ** x is 1. + if omask is not None: + mask = np.where((other == 1) & ~omask, False, mask) + elif other is not libmissing.NA: + mask = np.where(other == 1, False, mask) + # x ** 0 is 1. + mask = np.where((self._data == 0) & ~self._mask, False, mask) + + if other is libmissing.NA: + result = np.ones_like(self._data) + else: + with np.errstate(all="ignore"): + result = op(self._data, other) + + # divmod returns a tuple + if op_name == "divmod": + div, mod = result + return ( + self._maybe_mask_result(div, mask, other, "floordiv"), + self._maybe_mask_result(mod, mask, other, "mod"), + ) + + return self._maybe_mask_result(result, mask, other, op_name)
xref https://github.com/pandas-dev/pandas/issues/38110
https://api.github.com/repos/pandas-dev/pandas/pulls/38290
2020-12-04T14:32:41Z
2020-12-04T23:30:52Z
2020-12-04T23:30:52Z
2020-12-05T09:23:06Z
CLN: remove internal usage of integer_array()
diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index e5258a6aecd30..93f679d13b33c 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -7,7 +7,7 @@ from pandas.core.arrays.categorical import Categorical from pandas.core.arrays.datetimes import DatetimeArray from pandas.core.arrays.floating import FloatingArray -from pandas.core.arrays.integer import IntegerArray, integer_array +from pandas.core.arrays.integer import IntegerArray from pandas.core.arrays.interval import IntervalArray from pandas.core.arrays.masked import BaseMaskedArray from pandas.core.arrays.numpy_ import PandasArray, PandasDtype @@ -26,7 +26,6 @@ "DatetimeArray", "FloatingArray", "IntegerArray", - "integer_array", "IntervalArray", "PandasArray", "PandasDtype", diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index fa427e94fe08f..6a19a3aea3eee 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -121,29 +121,6 @@ def __from_arrow__( return IntegerArray._concat_same_type(results) -def integer_array(values, dtype=None, copy: bool = False) -> "IntegerArray": - """ - Infer and return an integer array of the values. - - Parameters - ---------- - values : 1D list-like - dtype : dtype, optional - dtype to coerce - copy : bool, default False - - Returns - ------- - IntegerArray - - Raises - ------ - TypeError if incompatible types - """ - values, mask = coerce_to_array(values, dtype=dtype, copy=copy) - return IntegerArray(values, mask) - - def safe_cast(values, dtype, copy: bool): """ Safely cast the values to the dtype if they @@ -360,7 +337,8 @@ def __abs__(self): def _from_sequence( cls, scalars, *, dtype=None, copy: bool = False ) -> "IntegerArray": - return integer_array(scalars, dtype=dtype, copy=copy) + values, mask = coerce_to_array(scalars, dtype=dtype, copy=copy) + return IntegerArray(values, mask) @classmethod def _from_sequence_of_strings( diff --git a/pandas/tests/arrays/integer/conftest.py b/pandas/tests/arrays/integer/conftest.py index 994fccf837f08..080ca180337f0 100644 --- a/pandas/tests/arrays/integer/conftest.py +++ b/pandas/tests/arrays/integer/conftest.py @@ -1,7 +1,7 @@ import numpy as np import pytest -from pandas.core.arrays import integer_array +import pandas as pd from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, @@ -32,7 +32,7 @@ def dtype(request): @pytest.fixture def data(dtype): - return integer_array( + return pd.array( list(range(8)) + [np.nan] + list(range(10, 98)) + [np.nan] + [99, 100], dtype=dtype, ) @@ -40,7 +40,7 @@ def data(dtype): @pytest.fixture def data_missing(dtype): - return integer_array([np.nan, 1], dtype=dtype) + return pd.array([np.nan, 1], dtype=dtype) @pytest.fixture(params=["data", "data_missing"]) diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 617cb6407d857..8ba984e649e35 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -7,7 +7,7 @@ import pandas as pd import pandas._testing as tm -from pandas.core.arrays import FloatingArray, integer_array +from pandas.core.arrays import FloatingArray import pandas.core.ops as ops # Basic test for the arithmetic array ops @@ -131,10 +131,10 @@ def test_pow_scalar(): def test_pow_array(): - a = integer_array([0, 0, 0, 1, 1, 1, None, None, None]) - b = integer_array([0, 1, None, 0, 1, None, 0, 1, None]) + a = pd.array([0, 0, 0, 1, 1, 1, None, None, None]) + b = pd.array([0, 1, None, 0, 1, None, 0, 1, None]) result = a ** b - expected = integer_array([1, 0, None, 1, 1, 1, 1, None, None]) + expected = pd.array([1, 0, None, 1, 1, 1, 1, None, None]) tm.assert_extension_array_equal(result, expected) @@ -149,7 +149,7 @@ def test_rpow_one_to_na(): @pytest.mark.parametrize("other", [0, 0.5]) def test_numpy_zero_dim_ndarray(other): - arr = integer_array([1, None, 2]) + arr = pd.array([1, None, 2]) result = arr + np.array(other) expected = arr + other tm.assert_equal(result, expected) @@ -265,7 +265,7 @@ def test_reduce_to_float(op): { "A": ["a", "b", "b"], "B": [1, None, 3], - "C": integer_array([1, None, 3], dtype="Int64"), + "C": pd.array([1, None, 3], dtype="Int64"), } ) @@ -277,10 +277,7 @@ def test_reduce_to_float(op): result = getattr(df.groupby("A"), op)() expected = pd.DataFrame( - { - "B": np.array([1.0, 3.0]), - "C": pd.array([1, 3], dtype="Float64"), - }, + {"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Float64")}, index=pd.Index(["a", "b"], name="A"), ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/arrays/integer/test_construction.py b/pandas/tests/arrays/integer/test_construction.py index 15307b6f2190e..a7e31ede8e384 100644 --- a/pandas/tests/arrays/integer/test_construction.py +++ b/pandas/tests/arrays/integer/test_construction.py @@ -4,10 +4,15 @@ import pandas as pd import pandas._testing as tm from pandas.api.types import is_integer -from pandas.core.arrays import IntegerArray, integer_array +from pandas.core.arrays import IntegerArray from pandas.core.arrays.integer import Int8Dtype, Int32Dtype, Int64Dtype +@pytest.fixture(params=[pd.array, IntegerArray._from_sequence]) +def constructor(request): + return request.param + + def test_uses_pandas_na(): a = pd.array([1, None], dtype=Int64Dtype()) assert a[1] is pd.NA @@ -65,7 +70,7 @@ def test_integer_array_constructor(): mask = np.array([False, False, False, True], dtype="bool") result = IntegerArray(values, mask) - expected = integer_array([1, 2, 3, np.nan], dtype="int64") + expected = pd.array([1, 2, 3, np.nan], dtype="Int64") tm.assert_extension_array_equal(result, expected) msg = r".* should be .* numpy array. Use the 'pd.array' function instead" @@ -82,21 +87,6 @@ def test_integer_array_constructor(): IntegerArray(values) -@pytest.mark.parametrize( - "a, b", - [ - ([1, None], [1, np.nan]), - ([None], [np.nan]), - ([None, np.nan], [np.nan, np.nan]), - ([np.nan, np.nan], [np.nan, np.nan]), - ], -) -def test_integer_array_constructor_none_is_nan(a, b): - result = integer_array(a) - expected = integer_array(b) - tm.assert_extension_array_equal(result, expected) - - def test_integer_array_constructor_copy(): values = np.array([1, 2, 3, 4], dtype="int64") mask = np.array([False, False, False, True], dtype="bool") @@ -110,6 +100,21 @@ def test_integer_array_constructor_copy(): assert result._mask is not mask +@pytest.mark.parametrize( + "a, b", + [ + ([1, None], [1, np.nan]), + ([None], [np.nan]), + ([None, np.nan], [np.nan, np.nan]), + ([np.nan, np.nan], [np.nan, np.nan]), + ], +) +def test_to_integer_array_none_is_nan(a, b): + result = pd.array(a, dtype="Int64") + expected = pd.array(b, dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + @pytest.mark.parametrize( "values", [ @@ -129,42 +134,46 @@ def test_to_integer_array_error(values): msg = ( r"(:?.* cannot be converted to an IntegerDtype)" r"|(:?values must be a 1D list-like)" + r"|(Cannot pass scalar)" ) + with pytest.raises((ValueError, TypeError), match=msg): + pd.array(values, dtype="Int64") + with pytest.raises(TypeError, match=msg): - integer_array(values) + IntegerArray._from_sequence(values) -def test_to_integer_array_inferred_dtype(): +def test_to_integer_array_inferred_dtype(constructor): # if values has dtype -> respect it - result = integer_array(np.array([1, 2], dtype="int8")) + result = constructor(np.array([1, 2], dtype="int8")) assert result.dtype == Int8Dtype() - result = integer_array(np.array([1, 2], dtype="int32")) + result = constructor(np.array([1, 2], dtype="int32")) assert result.dtype == Int32Dtype() # if values have no dtype -> always int64 - result = integer_array([1, 2]) + result = constructor([1, 2]) assert result.dtype == Int64Dtype() -def test_to_integer_array_dtype_keyword(): - result = integer_array([1, 2], dtype="int8") +def test_to_integer_array_dtype_keyword(constructor): + result = constructor([1, 2], dtype="Int8") assert result.dtype == Int8Dtype() # if values has dtype -> override it - result = integer_array(np.array([1, 2], dtype="int8"), dtype="int32") + result = constructor(np.array([1, 2], dtype="int8"), dtype="Int32") assert result.dtype == Int32Dtype() def test_to_integer_array_float(): - result = integer_array([1.0, 2.0]) - expected = integer_array([1, 2]) + result = IntegerArray._from_sequence([1.0, 2.0]) + expected = pd.array([1, 2], dtype="Int64") tm.assert_extension_array_equal(result, expected) with pytest.raises(TypeError, match="cannot safely cast non-equivalent"): - integer_array([1.5, 2.0]) + IntegerArray._from_sequence([1.5, 2.0]) # for float dtypes, the itemsize is not preserved - result = integer_array(np.array([1.0, 2.0], dtype="float32")) + result = IntegerArray._from_sequence(np.array([1.0, 2.0], dtype="float32")) assert result.dtype == Int64Dtype() @@ -176,10 +185,12 @@ def test_to_integer_array_float(): ([False, True, np.nan], [0, 1, np.nan], Int64Dtype(), Int64Dtype()), ], ) -def test_to_integer_array_bool(bool_values, int_values, target_dtype, expected_dtype): - result = integer_array(bool_values, dtype=target_dtype) +def test_to_integer_array_bool( + constructor, bool_values, int_values, target_dtype, expected_dtype +): + result = constructor(bool_values, dtype=target_dtype) assert result.dtype == expected_dtype - expected = integer_array(int_values, dtype=target_dtype) + expected = pd.array(int_values, dtype=target_dtype) tm.assert_extension_array_equal(result, expected) @@ -193,7 +204,7 @@ def test_to_integer_array_bool(bool_values, int_values, target_dtype, expected_d ) def test_to_integer_array(values, to_dtype, result_dtype): # convert existing arrays to IntegerArrays - result = integer_array(values, dtype=to_dtype) + result = IntegerArray._from_sequence(values, dtype=to_dtype) assert result.dtype == result_dtype() - expected = integer_array(values, dtype=result_dtype()) + expected = pd.array(values, dtype=result_dtype()) tm.assert_extension_array_equal(result, expected) diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py index d71037f9151e0..4d00a22e13c3a 100644 --- a/pandas/tests/arrays/integer/test_dtypes.py +++ b/pandas/tests/arrays/integer/test_dtypes.py @@ -5,7 +5,6 @@ import pandas as pd import pandas._testing as tm -from pandas.core.arrays import integer_array from pandas.core.arrays.integer import Int8Dtype, UInt32Dtype @@ -28,7 +27,7 @@ def test_preserve_dtypes(op): { "A": ["a", "b", "b"], "B": [1, None, 3], - "C": integer_array([1, None, 3], dtype="Int64"), + "C": pd.array([1, None, 3], dtype="Int64"), } ) @@ -43,7 +42,7 @@ def test_preserve_dtypes(op): result = getattr(df.groupby("A"), op)() expected = pd.DataFrame( - {"B": np.array([1.0, 3.0]), "C": integer_array([1, 3], dtype="Int64")}, + {"B": np.array([1.0, 3.0]), "C": pd.array([1, 3], dtype="Int64")}, index=pd.Index(["a", "b"], name="A"), ) tm.assert_frame_equal(result, expected) @@ -51,7 +50,7 @@ def test_preserve_dtypes(op): def test_astype_nansafe(): # see gh-22343 - arr = integer_array([np.nan, 1, 2], dtype="Int8") + arr = pd.array([np.nan, 1, 2], dtype="Int8") msg = "cannot convert to 'uint32'-dtype NumPy array with missing values." with pytest.raises(ValueError, match=msg): @@ -69,7 +68,7 @@ def test_construct_index(all_data, dropna): else: other = all_data - result = pd.Index(integer_array(other, dtype=all_data.dtype)) + result = pd.Index(pd.array(other, dtype=all_data.dtype)) expected = pd.Index(other, dtype=object) tm.assert_index_equal(result, expected) @@ -229,14 +228,14 @@ def test_construct_cast_invalid(dtype): msg = "cannot safely" arr = [1.2, 2.3, 3.7] with pytest.raises(TypeError, match=msg): - integer_array(arr, dtype=dtype) + pd.array(arr, dtype=dtype) with pytest.raises(TypeError, match=msg): pd.Series(arr).astype(dtype) arr = [1.2, 2.3, 3.7, np.nan] with pytest.raises(TypeError, match=msg): - integer_array(arr, dtype=dtype) + pd.array(arr, dtype=dtype) with pytest.raises(TypeError, match=msg): pd.Series(arr).astype(dtype) diff --git a/pandas/tests/arrays/integer/test_function.py b/pandas/tests/arrays/integer/test_function.py index 521547cc7357d..3a0ecee960e88 100644 --- a/pandas/tests/arrays/integer/test_function.py +++ b/pandas/tests/arrays/integer/test_function.py @@ -3,27 +3,26 @@ import pandas as pd import pandas._testing as tm -from pandas.core.arrays import integer_array @pytest.mark.parametrize("ufunc", [np.abs, np.sign]) # np.sign emits a warning with nans, <https://github.com/numpy/numpy/issues/15127> @pytest.mark.filterwarnings("ignore:invalid value encountered in sign") def test_ufuncs_single_int(ufunc): - a = integer_array([1, 2, -3, np.nan]) + a = pd.array([1, 2, -3, np.nan]) result = ufunc(a) - expected = integer_array(ufunc(a.astype(float))) + expected = pd.array(ufunc(a.astype(float)), dtype="Int64") tm.assert_extension_array_equal(result, expected) s = pd.Series(a) result = ufunc(s) - expected = pd.Series(integer_array(ufunc(a.astype(float)))) + expected = pd.Series(pd.array(ufunc(a.astype(float)), dtype="Int64")) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("ufunc", [np.log, np.exp, np.sin, np.cos, np.sqrt]) def test_ufuncs_single_float(ufunc): - a = integer_array([1, 2, -3, np.nan]) + a = pd.array([1, 2, -3, np.nan]) with np.errstate(invalid="ignore"): result = ufunc(a) expected = ufunc(a.astype(float)) @@ -39,33 +38,33 @@ def test_ufuncs_single_float(ufunc): @pytest.mark.parametrize("ufunc", [np.add, np.subtract]) def test_ufuncs_binary_int(ufunc): # two IntegerArrays - a = integer_array([1, 2, -3, np.nan]) + a = pd.array([1, 2, -3, np.nan]) result = ufunc(a, a) - expected = integer_array(ufunc(a.astype(float), a.astype(float))) + expected = pd.array(ufunc(a.astype(float), a.astype(float)), dtype="Int64") tm.assert_extension_array_equal(result, expected) # IntegerArray with numpy array arr = np.array([1, 2, 3, 4]) result = ufunc(a, arr) - expected = integer_array(ufunc(a.astype(float), arr)) + expected = pd.array(ufunc(a.astype(float), arr), dtype="Int64") tm.assert_extension_array_equal(result, expected) result = ufunc(arr, a) - expected = integer_array(ufunc(arr, a.astype(float))) + expected = pd.array(ufunc(arr, a.astype(float)), dtype="Int64") tm.assert_extension_array_equal(result, expected) # IntegerArray with scalar result = ufunc(a, 1) - expected = integer_array(ufunc(a.astype(float), 1)) + expected = pd.array(ufunc(a.astype(float), 1), dtype="Int64") tm.assert_extension_array_equal(result, expected) result = ufunc(1, a) - expected = integer_array(ufunc(1, a.astype(float))) + expected = pd.array(ufunc(1, a.astype(float)), dtype="Int64") tm.assert_extension_array_equal(result, expected) def test_ufunc_binary_output(): - a = integer_array([1, 2, np.nan]) + a = pd.array([1, 2, np.nan]) result = np.modf(a) expected = np.modf(a.to_numpy(na_value=np.nan, dtype="float")) @@ -74,13 +73,13 @@ def test_ufunc_binary_output(): for x, y in zip(result, expected): # TODO(FloatArray): This will return an extension array. - # y = integer_array(y) + # y = pd.array(y) tm.assert_numpy_array_equal(x, y) @pytest.mark.parametrize("values", [[0, 1], [0, None]]) def test_ufunc_reduce_raises(values): - a = integer_array(values) + a = pd.array(values) msg = r"The 'reduce' method is not supported." with pytest.raises(NotImplementedError, match=msg): np.add.reduce(a) diff --git a/pandas/tests/arrays/integer/test_repr.py b/pandas/tests/arrays/integer/test_repr.py index bdc5724e85e0d..35d07bda9a333 100644 --- a/pandas/tests/arrays/integer/test_repr.py +++ b/pandas/tests/arrays/integer/test_repr.py @@ -2,7 +2,6 @@ import pytest import pandas as pd -from pandas.core.arrays import integer_array from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, @@ -43,13 +42,13 @@ def test_repr_dtype(dtype, expected): def test_repr_array(): - result = repr(integer_array([1, None, 3])) + result = repr(pd.array([1, None, 3])) expected = "<IntegerArray>\n[1, <NA>, 3]\nLength: 3, dtype: Int64" assert result == expected def test_repr_array_long(): - data = integer_array([1, 2, None] * 1000) + data = pd.array([1, 2, None] * 1000) expected = ( "<IntegerArray>\n" "[ 1, 2, <NA>, 1, 2, <NA>, 1, 2, <NA>, 1,\n" diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index 72deada4eaf43..779cb7a2350ee 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -21,7 +21,7 @@ StringArray, TimedeltaArray, ) -from pandas.core.arrays import PandasArray, integer_array, period_array +from pandas.core.arrays import PandasArray, period_array from pandas.tests.extension.decimal import DecimalArray, DecimalDtype, to_decimal @@ -122,7 +122,7 @@ # Sparse ([0, 1], "Sparse[int64]", SparseArray([0, 1], dtype="int64")), # IntegerNA - ([1, None], "Int16", integer_array([1, None], dtype="Int16")), + ([1, None], "Int16", pd.array([1, None], dtype="Int16")), (pd.Series([1, 2]), None, PandasArray(np.array([1, 2], dtype=np.int64))), # String (["a", None], "string", StringArray._from_sequence(["a", None])), diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py index cc4aed5e4413d..94330f861eacd 100644 --- a/pandas/tests/base/test_conversion.py +++ b/pandas/tests/base/test_conversion.py @@ -240,7 +240,7 @@ def test_numpy_array_all_dtypes(any_numpy_dtype): [ (pd.Categorical(["a", "b"]), "_codes"), (pd.core.arrays.period_array(["2000", "2001"], freq="D"), "_data"), - (pd.core.arrays.integer_array([0, np.nan]), "_data"), + (pd.array([0, np.nan], dtype="Int64"), "_data"), (IntervalArray.from_breaks([0, 1]), "_left"), (SparseArray([0, 1]), "_sparse_values"), (DatetimeArray(np.array([1, 2], dtype="datetime64[ns]")), "_data"), @@ -285,7 +285,7 @@ def test_array_multiindex_raises(): pd.core.arrays.period_array(["2000", "2001"], freq="D"), np.array([pd.Period("2000", freq="D"), pd.Period("2001", freq="D")]), ), - (pd.core.arrays.integer_array([0, np.nan]), np.array([0, pd.NA], dtype=object)), + (pd.array([0, np.nan], dtype="Int64"), np.array([0, pd.NA], dtype=object)), ( IntervalArray.from_breaks([0, 1, 2]), np.array([pd.Interval(0, 1), pd.Interval(1, 2)], dtype=object), diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index b1461dcbd9e53..99a32203053c6 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -20,7 +20,6 @@ import pandas as pd import pandas._testing as tm -from pandas.core.arrays import integer_array from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, @@ -56,27 +55,27 @@ def dtype(request): @pytest.fixture def data(dtype): - return integer_array(make_data(), dtype=dtype) + return pd.array(make_data(), dtype=dtype) @pytest.fixture def data_for_twos(dtype): - return integer_array(np.ones(100) * 2, dtype=dtype) + return pd.array(np.ones(100) * 2, dtype=dtype) @pytest.fixture def data_missing(dtype): - return integer_array([pd.NA, 1], dtype=dtype) + return pd.array([pd.NA, 1], dtype=dtype) @pytest.fixture def data_for_sorting(dtype): - return integer_array([1, 2, 0], dtype=dtype) + return pd.array([1, 2, 0], dtype=dtype) @pytest.fixture def data_missing_for_sorting(dtype): - return integer_array([1, pd.NA, 0], dtype=dtype) + return pd.array([1, pd.NA, 0], dtype=dtype) @pytest.fixture @@ -96,7 +95,7 @@ def data_for_grouping(dtype): a = 0 c = 2 na = pd.NA - return integer_array([b, b, na, na, a, a, b, c], dtype=dtype) + return pd.array([b, b, na, na, a, a, b, c], dtype=dtype) class TestDtype(base.BaseDtypeTests): diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index d79969eac0323..54559400e3510 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -3,6 +3,7 @@ import numpy as np import pytest +import pandas as pd from pandas import ( Categorical, CategoricalDtype, @@ -20,7 +21,6 @@ option_context, ) import pandas._testing as tm -from pandas.core.arrays import integer_array def _check_cast(df, v): @@ -296,8 +296,8 @@ def test_astype_extension_dtypes(self, dtype): expected1 = DataFrame( { - "a": integer_array([1, 3, 5], dtype=dtype), - "b": integer_array([2, 4, 6], dtype=dtype), + "a": pd.array([1, 3, 5], dtype=dtype), + "b": pd.array([2, 4, 6], dtype=dtype), } ) tm.assert_frame_equal(df.astype(dtype), expected1) @@ -307,7 +307,7 @@ def test_astype_extension_dtypes(self, dtype): df = DataFrame([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], columns=["a", "b"]) df["b"] = df["b"].astype(dtype) expected2 = DataFrame( - {"a": [1.0, 3.0, 5.0], "b": integer_array([2, 4, 6], dtype=dtype)} + {"a": [1.0, 3.0, 5.0], "b": pd.array([2, 4, 6], dtype=dtype)} ) tm.assert_frame_equal(df, expected2) @@ -319,13 +319,13 @@ def test_astype_extension_dtypes_1d(self, dtype): # GH#22578 df = DataFrame({"a": [1.0, 2.0, 3.0]}) - expected1 = DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)}) + expected1 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)}) tm.assert_frame_equal(df.astype(dtype), expected1) tm.assert_frame_equal(df.astype("int64").astype(dtype), expected1) df = DataFrame({"a": [1.0, 2.0, 3.0]}) df["a"] = df["a"].astype(dtype) - expected2 = DataFrame({"a": integer_array([1, 2, 3], dtype=dtype)}) + expected2 = DataFrame({"a": pd.array([1, 2, 3], dtype=dtype)}) tm.assert_frame_equal(df, expected2) tm.assert_frame_equal(df.astype(dtype), expected1) diff --git a/pandas/tests/frame/methods/test_get_numeric_data.py b/pandas/tests/frame/methods/test_get_numeric_data.py index d73dbdf045be3..25b2a41b4b3a5 100644 --- a/pandas/tests/frame/methods/test_get_numeric_data.py +++ b/pandas/tests/frame/methods/test_get_numeric_data.py @@ -1,8 +1,9 @@ import numpy as np +import pandas as pd from pandas import Categorical, DataFrame, Index, Series, Timestamp import pandas._testing as tm -from pandas.core.arrays import IntervalArray, integer_array +from pandas.core.arrays import IntervalArray class TestGetNumericData: @@ -85,9 +86,9 @@ def test_get_numeric_data_extension_dtype(self): # GH#22290 df = DataFrame( { - "A": integer_array([-10, np.nan, 0, 10, 20, 30], dtype="Int64"), + "A": pd.array([-10, np.nan, 0, 10, 20, 30], dtype="Int64"), "B": Categorical(list("abcabc")), - "C": integer_array([0, 1, 2, 3, np.nan, 5], dtype="UInt8"), + "C": pd.array([0, 1, 2, 3, np.nan, 5], dtype="UInt8"), "D": IntervalArray.from_breaks(range(7)), } ) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index 06e5169fc6016..9825bcb0b5d57 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -1081,7 +1081,7 @@ def test_unstack_mixed_extension_types(self, level): index = MultiIndex.from_tuples([("A", 0), ("A", 1), ("B", 1)], names=["a", "b"]) df = DataFrame( { - "A": pd.core.arrays.integer_array([0, 1, None]), + "A": pd.array([0, 1, None], dtype="Int64"), "B": pd.Categorical(["a", "a", "b"]), }, index=index, diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index f750b3667cec2..5dee5c7f7adad 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -963,12 +963,12 @@ def test_extension_array_cross_section(): # A cross-section of a homogeneous EA should be an EA df = DataFrame( { - "A": pd.core.arrays.integer_array([1, 2]), - "B": pd.core.arrays.integer_array([3, 4]), + "A": pd.array([1, 2], dtype="Int64"), + "B": pd.array([3, 4], dtype="Int64"), }, index=["a", "b"], ) - expected = Series(pd.core.arrays.integer_array([1, 3]), index=["A", "B"], name="a") + expected = Series(pd.array([1, 3], dtype="Int64"), index=["A", "B"], name="a") result = df.loc["a"] tm.assert_series_equal(result, expected) diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index c66334065ea63..06a4474fcb3a6 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -15,7 +15,6 @@ import pandas as pd from pandas import DataFrame, MultiIndex, PeriodIndex, Series, bdate_range, date_range import pandas._testing as tm -from pandas.core.arrays import integer_array from pandas.tests.plotting.common import TestPlotBase, _check_plot_works from pandas.io.formats.printing import pprint_thing @@ -173,7 +172,7 @@ def test_nullable_int_plot(self): def test_integer_array_plot(self): # GH 25587 - arr = integer_array([1, 2, 3, 4], dtype="UInt32") + arr = pd.array([1, 2, 3, 4], dtype="UInt32") s = Series(arr) _check_plot_works(s.plot.line) diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index cd58df4fc5da6..16c4e9456aa05 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -429,7 +429,7 @@ def test_concat_order(self): tm.assert_index_equal(result, expected) def test_concat_different_extension_dtypes_upcasts(self): - a = Series(pd.core.arrays.integer_array([1, 2])) + a = Series(pd.array([1, 2], dtype="Int64")) b = Series(to_decimal([1, 2])) result = pd.concat([a, b], ignore_index=True)
The `integer_array()` function stems from a time that `pd.array(..)` didn't exist yet. But since now `pd.array` can do this, IMO we shouldn't be using that outside of the integer module (eg I didn't add a `floating_array(..)`). Only in `tests/arrays/integer/tst_construction.py` I still left the usage of `integer_array()` as is (but probably could also change it there). Could in principle remove the function altogether, since it is just a small wrapper around the private `arrays.integer.coerce_to_array`
https://api.github.com/repos/pandas-dev/pandas/pulls/38289
2020-12-04T14:08:21Z
2020-12-11T22:49:23Z
2020-12-11T22:49:23Z
2020-12-12T08:50:42Z
REF: avoid catching all exceptions in libreduction
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index 4b6b71088cb7c..25b41b020aee6 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -335,10 +335,6 @@ cdef class Slider: self.buf.shape[0] = 0 -class InvalidApply(Exception): - pass - - def apply_frame_axis0(object frame, object f, object names, const int64_t[:] starts, const int64_t[:] ends): cdef: @@ -365,11 +361,7 @@ def apply_frame_axis0(object frame, object f, object names, chunk = slider.dummy object.__setattr__(chunk, 'name', names[i]) - try: - piece = f(chunk) - except Exception as err: - # We can't be more specific without knowing something about `f` - raise InvalidApply("Let this error raise above us") from err + piece = f(chunk) # Need to infer if low level index slider will cause segfaults require_slow_apply = i == 0 and piece is chunk @@ -406,7 +398,8 @@ cdef class BlockSlider: """ cdef: object frame, dummy, index, block - list blk_values + list blocks, blk_values + ndarray orig_blklocs, orig_blknos ndarray values Slider idx_slider char **base_ptrs @@ -418,6 +411,13 @@ cdef class BlockSlider: self.dummy = frame[:0] self.index = self.dummy.index + # GH#35417 attributes we need to restore at each step in case + # the function modified them. + mgr = self.dummy._mgr + self.orig_blklocs = mgr.blklocs + self.orig_blknos = mgr.blknos + self.blocks = [x for x in self.dummy._mgr.blocks] + self.blk_values = [block.values for block in self.dummy._mgr.blocks] for values in self.blk_values: @@ -441,6 +441,9 @@ cdef class BlockSlider: cdef: ndarray arr Py_ssize_t i + + self._restore_blocks() + # move blocks for i in range(self.nblocks): arr = self.blk_values[i] @@ -460,9 +463,21 @@ cdef class BlockSlider: cdef: ndarray arr Py_ssize_t i + + self._restore_blocks() + for i in range(self.nblocks): arr = self.blk_values[i] # axis=1 is the frame's axis=0 arr.data = self.base_ptrs[i] arr.shape[1] = 0 + + cdef _restore_blocks(self): + """ + Ensure that we have the original blocks, blknos, and blklocs. + """ + mgr = self.dummy._mgr + mgr.blocks = self.blocks + mgr._blklocs = self.orig_blklocs + mgr._blknos = self.orig_blknos diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 7724e3930f7df..d1a4fc6fc74e5 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -202,13 +202,10 @@ def apply(self, f: F, data: FrameOrSeries, axis: int = 0): try: result_values, mutated = splitter.fast_apply(f, sdata, group_keys) - except libreduction.InvalidApply as err: - # This Exception is raised if `f` triggers an exception - # but it is preferable to raise the exception in Python. - if "Let this error raise above us" not in str(err): - # TODO: can we infer anything about whether this is - # worth-retrying in pure-python? - raise + except IndexError: + # This is a rare case in which re-running in python-space may + # make a difference, see test_apply_mutate.test_mutate_groups + pass else: # If the fast apply path could be used we can return here.
Most of the libreduction edits are from #35417
https://api.github.com/repos/pandas-dev/pandas/pulls/38285
2020-12-04T04:33:41Z
2020-12-17T13:53:36Z
2020-12-17T13:53:36Z
2020-12-17T15:43:21Z
TST: fixturize unfocused test
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 12e570490487d..60aae003d2956 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -145,140 +145,158 @@ def test_builtins_apply(keys, f): tm.assert_series_equal(getattr(result, fname)(), getattr(df, fname)()) -def test_arg_passthru(): - # make sure that we are passing thru kwargs - # to our agg functions +class TestNumericOnly: + # make sure that we are passing thru kwargs to our agg functions - # GH3668 - # GH5724 - df = DataFrame( - { - "group": [1, 1, 2], - "int": [1, 2, 3], - "float": [4.0, 5.0, 6.0], - "string": list("abc"), - "category_string": Series(list("abc")).astype("category"), - "category_int": [7, 8, 9], - "datetime": pd.date_range("20130101", periods=3), - "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"), - "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"), - }, - columns=[ - "group", - "int", - "float", - "string", - "category_string", - "category_int", - "datetime", - "datetimetz", - "timedelta", - ], - ) + @pytest.fixture + def df(self): + # GH3668 + # GH5724 + df = DataFrame( + { + "group": [1, 1, 2], + "int": [1, 2, 3], + "float": [4.0, 5.0, 6.0], + "string": list("abc"), + "category_string": Series(list("abc")).astype("category"), + "category_int": [7, 8, 9], + "datetime": date_range("20130101", periods=3), + "datetimetz": date_range("20130101", periods=3, tz="US/Eastern"), + "timedelta": pd.timedelta_range("1 s", periods=3, freq="s"), + }, + columns=[ + "group", + "int", + "float", + "string", + "category_string", + "category_int", + "datetime", + "datetimetz", + "timedelta", + ], + ) + return df - expected_columns_numeric = Index(["int", "float", "category_int"]) + @pytest.mark.parametrize("method", ["mean", "median"]) + def test_averages(self, df, method): + # mean / median + expected_columns_numeric = Index(["int", "float", "category_int"]) - # mean / median - expected = DataFrame( - { - "category_int": [7.5, 9], - "float": [4.5, 6.0], - "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], - "int": [1.5, 3], - "datetime": [ - Timestamp("2013-01-01 12:00:00"), - Timestamp("2013-01-03 00:00:00"), - ], - "datetimetz": [ - Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), - Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), + gb = df.groupby("group") + expected = DataFrame( + { + "category_int": [7.5, 9], + "float": [4.5, 6.0], + "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], + "int": [1.5, 3], + "datetime": [ + Timestamp("2013-01-01 12:00:00"), + Timestamp("2013-01-03 00:00:00"), + ], + "datetimetz": [ + Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), + Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), + ], + }, + index=Index([1, 2], name="group"), + columns=[ + "int", + "float", + "category_int", + "datetime", + "datetimetz", + "timedelta", ], - }, - index=Index([1, 2], name="group"), - columns=["int", "float", "category_int", "datetime", "datetimetz", "timedelta"], - ) - - for attr in ["mean", "median"]: - result = getattr(df.groupby("group"), attr)() - tm.assert_index_equal(result.columns, expected_columns_numeric) + ) - result = getattr(df.groupby("group"), attr)(numeric_only=False) + result = getattr(gb, method)(numeric_only=False) tm.assert_frame_equal(result.reindex_like(expected), expected) - # TODO: min, max *should* handle - # categorical (ordered) dtype - expected_columns = Index( - [ - "int", - "float", - "string", - "category_int", - "datetime", - "datetimetz", - "timedelta", - ] - ) - for attr in ["min", "max"]: - result = getattr(df.groupby("group"), attr)() - tm.assert_index_equal(result.columns, expected_columns) + expected_columns = expected.columns - result = getattr(df.groupby("group"), attr)(numeric_only=False) - tm.assert_index_equal(result.columns, expected_columns) + self._check(df, method, expected_columns, expected_columns_numeric) - expected_columns = Index( - [ - "int", - "float", - "string", - "category_string", - "category_int", - "datetime", - "datetimetz", - "timedelta", - ] - ) - for attr in ["first", "last"]: - result = getattr(df.groupby("group"), attr)() - tm.assert_index_equal(result.columns, expected_columns) + @pytest.mark.parametrize("method", ["min", "max"]) + def test_extrema(self, df, method): + # TODO: min, max *should* handle + # categorical (ordered) dtype - result = getattr(df.groupby("group"), attr)(numeric_only=False) - tm.assert_index_equal(result.columns, expected_columns) + expected_columns = Index( + [ + "int", + "float", + "string", + "category_int", + "datetime", + "datetimetz", + "timedelta", + ] + ) + expected_columns_numeric = expected_columns - expected_columns = Index(["int", "float", "string", "category_int", "timedelta"]) + self._check(df, method, expected_columns, expected_columns_numeric) - result = df.groupby("group").sum() - tm.assert_index_equal(result.columns, expected_columns_numeric) + @pytest.mark.parametrize("method", ["first", "last"]) + def test_first_last(self, df, method): - result = df.groupby("group").sum(numeric_only=False) - tm.assert_index_equal(result.columns, expected_columns) + expected_columns = Index( + [ + "int", + "float", + "string", + "category_string", + "category_int", + "datetime", + "datetimetz", + "timedelta", + ] + ) + expected_columns_numeric = expected_columns - expected_columns = Index(["int", "float", "category_int"]) - for attr in ["prod", "cumprod"]: - result = getattr(df.groupby("group"), attr)() - tm.assert_index_equal(result.columns, expected_columns_numeric) + self._check(df, method, expected_columns, expected_columns_numeric) - result = getattr(df.groupby("group"), attr)(numeric_only=False) - tm.assert_index_equal(result.columns, expected_columns) + @pytest.mark.parametrize("method", ["sum", "cumsum"]) + def test_sum_cumsum(self, df, method): - # like min, max, but don't include strings - expected_columns = Index( - ["int", "float", "category_int", "datetime", "datetimetz", "timedelta"] - ) - for attr in ["cummin", "cummax"]: - result = getattr(df.groupby("group"), attr)() - # GH 15561: numeric_only=False set by default like min/max - tm.assert_index_equal(result.columns, expected_columns) + expected_columns_numeric = Index(["int", "float", "category_int"]) + expected_columns = Index( + ["int", "float", "string", "category_int", "timedelta"] + ) + if method == "cumsum": + # cumsum loses string + expected_columns = Index(["int", "float", "category_int", "timedelta"]) - result = getattr(df.groupby("group"), attr)(numeric_only=False) - tm.assert_index_equal(result.columns, expected_columns) + self._check(df, method, expected_columns, expected_columns_numeric) + + @pytest.mark.parametrize("method", ["prod", "cumprod"]) + def test_prod_cumprod(self, df, method): + + expected_columns = Index(["int", "float", "category_int"]) + expected_columns_numeric = expected_columns + + self._check(df, method, expected_columns, expected_columns_numeric) - expected_columns = Index(["int", "float", "category_int", "timedelta"]) + @pytest.mark.parametrize("method", ["cummin", "cummax"]) + def test_cummin_cummax(self, df, method): + # like min, max, but don't include strings + expected_columns = Index( + ["int", "float", "category_int", "datetime", "datetimetz", "timedelta"] + ) + + # GH#15561: numeric_only=False set by default like min/max + expected_columns_numeric = expected_columns + + self._check(df, method, expected_columns, expected_columns_numeric) - result = getattr(df.groupby("group"), "cumsum")() - tm.assert_index_equal(result.columns, expected_columns_numeric) + def _check(self, df, method, expected_columns, expected_columns_numeric): + gb = df.groupby("group") - result = getattr(df.groupby("group"), "cumsum")(numeric_only=False) - tm.assert_index_equal(result.columns, expected_columns) + result = getattr(gb, method)() + tm.assert_index_equal(result.columns, expected_columns_numeric) + + result = getattr(gb, method)(numeric_only=False) + tm.assert_index_equal(result.columns, expected_columns) class TestGroupByNonCythonPaths:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38284
2020-12-04T04:31:04Z
2020-12-04T14:19:21Z
2020-12-04T14:19:21Z
2020-12-04T15:16:05Z
REF: de-duplicate intersection methods
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 4912fe6949958..f0d4d36531e0d 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -706,10 +706,6 @@ def _intersection(self, other: Index, sort=False) -> Index: if not isinstance(other, type(self)): result = Index.intersection(self, other, sort=sort) - if isinstance(result, type(self)): - if result.freq is None: - # TODO: no tests rely on this; needed? - result = result._with_freq("infer") return result elif not self._can_fast_intersect(other): diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 18be4bf225da5..f627b91958e75 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -126,10 +126,6 @@ def wrapped(self, other, sort=False): self._assert_can_do_setop(other) other, _ = self._convert_can_do_setop(other) - if op_name == "intersection": - if self.equals(other): - return self._get_reconciled_name_object(other) - if not isinstance(other, IntervalIndex): result = getattr(self.astype(object), op_name)(other) if op_name in ("difference",): @@ -965,7 +961,6 @@ def _assert_can_do_setop(self, other): ) @Appender(Index.intersection.__doc__) - @setop_check def intersection(self, other, sort=False) -> Index: self._validate_sort_keyword(sort) self._assert_can_do_setop(other) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index a71376187a8c4..ec896d94a20ba 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -15,7 +15,6 @@ from pandas.core.dtypes.common import ( ensure_platform_int, ensure_python_int, - is_dtype_equal, is_float, is_integer, is_list_like, @@ -483,42 +482,6 @@ def equals(self, other: object) -> bool: # -------------------------------------------------------------------- # Set Operations - def intersection(self, other, sort=False): - """ - Form the intersection of two Index objects. - - Parameters - ---------- - other : Index or array-like - sort : False or None, default False - Sort the resulting index if possible - - .. versionadded:: 0.24.0 - - .. versionchanged:: 0.24.1 - - Changed the default to ``False`` to match the behaviour - from before 0.24.0. - - Returns - ------- - intersection : Index - """ - self._validate_sort_keyword(sort) - self._assert_can_do_setop(other) - other, _ = self._convert_can_do_setop(other) - - if self.equals(other) and not self.has_duplicates: - # has_duplicates check is unnecessary for RangeIndex, but - # used to match other subclasses. - return self._get_reconciled_name_object(other) - - if not is_dtype_equal(self.dtype, other.dtype): - return super().intersection(other, sort=sort) - - result = self._intersection(other, sort=sort) - return self._wrap_setop_result(other, result) - def _intersection(self, other, sort=False): if not isinstance(other, RangeIndex):
De-duplicating the PeriodIndex, IntervalIndex, and MultiIndex methods is blocked by #38251
https://api.github.com/repos/pandas-dev/pandas/pulls/38283
2020-12-04T03:42:10Z
2020-12-04T14:19:59Z
2020-12-04T14:19:59Z
2020-12-04T15:14:59Z
BUG: IntervalIndex.union with mismatched dtypes both empty
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 94eb9a0b3fc58..cb4d04d4443e7 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -831,6 +831,7 @@ Other - Bug in :meth:`Index.difference` failing to set the correct name on the returned :class:`Index` in some corner cases (:issue:`38268`) - Bug in :meth:`Index.union` behaving differently depending on whether operand is an :class:`Index` or other list-like (:issue:`36384`) - Bug in :meth:`Index.intersection` with non-matching numeric dtypes casting to ``object`` dtype instead of minimal common dtype (:issue:`38122`) +- Bug in :meth:`IntervalIndex.intersection` returning an incorrectly-typed :class:`Index` when empty (:issue:`38282`) - Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError`` rather than a bare ``Exception`` (:issue:`35744`) - Bug in ``dir`` where ``dir(obj)`` wouldn't show attributes defined on the instance for pandas objects (:issue:`37173`) - Bug in :meth:`Index.drop` raising ``InvalidIndexError`` when index has duplicates (:issue:`38051`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index c0840d8e0d4b0..ba958b23e81af 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2694,7 +2694,7 @@ def union(self, other, sort=None): """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) - other = ensure_index(other) + other, result_name = self._convert_can_do_setop(other) if not self._can_union_without_object_cast(other): return self._union_incompatible_dtypes(other, sort=sort) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 3036e944d1e51..2f86d9c20bfe8 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1060,6 +1060,10 @@ def _intersection_non_unique(self, other: "IntervalIndex") -> "IntervalIndex": def _setop(op_name: str, sort=None): def func(self, other, sort=sort): + # At this point we are assured + # isinstance(other, IntervalIndex) + # other.closed == self.closed + result = getattr(self._multiindex, op_name)(other._multiindex, sort=sort) result_name = get_op_result_name(self, other) @@ -1074,7 +1078,7 @@ def func(self, other, sort=sort): func.__name__ = op_name return setop_check(func) - union = _setop("union") + _union = _setop("union") difference = _setop("difference") symmetric_difference = _setop("symmetric_difference") diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 911bbc44bb599..fd47c23b7c92b 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -3569,6 +3569,11 @@ def union(self, other, sort=None): if len(other) == 0 or self.equals(other): return self.rename(result_names) + return self._union(other, sort=sort) + + def _union(self, other, sort): + other, result_names = self._convert_can_do_setop(other) + # TODO: Index.union returns other when `len(self)` is 0. if not is_object_dtype(other.dtype): diff --git a/pandas/tests/indexes/interval/test_setops.py b/pandas/tests/indexes/interval/test_setops.py index 0b94d70367b4d..0ef833bb93ded 100644 --- a/pandas/tests/indexes/interval/test_setops.py +++ b/pandas/tests/indexes/interval/test_setops.py @@ -32,15 +32,17 @@ def test_union(self, closed, sort): tm.assert_index_equal(index.union(index, sort=sort), index) tm.assert_index_equal(index.union(index[:1], sort=sort), index) + def test_union_empty_result(self, closed, sort): # GH 19101: empty result, same dtype index = empty_index(dtype="int64", closed=closed) result = index.union(index, sort=sort) tm.assert_index_equal(result, index) - # GH 19101: empty result, different dtypes + # GH 19101: empty result, different dtypes -> common dtype is object other = empty_index(dtype="float64", closed=closed) result = index.union(other, sort=sort) - tm.assert_index_equal(result, index) + expected = Index([], dtype=object) + tm.assert_index_equal(result, expected) def test_intersection(self, closed, sort): index = monotonic_index(0, 11, closed=closed)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Ever so slowly ironing out the wrinkles between the setops.
https://api.github.com/repos/pandas-dev/pandas/pulls/38282
2020-12-04T01:44:54Z
2020-12-05T17:14:41Z
2020-12-05T17:14:41Z
2020-12-05T17:31:01Z
pandas/core/strings/accesory.py Unnecessary dict call - rewrite as a literal #38138
diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 9d16beba669ca..2713b76189157 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -26,7 +26,7 @@ from pandas.core.base import NoNewAttributesMixin -_shared_docs: Dict[str, str] = dict() +_shared_docs: Dict[str, str] = {} _cpython_optimized_encoders = ( "utf-8", "utf8", @@ -1446,17 +1446,17 @@ def pad(self, width, side="left", fillchar=" "): filled : Series/Index of objects. """ - @Appender(_shared_docs["str_pad"] % dict(side="left and right", method="center")) + @Appender(_shared_docs["str_pad"] % {"side": "left and right", "method": "center"}) @forbid_nonstring_types(["bytes"]) def center(self, width, fillchar=" "): return self.pad(width, side="both", fillchar=fillchar) - @Appender(_shared_docs["str_pad"] % dict(side="right", method="ljust")) + @Appender(_shared_docs["str_pad"] % {"side": "right", "method": "ljust"}) @forbid_nonstring_types(["bytes"]) def ljust(self, width, fillchar=" "): return self.pad(width, side="right", fillchar=fillchar) - @Appender(_shared_docs["str_pad"] % dict(side="left", method="rjust")) + @Appender(_shared_docs["str_pad"] % {"side": "left", "method": "rjust"}) @forbid_nonstring_types(["bytes"]) def rjust(self, width, fillchar=" "): return self.pad(width, side="left", fillchar=fillchar) @@ -1790,9 +1790,11 @@ def encode(self, encoding, errors="strict"): @Appender( _shared_docs["str_strip"] - % dict( - side="left and right sides", method="strip", position="leading and trailing" - ) + % { + "side": "left and right sides", + "method": "strip", + "position": "leading and trailing", + } ) @forbid_nonstring_types(["bytes"]) def strip(self, to_strip=None): @@ -1801,7 +1803,7 @@ def strip(self, to_strip=None): @Appender( _shared_docs["str_strip"] - % dict(side="left side", method="lstrip", position="leading") + % {"side": "left side", "method": "lstrip", "position": "leading"} ) @forbid_nonstring_types(["bytes"]) def lstrip(self, to_strip=None): @@ -1810,7 +1812,7 @@ def lstrip(self, to_strip=None): @Appender( _shared_docs["str_strip"] - % dict(side="right side", method="rstrip", position="trailing") + % {"side": "right side", "method": "rstrip", "position": "trailing"} ) @forbid_nonstring_types(["bytes"]) def rstrip(self, to_strip=None): @@ -2412,11 +2414,11 @@ def extractall(self, pat, flags=0): @Appender( _shared_docs["find"] - % dict( - side="lowest", - method="find", - also="rfind : Return highest indexes in each strings.", - ) + % { + "side": "lowest", + "method": "find", + "also": "rfind : Return highest indexes in each strings.", + } ) @forbid_nonstring_types(["bytes"]) def find(self, sub, start=0, end=None): @@ -2429,11 +2431,11 @@ def find(self, sub, start=0, end=None): @Appender( _shared_docs["find"] - % dict( - side="highest", - method="rfind", - also="find : Return lowest indexes in each strings.", - ) + % { + "side": "highest", + "method": "rfind", + "also": "find : Return lowest indexes in each strings.", + } ) @forbid_nonstring_types(["bytes"]) def rfind(self, sub, start=0, end=None): @@ -2495,12 +2497,12 @@ def normalize(self, form): @Appender( _shared_docs["index"] - % dict( - side="lowest", - similar="find", - method="index", - also="rindex : Return highest indexes in each strings.", - ) + % { + "side": "lowest", + "similar": "find", + "method": "index", + "also": "rindex : Return highest indexes in each strings.", + } ) @forbid_nonstring_types(["bytes"]) def index(self, sub, start=0, end=None): @@ -2513,12 +2515,12 @@ def index(self, sub, start=0, end=None): @Appender( _shared_docs["index"] - % dict( - side="highest", - similar="rfind", - method="rindex", - also="index : Return lowest indexes in each strings.", - ) + % { + "side": "highest", + "similar": "rfind", + "method": "rindex", + "also": "index : Return lowest indexes in each strings.", + } ) @forbid_nonstring_types(["bytes"]) def rindex(self, sub, start=0, end=None): @@ -2653,18 +2655,24 @@ def len(self): # isalpha, isnumeric isalnum isdigit isdecimal isspace islower isupper istitle # _doc_args holds dict of strings to use in substituting casemethod docs _doc_args: Dict[str, Dict[str, str]] = {} - _doc_args["lower"] = dict(type="lowercase", method="lower", version="") - _doc_args["upper"] = dict(type="uppercase", method="upper", version="") - _doc_args["title"] = dict(type="titlecase", method="title", version="") - _doc_args["capitalize"] = dict( - type="be capitalized", method="capitalize", version="" - ) - _doc_args["swapcase"] = dict(type="be swapcased", method="swapcase", version="") - _doc_args["casefold"] = dict( - type="be casefolded", - method="casefold", - version="\n .. versionadded:: 0.25.0\n", - ) + _doc_args["lower"] = {"type": "lowercase", "method": "lower", "version": ""} + _doc_args["upper"] = {"type": "uppercase", "method": "upper", "version": ""} + _doc_args["title"] = {"type": "titlecase", "method": "title", "version": ""} + _doc_args["capitalize"] = { + "type": "be capitalized", + "method": "capitalize", + "version": "", + } + _doc_args["swapcase"] = { + "type": "be swapcased", + "method": "swapcase", + "version": "", + } + _doc_args["casefold"] = { + "type": "be casefolded", + "method": "casefold", + "version": "\n .. versionadded:: 0.25.0\n", + } @Appender(_shared_docs["casemethods"] % _doc_args["lower"]) @forbid_nonstring_types(["bytes"]) @@ -2844,15 +2852,15 @@ def casefold(self): 3 False dtype: bool """ - _doc_args["isalnum"] = dict(type="alphanumeric", method="isalnum") - _doc_args["isalpha"] = dict(type="alphabetic", method="isalpha") - _doc_args["isdigit"] = dict(type="digits", method="isdigit") - _doc_args["isspace"] = dict(type="whitespace", method="isspace") - _doc_args["islower"] = dict(type="lowercase", method="islower") - _doc_args["isupper"] = dict(type="uppercase", method="isupper") - _doc_args["istitle"] = dict(type="titlecase", method="istitle") - _doc_args["isnumeric"] = dict(type="numeric", method="isnumeric") - _doc_args["isdecimal"] = dict(type="decimal", method="isdecimal") + _doc_args["isalnum"] = {"type": "alphanumeric", "method": "isalnum"} + _doc_args["isalpha"] = {"type": "alphabetic", "method": "isalpha"} + _doc_args["isdigit"] = {"type": "digits", "method": "isdigit"} + _doc_args["isspace"] = {"type": "whitespace", "method": "isspace"} + _doc_args["islower"] = {"type": "lowercase", "method": "islower"} + _doc_args["isupper"] = {"type": "uppercase", "method": "isupper"} + _doc_args["istitle"] = {"type": "titlecase", "method": "istitle"} + _doc_args["isnumeric"] = {"type": "numeric", "method": "isnumeric"} + _doc_args["isdecimal"] = {"type": "decimal", "method": "isdecimal"} # force _noarg_wrapper return type with dtype=np.dtype(bool) (GH 29624) isalnum = _map_and_wrap(
xref #38138 File modified: pandas/core/strings/accesory.py Changed unnecessary dict calls for flake8 (C408) standard: - Rewrite dict() as {} - [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38280
2020-12-04T00:52:36Z
2020-12-04T14:21:39Z
2020-12-04T14:21:39Z
2020-12-04T17:57:30Z
BUG: isin numeric vs string
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 840e79c6c9ebe..9749297efd004 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -445,6 +445,8 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray: elif isinstance(values, ABCMultiIndex): # Avoid raising in extract_array values = np.array(values) + else: + values = extract_array(values, extract_numpy=True) comps = _ensure_arraylike(comps) comps = extract_array(comps, extract_numpy=True) @@ -459,11 +461,14 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray: elif needs_i8_conversion(values.dtype) and not is_object_dtype(comps.dtype): # e.g. comps are integers and values are datetime64s return np.zeros(comps.shape, dtype=bool) + # TODO: not quite right ... Sparse/Categorical + elif needs_i8_conversion(values.dtype): + return isin(comps, values.astype(object)) - comps, dtype = _ensure_data(comps) - values, _ = _ensure_data(values, dtype=dtype) - - f = htable.ismember_object + elif is_extension_array_dtype(comps.dtype) or is_extension_array_dtype( + values.dtype + ): + return isin(np.asarray(comps), np.asarray(values)) # GH16012 # Ensure np.in1d doesn't get object types or it *may* throw an exception @@ -476,23 +481,15 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray: f = lambda c, v: np.logical_or(np.in1d(c, v), np.isnan(c)) else: f = np.in1d - elif is_integer_dtype(comps.dtype): - try: - values = values.astype("int64", copy=False) - comps = comps.astype("int64", copy=False) - f = htable.ismember_int64 - except (TypeError, ValueError, OverflowError): - values = values.astype(object) - comps = comps.astype(object) - - elif is_float_dtype(comps.dtype): - try: - values = values.astype("float64", copy=False) - comps = comps.astype("float64", copy=False) - f = htable.ismember_float64 - except (TypeError, ValueError): - values = values.astype(object) - comps = comps.astype(object) + + else: + common = np.find_common_type([values.dtype, comps.dtype], []) + values = values.astype(common, copy=False) + comps = comps.astype(common, copy=False) + name = common.name + if name == "bool": + name = "uint8" + f = getattr(htable, f"ismember_{name}") return f(comps, values) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index d836ca7a53249..35411d7e9cfb7 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1044,7 +1044,6 @@ def test_different_nans_as_float64(self): expected = np.array([True, True]) tm.assert_numpy_array_equal(result, expected) - @pytest.mark.xfail(reason="problem related with issue #34125") def test_isin_int_df_string_search(self): """Comparing df with int`s (1,2) with a string at isin() ("1") -> should not match values because int 1 is not equal str 1""" @@ -1053,7 +1052,6 @@ def test_isin_int_df_string_search(self): expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false) - @pytest.mark.xfail(reason="problem related with issue #34125") def test_isin_nan_df_string_search(self): """Comparing df with nan value (np.nan,2) with a string at isin() ("NaN") -> should not match values because np.nan is not equal str NaN""" @@ -1062,7 +1060,6 @@ def test_isin_nan_df_string_search(self): expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false) - @pytest.mark.xfail(reason="problem related with issue #34125") def test_isin_float_df_string_search(self): """Comparing df with floats (1.4245,2.32441) with a string at isin() ("1.4245") -> should not match values because float 1.4245 is not equal str 1.4245"""
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Using the new hashtables! ``` In [3]: arr = np.arange(10**7).astype(np.int32) In [4]: %timeit isin(arr, arr[:10]) 88.8 ms ± 497 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # <-- master 42.7 ms ± 385 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # <-- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/38279
2020-12-03T23:16:56Z
2020-12-04T14:25:42Z
2020-12-04T14:25:42Z
2020-12-07T17:28:41Z
BUG: Validate drop_duplicates ignore_index argument for bool
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 84ac2d0c17676..216139b13dfc5 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -793,6 +793,7 @@ Reshaping - Bug in :func:`merge_ordered` couldn't handle list-like ``left_by`` or ``right_by`` (:issue:`35269`) - Bug in :func:`merge_ordered` returned wrong join result when length of ``left_by`` or ``right_by`` equals to the rows of ``left`` or ``right`` (:issue:`38166`) - Bug in :func:`merge_ordered` didn't raise when elements in ``left_by`` or ``right_by`` not exist in ``left`` columns or ``right`` columns (:issue:`38167`) +- Bug in :func:`DataFrame.drop_duplicates` not validating bool dtype for ``ignore_index`` keyword (:issue:`38274`) Sparse ^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5f149f10b05d3..f710660d6ad8e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -5273,6 +5273,7 @@ def drop_duplicates( return self.copy() inplace = validate_bool_kwarg(inplace, "inplace") + ignore_index = validate_bool_kwarg(ignore_index, "ignore_index") duplicated = self.duplicated(subset, keep=keep) result = self[-duplicated] diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index 79b152b677dfd..b1d3890540bf9 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -459,3 +459,12 @@ def test_drop_duplicates_series_vs_dataframe(keep): dropped_frame = df[[column]].drop_duplicates(keep=keep) dropped_series = df[column].drop_duplicates(keep=keep) tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) + + +@pytest.mark.parametrize("arg", [[1], 1, "True", [], 0]) +def test_drop_duplicates_non_boolean_ignore_index(arg): + # GH#38274 + df = DataFrame({"a": [1, 2, 1, 3]}) + msg = '^For argument "ignore_index" expected type bool, received type .*.$' + with pytest.raises(ValueError, match=msg): + df.drop_duplicates(ignore_index=arg)
- [x] closes #38274 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Saw this on the tracker. I think we should validate this, some inputs could lead to weird results. The last drop duplicates entry in whatsnew was also under reshaping, so put it there
https://api.github.com/repos/pandas-dev/pandas/pulls/38277
2020-12-03T22:36:46Z
2020-12-04T14:24:58Z
2020-12-04T14:24:58Z
2020-12-04T23:46:21Z
Removing dict calls
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index 4aed39d7edb92..fe3a7ae3c8631 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -386,9 +386,9 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: # coerce if is_float_dtype(dtype): # In astype, we consider dtype=float to also mean na_value=np.nan - kwargs = dict(na_value=np.nan) + kwargs = {"na_value": np.nan} elif is_datetime64_dtype(dtype): - kwargs = dict(na_value=np.datetime64("NaT")) + kwargs = {"na_value": np.datetime64("NaT")} else: kwargs = {} diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 4eb67dcd12728..50d12703c3a30 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -273,12 +273,12 @@ def _values_for_factorize(self) -> Tuple[np.ndarray, int]: # Reductions def any(self, *, axis=None, out=None, keepdims=False, skipna=True): - nv.validate_any((), dict(out=out, keepdims=keepdims)) + nv.validate_any((), {"out": out, "keepdims": keepdims}) result = nanops.nanany(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) def all(self, *, axis=None, out=None, keepdims=False, skipna=True): - nv.validate_all((), dict(out=out, keepdims=keepdims)) + nv.validate_all((), {"out": out, "keepdims": keepdims}) result = nanops.nanall(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) @@ -311,7 +311,7 @@ def prod(self, *, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: return self._wrap_reduction_result(axis, result) def mean(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): - nv.validate_mean((), dict(dtype=dtype, out=out, keepdims=keepdims)) + nv.validate_mean((), {"dtype": dtype, "out": out, "keepdims": keepdims}) result = nanops.nanmean(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) @@ -319,7 +319,7 @@ def median( self, *, axis=None, out=None, overwrite_input=False, keepdims=False, skipna=True ): nv.validate_median( - (), dict(out=out, overwrite_input=overwrite_input, keepdims=keepdims) + (), {"out": out, "overwrite_input": overwrite_input, "keepdims": keepdims} ) result = nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) @@ -328,7 +328,7 @@ def std( self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True ): nv.validate_stat_ddof_func( - (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="std" + (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="std" ) result = nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) return self._wrap_reduction_result(axis, result) @@ -337,7 +337,7 @@ def var( self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True ): nv.validate_stat_ddof_func( - (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="var" + (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="var" ) result = nanops.nanvar(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) return self._wrap_reduction_result(axis, result) @@ -346,21 +346,21 @@ def sem( self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True ): nv.validate_stat_ddof_func( - (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="sem" + (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="sem" ) result = nanops.nansem(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) return self._wrap_reduction_result(axis, result) def kurt(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): nv.validate_stat_ddof_func( - (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="kurt" + (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="kurt" ) result = nanops.nankurt(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result) def skew(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): nv.validate_stat_ddof_func( - (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="skew" + (), {"dtype": dtype, "out": out, "keepdims": keepdims}, fname="skew" ) result = nanops.nanskew(self._ndarray, axis=axis, skipna=skipna) return self._wrap_reduction_result(axis, result)
- [ ] xref #38138 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Removed the dict calls for the files: `./pandas/core/arrays/floating.py` `./pandas/core/arrays/numpy_.py` `./pandas/core/arrays/interval.py`
https://api.github.com/repos/pandas-dev/pandas/pulls/38276
2020-12-03T22:00:40Z
2020-12-04T14:22:38Z
2020-12-04T14:22:38Z
2020-12-04T14:22:42Z
CLN: assorted cleanups
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index ad6329c588bbe..4b6b71088cb7c 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -367,9 +367,9 @@ def apply_frame_axis0(object frame, object f, object names, try: piece = f(chunk) - except Exception: + except Exception as err: # We can't be more specific without knowing something about `f` - raise InvalidApply('Let this error raise above us') + raise InvalidApply("Let this error raise above us") from err # Need to infer if low level index slider will cause segfaults require_slow_apply = i == 0 and piece is chunk diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 5e78fe8fea00c..0a863dc3c00e8 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -63,7 +63,7 @@ import pandas.core.common as com from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame -from pandas.core.generic import ABCDataFrame, ABCSeries, NDFrame +from pandas.core.generic import NDFrame from pandas.core.groupby import base from pandas.core.groupby.groupby import ( GroupBy, @@ -531,7 +531,7 @@ def _transform_general(self, func, *args, **kwargs): object.__setattr__(group, "name", name) res = func(group, *args, **kwargs) - if isinstance(res, (ABCDataFrame, ABCSeries)): + if isinstance(res, (DataFrame, Series)): res = res._values results.append(klass(res, index=group.index)) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 798c0742f03e5..652fda85c4b8e 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -966,22 +966,6 @@ def _cumcount_array(self, ascending: bool = True): rev[sorter] = np.arange(count, dtype=np.intp) return out[rev].astype(np.int64, copy=False) - def _transform_should_cast(self, func_nm: str) -> bool: - """ - Parameters - ---------- - func_nm: str - The name of the aggregation function being performed - - Returns - ------- - bool - Whether transform should attempt to cast the result of aggregation - """ - filled_series = self.grouper.size().fillna(0) - assert filled_series is not None - return filled_series.gt(0).any() and func_nm not in base.cython_cast_blocklist - def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index e8af9da30a298..8b79ea2242258 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -18,7 +18,6 @@ is_scalar, is_timedelta64_dtype, ) -from pandas.core.dtypes.generic import ABCSeries import pandas.core.algorithms as algorithms from pandas.core.arrays import Categorical, ExtensionArray @@ -345,9 +344,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): if self.key is not None: key = self.key # The 'on' is already defined - if getattr(self.grouper, "name", None) == key and isinstance( - obj, ABCSeries - ): + if getattr(self.grouper, "name", None) == key and isinstance(obj, Series): # pandas\core\groupby\grouper.py:348: error: Item "None" of # "Optional[Any]" has no attribute "take" [union-attr] ax = self._grouper.take(obj.index) # type: ignore[union-attr] diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 52ffb1567cb2d..3778f234bdb4a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -70,7 +70,6 @@ ABCMultiIndex, ABCPandasArray, ABCPeriodIndex, - ABCRangeIndex, ABCSeries, ABCTimedeltaIndex, ) @@ -3494,12 +3493,7 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): target = ensure_has_len(target) # target may be an iterator if not isinstance(target, Index) and len(target) == 0: - values: Union[range, ExtensionArray, np.ndarray] - if isinstance(self, ABCRangeIndex): - values = range(0) - else: - values = self._data[:0] # appropriately-dtyped empty array - target = self._simple_new(values, name=self.name) + target = self[:0] else: target = ensure_index(target) @@ -3829,6 +3823,7 @@ def _join_non_unique(self, other, how="left", return_indexers=False): else: return join_index + @final def _join_level( self, other, level, how="left", return_indexers=False, keep_order=True ): @@ -3972,6 +3967,7 @@ def _get_leaf_sorter(labels): else: return join_index + @final def _join_monotonic(self, other, how="left", return_indexers=False): # We only get here with matching dtypes assert other.dtype == self.dtype diff --git a/pandas/tests/series/indexing/test_xs.py b/pandas/tests/series/indexing/test_xs.py index ca7ed50ab8875..83cc6d4670423 100644 --- a/pandas/tests/series/indexing/test_xs.py +++ b/pandas/tests/series/indexing/test_xs.py @@ -56,8 +56,8 @@ def test_series_xs_droplevel_false(self): mi = MultiIndex.from_tuples( [("a", "x"), ("a", "y"), ("b", "x")], names=["level1", "level2"] ) - df = Series([1, 1, 1], index=mi) - result = df.xs("a", axis=0, drop_level=False) + ser = Series([1, 1, 1], index=mi) + result = ser.xs("a", axis=0, drop_level=False) expected = Series( [1, 1], index=MultiIndex.from_tuples(
https://api.github.com/repos/pandas-dev/pandas/pulls/38275
2020-12-03T21:20:24Z
2020-12-03T22:59:42Z
2020-12-03T22:59:42Z
2020-12-04T00:02:17Z
BUG: DataFrame.apply with axis=1 and EA dtype
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index c5260deafc0c3..6d9e11ecb824f 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -9,7 +9,12 @@ from pandas._typing import Axis, FrameOrSeriesUnion from pandas.util._decorators import cache_readonly -from pandas.core.dtypes.common import is_dict_like, is_list_like, is_sequence +from pandas.core.dtypes.common import ( + is_dict_like, + is_extension_array_dtype, + is_list_like, + is_sequence, +) from pandas.core.dtypes.generic import ABCSeries from pandas.core.construction import create_series_with_explicit_dtype @@ -392,12 +397,20 @@ def series_generator(self): mgr = ser._mgr blk = mgr.blocks[0] - for (arr, name) in zip(values, self.index): - # GH#35462 re-pin mgr in case setitem changed it - ser._mgr = mgr - blk.values = arr - ser.name = name - yield ser + if is_extension_array_dtype(blk.dtype): + # values will be incorrect for this block + # TODO(EA2D): special case would be unnecessary with 2D EAs + obj = self.obj + for i in range(len(obj)): + yield obj._ixs(i, axis=0) + + else: + for (arr, name) in zip(values, self.index): + # GH#35462 re-pin mgr in case setitem changed it + ser._mgr = mgr + blk.values = arr + ser.name = name + yield ser @property def result_index(self) -> "Index": diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 15952f36b0fae..9ec56c3429b22 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -58,6 +58,12 @@ def test_apply(self, float_frame): assert isinstance(df["c0"].dtype, CategoricalDtype) assert isinstance(df["c1"].dtype, CategoricalDtype) + def test_apply_axis1_with_ea(self): + # GH#36785 + df = DataFrame({"A": [Timestamp("2013-01-01", tz="UTC")]}) + result = df.apply(lambda x: x, axis=1) + tm.assert_frame_equal(result, df) + def test_apply_mixed_datetimelike(self): # mixed datetimelike # GH 7778
- [x] closes #36785 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38272
2020-12-03T18:51:39Z
2020-12-04T16:21:24Z
2020-12-04T16:21:24Z
2020-12-05T21:01:42Z
BUG: name retention in Index.difference corner cases
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 8dbc6728dccfe..650ee9dc4f507 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -825,6 +825,7 @@ Other - Fixed metadata propagation when selecting columns with ``DataFrame.__getitem__`` (:issue:`28283`) - Bug in :meth:`Index.intersection` with non-:class:`Index` failing to set the correct name on the returned :class:`Index` (:issue:`38111`) - Bug in :meth:`RangeIndex.intersection` failing to set the correct name on the returned :class:`Index` in some corner cases (:issue:`38197`) +- Bug in :meth:`Index.difference` failing to set the correct name on the returned :class:`Index` in some corner cases (:issue:`38268`) - Bug in :meth:`Index.union` behaving differently depending on whether operand is an :class:`Index` or other list-like (:issue:`36384`) - Bug in :meth:`Index.intersection` with non-matching numeric dtypes casting to ``object`` dtype instead of minimal common dtype (:issue:`38122`) - Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError`` rather than a bare ``Exception`` (:issue:`35744`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 3778f234bdb4a..49c980e073ed8 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2913,12 +2913,15 @@ def difference(self, other, sort=None): """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) + other, result_name = self._convert_can_do_setop(other) if self.equals(other): - # pass an empty np.ndarray with the appropriate dtype - return self._shallow_copy(self._data[:0]) + return self[:0].rename(result_name) - other, result_name = self._convert_can_do_setop(other) + result = self._difference(other, sort=sort) + return self._wrap_setop_result(other, result) + + def _difference(self, other, sort): this = self._get_unique_index() @@ -2933,7 +2936,7 @@ def difference(self, other, sort=None): except TypeError: pass - return this._shallow_copy(the_diff, name=result_name) + return the_diff def symmetric_difference(self, other, result_name=None, sort=None): """ diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 4b004ce94b0e2..26bba4653007f 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,5 +1,5 @@ from datetime import datetime, timedelta -from typing import Any, cast +from typing import Any import warnings import numpy as np @@ -660,14 +660,14 @@ def _intersection(self, other, sort=False): def difference(self, other, sort=None): self._validate_sort_keyword(sort) self._assert_can_do_setop(other) - other = ensure_index(other) + other, result_name = self._convert_can_do_setop(other) if self.equals(other): - # pass an empty PeriodArray with the appropriate dtype + return self[:0].rename(result_name) + + return self._difference(other, sort=sort) - # TODO: overload DatetimeLikeArrayMixin.__getitem__ - values = cast(PeriodArray, self._data[:0]) - return type(self)._simple_new(values, name=self.name) + def _difference(self, other, sort): if is_object_dtype(other): return self.astype(object).difference(other).astype(self.dtype) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 77de6bdaeec5a..a71376187a8c4 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -666,6 +666,8 @@ def _union(self, other, sort): def difference(self, other, sort=None): # optimized set operation if we have another RangeIndex self._validate_sort_keyword(sort) + self._assert_can_do_setop(other) + other, result_name = self._convert_can_do_setop(other) if not isinstance(other, RangeIndex): return super().difference(other, sort=sort) diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index b6e793ba334ff..6f949960ce30b 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -424,6 +424,18 @@ def test_difference_preserves_type_empty(self, index, sort): expected = index[:0] tm.assert_index_equal(result, expected, exact=True) + def test_difference_name_retention_equals(self, index, sort, names): + if isinstance(index, MultiIndex): + names = [[x] * index.nlevels for x in names] + index = index.rename(names[0]) + other = index.rename(names[1]) + + assert index.equals(other) + + result = index.difference(other) + expected = index[:0].rename(names[2]) + tm.assert_index_equal(result, expected) + def test_intersection_difference_match_empty(self, index, sort): # GH#20040 # Test that the intersection of an index with an
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38268
2020-12-03T17:58:15Z
2020-12-04T02:01:12Z
2020-12-04T02:01:12Z
2020-12-04T02:08:54Z
BUG: Inserting array of same size with Series.loc raises ValueError
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 94eb9a0b3fc58..30a919b9c050b 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -678,6 +678,8 @@ Indexing - Bug in :meth:`DataFrame.loc` and :meth:`DataFrame.__getitem__` raising ``KeyError`` when columns were :class:`MultiIndex` with only one level (:issue:`29749`) - Bug in :meth:`Series.__getitem__` and :meth:`DataFrame.__getitem__` raising blank ``KeyError`` without missing keys for :class:`IntervalIndex` (:issue:`27365`) - Bug in setting a new label on a :class:`DataFrame` or :class:`Series` with a :class:`CategoricalIndex` incorrectly raising ``TypeError`` when the new label is not among the index's categories (:issue:`38098`) +- Bug in :meth:`Series.loc` and :meth:`Series.iloc` raising ``ValueError`` when inserting a listlike ``np.array``, ``list`` or ``tuple`` in an ``object`` Series of equal length (:issue:`37748`, :issue:`37486`) +- Bug in :meth:`Series.loc` and :meth:`Series.iloc` setting all the values of an ``object`` Series with those of a listlike ``ExtensionArray`` instead of inserting it (:issue:`38271`) Missing ^^^^^^^ diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py index b6713bc760c5e..da4654bbf2c10 100644 --- a/pandas/core/indexers.py +++ b/pandas/core/indexers.py @@ -79,6 +79,9 @@ def is_scalar_indexer(indexer, ndim: int) -> bool: ------- bool """ + if ndim == 1 and is_integer(indexer): + # GH37748: allow indexer to be an integer for Series + return True if isinstance(indexer, tuple): if len(indexer) == ndim: return all( diff --git a/pandas/tests/indexing/test_indexers.py b/pandas/tests/indexing/test_indexers.py index 744f9441e7376..14b2b494d65fb 100644 --- a/pandas/tests/indexing/test_indexers.py +++ b/pandas/tests/indexing/test_indexers.py @@ -28,6 +28,12 @@ def test_is_scalar_indexer(): assert not is_scalar_indexer(slice(None), 1) + indexer = 0 + assert is_scalar_indexer(indexer, 1) + + indexer = (0,) + assert is_scalar_indexer(indexer, 1) + class TestValidateIndices: def test_validate_indices_ok(self): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index f6aa2371cf13a..68f12a939e061 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2072,3 +2072,21 @@ def test_loc_setitem_dt64tz_values(self): s2["a"] = expected result = s2["a"] assert result == expected + + @pytest.mark.parametrize("array_fn", [np.array, pd.array, list, tuple]) + @pytest.mark.parametrize("size", [0, 4, 5, 6]) + def test_loc_iloc_setitem_with_listlike(self, size, array_fn): + # GH37748 + # testing insertion, in a Series of size N (here 5), of a listlike object + # of size 0, N-1, N, N+1 + + arr = array_fn([0] * size) + expected = Series([arr, 0, 0, 0, 0], index=list("abcde"), dtype=object) + + ser = Series(0, index=list("abcde"), dtype=object) + ser.loc["a"] = arr + tm.assert_series_equal(ser, expected) + + ser = Series(0, index=list("abcde"), dtype=object) + ser.iloc[0] = arr + tm.assert_series_equal(ser, expected)
closes #37748 closes #37486 closes #38271 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38266
2020-12-03T17:33:05Z
2020-12-05T17:14:06Z
2020-12-05T17:14:04Z
2020-12-06T00:28:19Z
Rewrite dict call to literals
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 12f61fc44582d..b2bd5ef587a00 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -29,7 +29,7 @@ import pandas.core.common as com from pandas.core.indexes.base import Index, maybe_extract_name -_num_index_shared_docs = dict() +_num_index_shared_docs = {} class NumericIndex(Index): @@ -224,7 +224,12 @@ def _union(self, other, sort): An Index instance can **only** contain hashable objects. """ -_int64_descr_args = dict(klass="Int64Index", ltype="integer", dtype="int64", extra="") +_int64_descr_args = { + "klass": "Int64Index", + "ltype": "integer", + "dtype": "int64", + "extra": "", +} class IntegerIndex(NumericIndex): @@ -286,9 +291,12 @@ class Int64Index(IntegerIndex): _default_dtype = np.dtype(np.int64) -_uint64_descr_args = dict( - klass="UInt64Index", ltype="unsigned integer", dtype="uint64", extra="" -) +_uint64_descr_args = { + "klass": "UInt64Index", + "ltype": "unsigned integer", + "dtype": "uint64", + "extra": "", +} class UInt64Index(IntegerIndex): @@ -314,9 +322,12 @@ def _convert_arr_indexer(self, keyarr): return com.asarray_tuplesafe(keyarr, dtype=dtype) -_float64_descr_args = dict( - klass="Float64Index", dtype="float64", ltype="float", extra="" -) +_float64_descr_args = { + "klass": "Float64Index", + "dtype": "float64", + "ltype": "float", + "extra": "", +} class Float64Index(NumericIndex):
- [ ] xref #38138 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Identify unnecessary dict call - rewrite as a literal in `pandas\core\indexes\numeric.py`
https://api.github.com/repos/pandas-dev/pandas/pulls/38265
2020-12-03T16:53:39Z
2020-12-03T21:39:58Z
2020-12-03T21:39:58Z
2020-12-03T21:39:58Z
REF: implement Groupby idxmin, idxmax without fallback
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 5e78fe8fea00c..19bd13b76762c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -50,6 +50,7 @@ ) from pandas.core.dtypes.missing import isna, notna +from pandas.core import algorithms, nanops from pandas.core.aggregation import ( agg_list_like, aggregate, @@ -57,7 +58,6 @@ reconstruct_func, validate_func_kwargs, ) -import pandas.core.algorithms as algorithms from pandas.core.arrays import Categorical, ExtensionArray from pandas.core.base import DataError, SpecificationError import pandas.core.common as com @@ -1826,4 +1826,46 @@ def nunique(self, dropna: bool = True) -> DataFrame: self._insert_inaxis_grouper_inplace(results) return results + @Appender(DataFrame.idxmax.__doc__) + def idxmax(self, axis=0, skipna: bool = True): + axis = DataFrame._get_axis_number(axis) + numeric_only = None if axis == 0 else False + + def func(df): + # NB: here we use numeric_only=None, in DataFrame it is False GH#38217 + res = df._reduce( + nanops.nanargmax, + "argmax", + axis=axis, + skipna=skipna, + numeric_only=numeric_only, + ) + indices = res._values + index = df._get_axis(axis) + result = [index[i] if i >= 0 else np.nan for i in indices] + return df._constructor_sliced(result, index=res.index) + + return self._python_apply_general(func, self._obj_with_exclusions) + + @Appender(DataFrame.idxmin.__doc__) + def idxmin(self, axis=0, skipna: bool = True): + axis = DataFrame._get_axis_number(axis) + numeric_only = None if axis == 0 else False + + def func(df): + # NB: here we use numeric_only=None, in DataFrame it is False GH#38217 + res = df._reduce( + nanops.nanargmin, + "argmin", + axis=axis, + skipna=skipna, + numeric_only=numeric_only, + ) + indices = res._values + index = df._get_axis(axis) + result = [index[i] if i >= 0 else np.nan for i in indices] + return df._constructor_sliced(result, index=res.index) + + return self._python_apply_general(func, self._obj_with_exclusions) + boxplot = boxplot_frame_groupby diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 798c0742f03e5..7e21de41873be 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -11,7 +11,6 @@ class providing the base-class of operations. import datetime from functools import partial, wraps import inspect -import re import types from typing import ( Callable, @@ -797,23 +796,7 @@ def curried(x): if name in base.plotting_methods: return self.apply(curried) - try: - return self._python_apply_general(curried, self._obj_with_exclusions) - except TypeError as err: - if not re.search( - "reduction operation '.*' not allowed for this dtype", str(err) - ): - # We don't have a cython implementation - # TODO: is the above comment accurate? - raise - - if self.obj.ndim == 1: - # this can be called recursively, so need to raise ValueError - raise ValueError - - # GH#3688 try to operate item-by-item - result = self._aggregate_item_by_item(name, *args, **kwargs) - return result + return self._python_apply_general(curried, self._obj_with_exclusions) wrapper.__name__ = name return wrapper diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 12e570490487d..230b9be41706a 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -521,6 +521,27 @@ def test_idxmin_idxmax_returns_int_types(func, values): tm.assert_frame_equal(result, expected) +def test_idxmin_idxmax_axis1(): + df = DataFrame(np.random.randn(10, 4), columns=["A", "B", "C", "D"]) + df["A"] = [1, 2, 3, 1, 2, 3, 1, 2, 3, 4] + + gb = df.groupby("A") + + res = gb.idxmax(axis=1) + + alt = df.iloc[:, 1:].idxmax(axis=1) + indexer = res.index.get_level_values(1) + + tm.assert_series_equal(alt[indexer], res.droplevel("A")) + + df["E"] = pd.date_range("2016-01-01", periods=10) + gb2 = df.groupby("A") + + msg = "reduction operation 'argmax' not allowed for this dtype" + with pytest.raises(TypeError, match=msg): + gb2.idxmax(axis=1) + + def test_groupby_cumprod(): # GH 4095 df = DataFrame({"key": ["b"] * 10, "value": 2})
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38264
2020-12-03T16:00:17Z
2020-12-04T23:41:41Z
2020-12-04T23:41:41Z
2020-12-05T00:00:49Z
C408 rewrite dict call to dict literals
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 757cea2c710b2..53a98fc43becc 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -57,9 +57,11 @@ _interval_shared_docs = {} -_shared_docs_kwargs = dict( - klass="IntervalArray", qualname="arrays.IntervalArray", name="" -) +_shared_docs_kwargs = { + "klass": "IntervalArray", + "qualname": "arrays.IntervalArray", + "name": "", +} _interval_shared_docs[ @@ -127,14 +129,14 @@ @Appender( _interval_shared_docs["class"] - % dict( - klass="IntervalArray", - summary="Pandas array for interval data that are closed on the same side.", - versionadded="0.24.0", - name="", - extra_attributes="", - extra_methods="", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "summary": "Pandas array for interval data that are closed on the same side.", + "versionadded": "0.24.0", + "name": "", + "extra_attributes": "", + "extra_methods": "", + "examples": textwrap.dedent( """\ Examples -------- @@ -151,7 +153,7 @@ :meth:`IntervalArray.from_breaks`, and :meth:`IntervalArray.from_tuples`. """ ), - ) + } ) class IntervalArray(IntervalMixin, ExtensionArray): ndim = 1 @@ -319,9 +321,9 @@ def _from_factorized(cls, values, original): @classmethod @Appender( _interval_shared_docs["from_breaks"] - % dict( - klass="IntervalArray", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "examples": textwrap.dedent( """\ Examples -------- @@ -331,7 +333,7 @@ def _from_factorized(cls, values, original): Length: 3, closed: right, dtype: interval[int64] """ ), - ) + } ) def from_breaks(cls, breaks, closed="right", copy=False, dtype=None): breaks = maybe_convert_platform_interval(breaks) @@ -390,9 +392,9 @@ def from_breaks(cls, breaks, closed="right", copy=False, dtype=None): @classmethod @Appender( _interval_shared_docs["from_arrays"] - % dict( - klass="IntervalArray", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "examples": textwrap.dedent( """\ >>> pd.arrays.IntervalArray.from_arrays([0, 1, 2], [1, 2, 3]) <IntervalArray> @@ -400,7 +402,7 @@ def from_breaks(cls, breaks, closed="right", copy=False, dtype=None): Length: 3, closed: right, dtype: interval[int64] """ ), - ) + } ) def from_arrays(cls, left, right, closed="right", copy=False, dtype=None): left = maybe_convert_platform_interval(left) @@ -445,9 +447,9 @@ def from_arrays(cls, left, right, closed="right", copy=False, dtype=None): @classmethod @Appender( _interval_shared_docs["from_tuples"] - % dict( - klass="IntervalArray", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "examples": textwrap.dedent( """\ Examples -------- @@ -457,7 +459,7 @@ def from_arrays(cls, left, right, closed="right", copy=False, dtype=None): Length: 2, closed: right, dtype: interval[int64] """ ), - ) + } ) def from_tuples(cls, data, closed="right", copy=False, dtype=None): if len(data): @@ -904,7 +906,7 @@ def take(self, indices, *, allow_fill=False, fill_value=None, axis=None, **kwarg When `indices` contains negative values other than ``-1`` and `allow_fill` is True. """ - nv.validate_take(tuple(), kwargs) + nv.validate_take((), kwargs) fill_left = fill_right = fill_value if allow_fill: @@ -1144,9 +1146,9 @@ def mid(self): @Appender( _interval_shared_docs["overlaps"] - % dict( - klass="IntervalArray", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "examples": textwrap.dedent( """\ >>> data = [(0, 1), (1, 3), (2, 4)] >>> intervals = pd.arrays.IntervalArray.from_tuples(data) @@ -1156,7 +1158,7 @@ def mid(self): Length: 3, closed: right, dtype: interval[int64] """ ), - ) + } ) def overlaps(self, other): if isinstance(other, (IntervalArray, ABCIntervalIndex)): @@ -1207,9 +1209,9 @@ def closed(self): @Appender( _interval_shared_docs["set_closed"] - % dict( - klass="IntervalArray", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "examples": textwrap.dedent( """\ Examples -------- @@ -1224,7 +1226,7 @@ def closed(self): Length: 3, closed: both, dtype: interval[int64] """ ), - ) + } ) def set_closed(self, closed): if closed not in VALID_CLOSED: @@ -1360,7 +1362,7 @@ def __arrow_array__(self, type=None): """ @Appender( - _interval_shared_docs["to_tuples"] % dict(return_type="ndarray", examples="") + _interval_shared_docs["to_tuples"] % {"return_type": "ndarray", "examples": ""} ) def to_tuples(self, na_tuple=True): tuples = com.asarray_tuplesafe(zip(self._left, self._right)) @@ -1373,7 +1375,7 @@ def to_tuples(self, na_tuple=True): @Appender(_extension_array_shared_docs["repeat"] % _shared_docs_kwargs) def repeat(self, repeats, axis=None): - nv.validate_repeat(tuple(), dict(axis=axis)) + nv.validate_repeat((), {"axis": axis}) left_repeat = self.left.repeat(repeats) right_repeat = self.right.repeat(repeats) return self._shallow_copy(left=left_repeat, right=right_repeat) @@ -1412,9 +1414,9 @@ def repeat(self, repeats, axis=None): @Appender( _interval_shared_docs["contains"] - % dict( - klass="IntervalArray", - examples=textwrap.dedent( + % { + "klass": "IntervalArray", + "examples": textwrap.dedent( """\ >>> intervals = pd.arrays.IntervalArray.from_tuples([(0, 1), (1, 3), (2, 4)]) >>> intervals @@ -1423,7 +1425,7 @@ def repeat(self, repeats, axis=None): Length: 3, closed: right, dtype: interval[int64] """ ), - ) + } ) def contains(self, other): if isinstance(other, Interval): diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index c20955227d05e..f8d283f622d4d 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -112,7 +112,7 @@ def roundtrip(key, obj, **kwargs): tm.assert_frame_equal(o, roundtrip("frame", o)) # table - df = DataFrame(dict(A=range(5), B=range(5))) + df = DataFrame({"A": range(5), "B": range(5)}) df.to_hdf(path, "table", append=True) result = read_hdf(path, "table", where=["index>2"]) tm.assert_frame_equal(df[df.index > 2], result) @@ -370,7 +370,7 @@ def test_keys_ignore_hdf_softlink(self, setup_path): with ensure_clean_store(setup_path) as store: - df = DataFrame(dict(A=range(5), B=range(5))) + df = DataFrame({"A": range(5), "B": range(5)}) store.put("df", df) assert store.keys() == ["/df"] @@ -1081,7 +1081,7 @@ def check(format, index): def test_encoding(self, setup_path): with ensure_clean_store(setup_path) as store: - df = DataFrame(dict(A="foo", B="bar"), index=range(5)) + df = DataFrame({"A": "foo", "B": "bar"}, index=range(5)) df.loc[2, "A"] = np.nan df.loc[3, "B"] = np.nan _maybe_remove(store, "df") @@ -1458,7 +1458,7 @@ def check_col(key, name, size): store.get_storer(key).table.description, name ).itemsize, size - df = DataFrame(dict(A="foo", B="bar"), index=range(10)) + df = DataFrame({"A": "foo", "B": "bar"}, index=range(10)) # a min_itemsize that creates a data_column _maybe_remove(store, "df") @@ -2188,13 +2188,13 @@ def test_append_with_timedelta(self, setup_path): # append timedelta df = DataFrame( - dict( - A=Timestamp("20130101"), - B=[ + { + "A": Timestamp("20130101"), + "B": [ Timestamp("20130101") + timedelta(days=i, seconds=10) for i in range(10) ], - ) + } ) df["C"] = df["A"] - df["B"] df.loc[3:5, "C"] = np.nan @@ -2732,7 +2732,10 @@ def test_select_dtypes(self, setup_path): with ensure_clean_store(setup_path) as store: # with a Timestamp data column (GH #2637) df = DataFrame( - dict(ts=bdate_range("2012-01-01", periods=300), A=np.random.randn(300)) + { + "ts": bdate_range("2012-01-01", periods=300), + "A": np.random.randn(300), + } ) _maybe_remove(store, "df") store.append("df", df, data_columns=["ts", "A"]) @@ -2760,7 +2763,7 @@ def test_select_dtypes(self, setup_path): tm.assert_frame_equal(expected, result) # integer index - df = DataFrame(dict(A=np.random.rand(20), B=np.random.rand(20))) + df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) _maybe_remove(store, "df_int") store.append("df_int", df) result = store.select("df_int", "index<10 and columns=['A']") @@ -2769,11 +2772,11 @@ def test_select_dtypes(self, setup_path): # float index df = DataFrame( - dict( - A=np.random.rand(20), - B=np.random.rand(20), - index=np.arange(20, dtype="f8"), - ) + { + "A": np.random.rand(20), + "B": np.random.rand(20), + "index": np.arange(20, dtype="f8"), + } ) _maybe_remove(store, "df_float") store.append("df_float", df) @@ -2784,7 +2787,7 @@ def test_select_dtypes(self, setup_path): with ensure_clean_store(setup_path) as store: # floats w/o NaN - df = DataFrame(dict(cols=range(11), values=range(11)), dtype="float64") + df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") df["cols"] = (df["cols"] + 10).apply(str) store.append("df1", df, data_columns=True) @@ -2808,7 +2811,7 @@ def test_select_dtypes(self, setup_path): # tm.assert_frame_equal(expected, result) # not in first position float with NaN ok too - df = DataFrame(dict(cols=range(11), values=range(11)), dtype="float64") + df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") df["cols"] = (df["cols"] + 10).apply(str) df.iloc[1] = np.nan @@ -2835,15 +2838,15 @@ def test_select_with_many_inputs(self, setup_path): with ensure_clean_store(setup_path) as store: df = DataFrame( - dict( - ts=bdate_range("2012-01-01", periods=300), - A=np.random.randn(300), - B=range(300), - users=["a"] * 50 + { + "ts": bdate_range("2012-01-01", periods=300), + "A": np.random.randn(300), + "B": range(300), + "users": ["a"] * 50 + ["b"] * 50 + ["c"] * 100 + [f"a{i:03d}" for i in range(100)], - ) + } ) _maybe_remove(store, "df") store.append("df", df, data_columns=["ts", "A", "B", "users"]) @@ -3139,7 +3142,7 @@ def test_retain_index_attributes(self, setup_path): # GH 3499, losing frequency info on index recreation df = DataFrame( - dict(A=Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))) + {"A": Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))} ) with ensure_clean_store(setup_path) as store: @@ -3158,11 +3161,11 @@ def test_retain_index_attributes(self, setup_path): # try to append a table with a different frequency with catch_warnings(record=True): df2 = DataFrame( - dict( - A=Series( + { + "A": Series( range(3), index=date_range("2002-1-1", periods=3, freq="D") ) - ) + } ) store.append("data", df2) @@ -3171,8 +3174,8 @@ def test_retain_index_attributes(self, setup_path): # this is ok _maybe_remove(store, "df2") df2 = DataFrame( - dict( - A=Series( + { + "A": Series( range(3), index=[ Timestamp("20010101"), @@ -3180,15 +3183,15 @@ def test_retain_index_attributes(self, setup_path): Timestamp("20020101"), ], ) - ) + } ) store.append("df2", df2) df3 = DataFrame( - dict( - A=Series( + { + "A": Series( range(3), index=date_range("2002-1-1", periods=3, freq="D") ) - ) + } ) store.append("df2", df3) @@ -3201,25 +3204,26 @@ def test_retain_index_attributes2(self, setup_path): with catch_warnings(record=True): df = DataFrame( - dict( - A=Series( + { + "A": Series( range(3), index=date_range("2000-1-1", periods=3, freq="H") ) - ) + } ) df.to_hdf(path, "data", mode="w", append=True) df2 = DataFrame( - dict( - A=Series( + { + "A": Series( range(3), index=date_range("2002-1-1", periods=3, freq="D") ) - ) + } ) + df2.to_hdf(path, "data", append=True) idx = date_range("2000-1-1", periods=3, freq="H") idx.name = "foo" - df = DataFrame(dict(A=Series(range(3), index=idx))) + df = DataFrame({"A": Series(range(3), index=idx)}) df.to_hdf(path, "data", mode="w", append=True) assert read_hdf(path, "data").index.name == "foo" @@ -3228,7 +3232,7 @@ def test_retain_index_attributes2(self, setup_path): idx2 = date_range("2001-1-1", periods=3, freq="H") idx2.name = "bar" - df2 = DataFrame(dict(A=Series(range(3), index=idx2))) + df2 = DataFrame({"A": Series(range(3), index=idx2)}) df2.to_hdf(path, "data", append=True) assert read_hdf(path, "data").index.name is None @@ -3529,7 +3533,7 @@ def test_coordinates(self, setup_path): # get coordinates back & test vs frame _maybe_remove(store, "df") - df = DataFrame(dict(A=range(5), B=range(5))) + df = DataFrame({"A": range(5), "B": range(5)}) store.append("df", df) c = store.select_as_coordinates("df", ["index<3"]) assert (c.values == np.arange(3)).all() @@ -3791,12 +3795,12 @@ def test_nan_selection_bug_4858(self, setup_path): with ensure_clean_store(setup_path) as store: - df = DataFrame(dict(cols=range(6), values=range(6)), dtype="float64") + df = DataFrame({"cols": range(6), "values": range(6)}, dtype="float64") df["cols"] = (df["cols"] + 10).apply(str) df.iloc[0] = np.nan expected = DataFrame( - dict(cols=["13.0", "14.0", "15.0"], values=[3.0, 4.0, 5.0]), + {"cols": ["13.0", "14.0", "15.0"], "values": [3.0, 4.0, 5.0]}, index=[3, 4, 5], ) @@ -3810,7 +3814,7 @@ def test_start_stop_table(self, setup_path): with ensure_clean_store(setup_path) as store: # table - df = DataFrame(dict(A=np.random.rand(20), B=np.random.rand(20))) + df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) store.append("df", df) result = store.select("df", "columns=['A']", start=0, stop=5) @@ -3845,7 +3849,7 @@ def test_start_stop_fixed(self, setup_path): # fixed, GH 8287 df = DataFrame( - dict(A=np.random.rand(20), B=np.random.rand(20)), + {"A": np.random.rand(20), "B": np.random.rand(20)}, index=pd.date_range("20130101", periods=20), ) store.put("df", df) @@ -4478,7 +4482,7 @@ def test_categorical_conversion(self, setup_path): data = [4.3, 9.8] # Test without categories - df = DataFrame(dict(obsids=obsids, imgids=imgids, data=data)) + df = DataFrame({"obsids": obsids, "imgids": imgids, "data": data}) # We are expecting an empty DataFrame matching types of df expected = df.iloc[[], :]
- [ ] xref #38138 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Identify unnecessary dict call - rewrite as a literal in `./pandas/tests/io/pytables/test_store.py`, `./pandas/core/arrays/interval.py`
https://api.github.com/repos/pandas-dev/pandas/pulls/38263
2020-12-03T15:40:40Z
2020-12-03T22:58:33Z
2020-12-03T22:58:33Z
2020-12-03T22:58:47Z
BUG: to_hdf and HDFStore for subclasses
diff --git a/doc/source/reference/io.rst b/doc/source/reference/io.rst index 0037d4a4410c3..e755ce94812bb 100644 --- a/doc/source/reference/io.rst +++ b/doc/source/reference/io.rst @@ -83,6 +83,11 @@ HDFStore: PyTables (HDF5) HDFStore.groups HDFStore.walk +.. warning:: + + One can store a subclass of ``DataFrame`` or ``Series`` to HDF5, + but the type of the subclass is lost upon storing. + Feather ~~~~~~~ .. autosummary:: diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 3545dd8a89159..d12fefbab8797 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -241,7 +241,8 @@ I/O - Bug in :func:`read_csv` not accepting ``usecols`` with different length than ``names`` for ``engine="python"`` (:issue:`16469`) - Bug in :func:`read_csv` raising ``TypeError`` when ``names`` and ``parse_dates`` is specified for ``engine="c"`` (:issue:`33699`) - Allow custom error values for parse_dates argument of :func:`read_sql`, :func:`read_sql_query` and :func:`read_sql_table` (:issue:`35185`) -- +- Bug in :func:`to_hdf` raising ``KeyError`` when trying to apply + for subclasses of ``DataFrame`` or ``Series`` (:issue:`33748`). Period ^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9b0c3caa0b407..fbf502ffa280c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2505,6 +2505,11 @@ def to_hdf( In order to add another DataFrame or Series to an existing HDF file please use append mode and a different a key. + .. warning:: + + One can store a subclass of ``DataFrame`` or ``Series`` to HDF5, + but the type of the subclass is lost upon storing. + For more information see the :ref:`user guide <io.hdf5>`. Parameters diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 3fe251d300856..c22f6806e932e 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -1646,8 +1646,10 @@ def error(t): "nor a value are passed" ) else: - _TYPE_MAP = {Series: "series", DataFrame: "frame"} - pt = _TYPE_MAP[type(value)] + if isinstance(value, Series): + pt = "series" + else: + pt = "frame" # we are actually a table if format == "table": diff --git a/pandas/tests/io/pytables/test_subclass.py b/pandas/tests/io/pytables/test_subclass.py new file mode 100644 index 0000000000000..196f729cd6eb2 --- /dev/null +++ b/pandas/tests/io/pytables/test_subclass.py @@ -0,0 +1,44 @@ +import numpy as np + +from pandas import DataFrame, Series +import pandas._testing as tm +from pandas.tests.io.pytables.common import ensure_clean_path + +from pandas.io.pytables import HDFStore, read_hdf + + +class TestHDFStoreSubclass: + # GH 33748 + def test_supported_for_subclass_dataframe(self): + data = {"a": [1, 2], "b": [3, 4]} + sdf = tm.SubclassedDataFrame(data, dtype=np.intp) + + expected = DataFrame(data, dtype=np.intp) + + with ensure_clean_path("temp.h5") as path: + sdf.to_hdf(path, "df") + result = read_hdf(path, "df") + tm.assert_frame_equal(result, expected) + + with ensure_clean_path("temp.h5") as path: + with HDFStore(path) as store: + store.put("df", sdf) + result = read_hdf(path, "df") + tm.assert_frame_equal(result, expected) + + def test_supported_for_subclass_series(self): + data = [1, 2, 3] + sser = tm.SubclassedSeries(data, dtype=np.intp) + + expected = Series(data, dtype=np.intp) + + with ensure_clean_path("temp.h5") as path: + sser.to_hdf(path, "ser") + result = read_hdf(path, "ser") + tm.assert_series_equal(result, expected) + + with ensure_clean_path("temp.h5") as path: + with HDFStore(path) as store: + store.put("ser", sser) + result = read_hdf(path, "ser") + tm.assert_series_equal(result, expected)
- [ ] closes #33748 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Fix the bug that the subclasses of a dataframe and a series cannot be saved ``to_hdf``. The tests were added. When testing I found that ``assert_frame_equal`` does not work on subclasses as well - probably need to fix it in a separate PR. For now in the tests I compare values only.
https://api.github.com/repos/pandas-dev/pandas/pulls/38262
2020-12-03T14:34:39Z
2020-12-19T02:19:00Z
2020-12-19T02:19:00Z
2020-12-19T02:19:07Z
C408 fix
diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index 8d93fbcc063f4..244302e34337d 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -521,13 +521,13 @@ def test_meta_non_iterable(self): class TestNestedToRecord: def test_flat_stays_flat(self): - recs = [dict(flat1=1, flat2=2), dict(flat1=3, flat2=4)] + recs = [{"flat1": 1, "flat2": 2}, {"flat3": 3, "flat2": 4}] result = nested_to_record(recs) expected = recs assert result == expected def test_one_level_deep_flattens(self): - data = dict(flat1=1, dict1=dict(c=1, d=2)) + data = {"flat1": 1, "dict1": {"c": 1, "d": 2}} result = nested_to_record(data) expected = {"dict1.c": 1, "dict1.d": 2, "flat1": 1} @@ -535,7 +535,11 @@ def test_one_level_deep_flattens(self): assert result == expected def test_nested_flattens(self): - data = dict(flat1=1, dict1=dict(c=1, d=2), nested=dict(e=dict(c=1, d=2), d=2)) + data = { + "flat1": 1, + "dict1": {"c": 1, "d": 2}, + "nested": {"e": {"c": 1, "d": 2}, "d": 2}, + } result = nested_to_record(data) expected = { diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 086c0b7ba08b2..ced0d540f33ef 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -757,10 +757,10 @@ def test_array_reshaped(self, shape): def test_array_list(self): arr_list = [ "a", - list(), - dict(), - dict(), - list(), + [], + {}, + {}, + [], 42, 97.8, ["a", "b"], @@ -797,9 +797,9 @@ def test_0d_array(self): ([42, {}, "a"], TypeError, {}), ([42, ["a"], 42], ValueError, {}), (["a", "b", [], "c"], ValueError, {}), - ([{"a": "b"}], ValueError, dict(labelled=True)), - ({"a": {"b": {"c": 42}}}, ValueError, dict(labelled=True)), - ([{"a": 42, "b": 23}, {"c": 17}], ValueError, dict(labelled=True)), + ([{"a": "b"}], ValueError, {"labelled": True}), + ({"a": {"b": {"c": 42}}}, ValueError, {"labelled": True}), + ([{"a": 42, "b": 23}, {"c": 17}], ValueError, {"labelled": True}), ], ) def test_array_numpy_except(self, bad_input, exc_type, kwargs): @@ -852,8 +852,8 @@ def test_dataframe(self, orient, numpy): columns=["x", "y", "z"], dtype=dtype, ) - encode_kwargs = {} if orient is None else dict(orient=orient) - decode_kwargs = {} if numpy is None else dict(numpy=numpy) + encode_kwargs = {} if orient is None else {"orient": orient} + decode_kwargs = {} if numpy is None else {"numpy": numpy} assert (df.dtypes == dtype).all() output = ujson.decode(ujson.encode(df, **encode_kwargs), **decode_kwargs) @@ -884,7 +884,7 @@ def test_dataframe_nested(self, orient): ) nested = {"df1": df, "df2": df.copy()} - kwargs = {} if orient is None else dict(orient=orient) + kwargs = {} if orient is None else {"orient": orient} exp = { "df1": ujson.decode(ujson.encode(df, **kwargs)), @@ -902,7 +902,7 @@ def test_dataframe_numpy_labelled(self, orient): columns=["x", "y", "z"], dtype=int, ) - kwargs = {} if orient is None else dict(orient=orient) + kwargs = {} if orient is None else {"orient": orient} output = DataFrame( *ujson.decode(ujson.encode(df, **kwargs), numpy=True, labelled=True) @@ -925,8 +925,8 @@ def test_series(self, orient, numpy): ).sort_values() assert s.dtype == dtype - encode_kwargs = {} if orient is None else dict(orient=orient) - decode_kwargs = {} if numpy is None else dict(numpy=numpy) + encode_kwargs = {} if orient is None else {"orient": orient} + decode_kwargs = {} if numpy is None else {"numpy": numpy} output = ujson.decode(ujson.encode(s, **encode_kwargs), **decode_kwargs) assert s.dtype == dtype @@ -953,7 +953,7 @@ def test_series_nested(self, orient): [10, 20, 30, 40, 50, 60], name="series", index=[6, 7, 8, 9, 10, 15] ).sort_values() nested = {"s1": s, "s2": s.copy()} - kwargs = {} if orient is None else dict(orient=orient) + kwargs = {} if orient is None else {"orient": orient} exp = { "s1": ujson.decode(ujson.encode(s, **kwargs)),
- [x] xref #38138 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Rewrote dict calls to dict literals in the following files ./pandas/tests/io/json/test_ujson.py ./pandas/tests/io/json/test_normalize.py Also changed list calls to literals in line 730 of the following file pandas/tests/io/json/test_ujson.py
https://api.github.com/repos/pandas-dev/pandas/pulls/38260
2020-12-03T11:45:08Z
2020-12-04T14:23:37Z
2020-12-04T14:23:37Z
2020-12-04T14:23:41Z
Backport PR #38244: REGR: unstack on 'int' dtype prevent fillna to work
diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst index 0e2e510147603..fbb12cb38448a 100644 --- a/doc/source/whatsnew/v1.1.5.rst +++ b/doc/source/whatsnew/v1.1.5.rst @@ -20,6 +20,7 @@ Fixed regressions - Fixed regression in inplace operations on :class:`Series` with ``ExtensionDtype`` with NumPy dtyped operand (:issue:`37910`) - Fixed regression in metadata propagation for ``groupby`` iterator (:issue:`37343`) - Fixed regression in :class:`MultiIndex` constructed from a :class:`DatetimeIndex` not retaining frequency (:issue:`35563`) +- Fixed regression in :meth:`DataFrame.unstack` with columns with integer dtype (:issue:`37115`) - Fixed regression in indexing on a :class:`Series` with ``CategoricalDtype`` after unpickling (:issue:`37631`) - Fixed regression in :meth:`DataFrame.groupby` aggregation with out-of-bounds datetime objects in an object-dtype column (:issue:`36003`) - Fixed regression in ``df.groupby(..).rolling(..)`` with the resulting :class:`MultiIndex` when grouping by a label that is in the index (:issue:`37641`) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 709924d800ebc..944652924611e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1410,7 +1410,7 @@ def _unstack(self, unstacker, fill_value, new_placement): new_values = new_values.T[mask] new_placement = new_placement[mask] - blocks = [self.make_block_same_class(new_values, placement=new_placement)] + blocks = [make_block(new_values, placement=new_placement)] return blocks, mask def quantile(self, qs, interpolation="linear", axis: int = 0): diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 1b452658cc219..506a5a5706673 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -1315,3 +1315,26 @@ def test_stack_positional_level_duplicate_column_names(): expected = pd.DataFrame([[1, 1], [1, 1]], index=new_index, columns=new_columns) tm.assert_frame_equal(result, expected) + + +def test_unstack_with_missing_int_cast_to_float(): + # https://github.com/pandas-dev/pandas/issues/37115 + df = DataFrame( + {"a": ["A", "A", "B"], "b": ["ca", "cb", "cb"], "v": [10] * 3} + ).set_index(["a", "b"]) + + # add another int column to get 2 blocks + df["is_"] = 1 + assert len(df._mgr.blocks) == 2 + + result = df.unstack("b") + result[("is_", "ca")] = result[("is_", "ca")].fillna(0) + + expected = DataFrame( + [[10.0, 10.0, 1.0, 1.0], [np.nan, 10.0, 0.0, 1.0]], + index=Index(["A", "B"], dtype="object", name="a"), + columns=MultiIndex.from_tuples( + [("v", "ca"), ("v", "cb"), ("is_", "ca"), ("is_", "cb")], names=[None, "b"], + ), + ) + tm.assert_frame_equal(result, expected)
Backport PR #38244
https://api.github.com/repos/pandas-dev/pandas/pulls/38259
2020-12-03T11:10:30Z
2020-12-03T12:02:28Z
2020-12-03T12:02:28Z
2020-12-03T12:02:33Z
BUG: groupby.apply on the NaN group drops values with original axes return
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 8dbc6728dccfe..b166f0a360d26 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -771,6 +771,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.groupby` dropped ``nan`` groups from result with ``dropna=False`` when grouping over a single column (:issue:`35646`, :issue:`35542`) - Bug in :meth:`.DataFrameGroupBy.head`, :meth:`.DataFrameGroupBy.tail`, :meth:`SeriesGroupBy.head`, and :meth:`SeriesGroupBy.tail` would raise when used with ``axis=1`` (:issue:`9772`) - Bug in :meth:`.DataFrameGroupBy.transform` would raise when used with ``axis=1`` and a transformation kernel (e.g. "shift") (:issue:`36308`) +- Bug in :meth:`.DataFrameGroupBy.apply` dropped values on ``nan`` group when returning the same axes with the original frame (:issue:`38227`) - Bug in :meth:`.DataFrameGroupBy.quantile` couldn't handle with arraylike ``q`` when grouping by columns (:issue:`33795`) - Bug in :meth:`DataFrameGroupBy.rank` with ``datetime64tz`` or period dtype incorrectly casting results to those dtypes instead of returning ``float64`` dtype (:issue:`38187`) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 583fc6bf8ddb7..4b9e554aa8bc2 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1216,7 +1216,7 @@ def reset_identity(values): if not not_indexed_same: result = concat(values, axis=self.axis) - ax = self._selected_obj._get_axis(self.axis) + ax = self.filter(lambda x: True).axes[self.axis] # this is a very unfortunate situation # we can't use reindex to restore the original order diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index b2074dcb08c95..975cebe16dc55 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -1087,3 +1087,25 @@ def test_apply_by_cols_equals_apply_by_rows_transposed(): tm.assert_frame_equal(by_cols, by_rows.T) tm.assert_frame_equal(by_cols, df) + + +def test_apply_dropna_with_indexed_same(): + # GH 38227 + + df = DataFrame( + { + "col": [1, 2, 3, 4, 5], + "group": ["a", np.nan, np.nan, "b", "b"], + }, + index=list("xxyxz"), + ) + result = df.groupby("group").apply(lambda x: x) + expected = DataFrame( + { + "col": [1, 4, 5], + "group": ["a", "b", "b"], + }, + index=list("xxz"), + ) + + tm.assert_frame_equal(result, expected)
- [x] closes #38227 - [x] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38257
2020-12-03T08:22:13Z
2020-12-04T23:45:03Z
2020-12-04T23:45:03Z
2020-12-08T00:39:56Z
TST: split unfocused groupby test
diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 720c7f8c2324d..12e570490487d 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -281,67 +281,93 @@ def test_arg_passthru(): tm.assert_index_equal(result.columns, expected_columns) -def test_non_cython_api(): - - # GH5610 - # non-cython calls should not include the grouper - - df = DataFrame( - [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], columns=["A", "B", "C"] - ) - g = df.groupby("A") - gni = df.groupby("A", as_index=False) - - # mad - expected = DataFrame([[0], [np.nan]], columns=["B"], index=[1, 3]) - expected.index.name = "A" - result = g.mad() - tm.assert_frame_equal(result, expected) - - expected = DataFrame([[1, 0.0], [3, np.nan]], columns=["A", "B"], index=[0, 1]) - result = gni.mad() - tm.assert_frame_equal(result, expected) - - # describe - expected_index = Index([1, 3], name="A") - expected_col = pd.MultiIndex( - levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], - codes=[[0] * 8, list(range(8))], - ) - expected = DataFrame( - [ - [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], - [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], - ], - index=expected_index, - columns=expected_col, - ) - result = g.describe() - tm.assert_frame_equal(result, expected) - - expected = pd.concat( - [ - df[df.A == 1].describe().unstack().to_frame().T, - df[df.A == 3].describe().unstack().to_frame().T, - ] - ) - expected.index = Index([0, 1]) - result = gni.describe() - tm.assert_frame_equal(result, expected) - - # any - expected = DataFrame( - [[True, True], [False, True]], columns=["B", "C"], index=[1, 3] - ) - expected.index.name = "A" - result = g.any() - tm.assert_frame_equal(result, expected) +class TestGroupByNonCythonPaths: + # GH#5610 non-cython calls should not include the grouper + # Tests for code not expected to go through cython paths. + + @pytest.fixture + def df(self): + df = DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], + columns=["A", "B", "C"], + ) + return df + + @pytest.fixture + def gb(self, df): + gb = df.groupby("A") + return gb + + @pytest.fixture + def gni(self, df): + gni = df.groupby("A", as_index=False) + return gni + + # TODO: non-unique columns, as_index=False + def test_idxmax(self, gb): + # object dtype so idxmax goes through _aggregate_item_by_item + # GH#5610 + # non-cython calls should not include the grouper + expected = DataFrame([[0.0], [np.nan]], columns=["B"], index=[1, 3]) + expected.index.name = "A" + result = gb.idxmax() + tm.assert_frame_equal(result, expected) + + def test_idxmin(self, gb): + # object dtype so idxmax goes through _aggregate_item_by_item + # GH#5610 + # non-cython calls should not include the grouper + expected = DataFrame([[0.0], [np.nan]], columns=["B"], index=[1, 3]) + expected.index.name = "A" + result = gb.idxmin() + tm.assert_frame_equal(result, expected) + + def test_any(self, gb): + expected = DataFrame( + [[True, True], [False, True]], columns=["B", "C"], index=[1, 3] + ) + expected.index.name = "A" + result = gb.any() + tm.assert_frame_equal(result, expected) + + def test_mad(self, gb, gni): + # mad + expected = DataFrame([[0], [np.nan]], columns=["B"], index=[1, 3]) + expected.index.name = "A" + result = gb.mad() + tm.assert_frame_equal(result, expected) + + expected = DataFrame([[1, 0.0], [3, np.nan]], columns=["A", "B"], index=[0, 1]) + result = gni.mad() + tm.assert_frame_equal(result, expected) + + def test_describe(self, df, gb, gni): + # describe + expected_index = Index([1, 3], name="A") + expected_col = pd.MultiIndex( + levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], + codes=[[0] * 8, list(range(8))], + ) + expected = DataFrame( + [ + [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], + [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + ], + index=expected_index, + columns=expected_col, + ) + result = gb.describe() + tm.assert_frame_equal(result, expected) - # idxmax - expected = DataFrame([[0.0], [np.nan]], columns=["B"], index=[1, 3]) - expected.index.name = "A" - result = g.idxmax() - tm.assert_frame_equal(result, expected) + expected = pd.concat( + [ + df[df.A == 1].describe().unstack().to_frame().T, + df[df.A == 3].describe().unstack().to_frame().T, + ] + ) + expected.index = Index([0, 1]) + result = gni.describe() + tm.assert_frame_equal(result, expected) def test_cython_api2():
https://api.github.com/repos/pandas-dev/pandas/pulls/38255
2020-12-03T02:57:59Z
2020-12-03T14:30:45Z
2020-12-03T14:30:45Z
2020-12-03T15:48:30Z
REF: simplify _cython_operation return
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 00561e5441e00..5e78fe8fea00c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1087,7 +1087,7 @@ def py_fallback(bvalues: ArrayLike) -> ArrayLike: def blk_func(bvalues: ArrayLike) -> ArrayLike: try: - result, _ = self.grouper._cython_operation( + result = self.grouper._cython_operation( "aggregate", bvalues, how, axis=1, min_count=min_count ) except NotImplementedError: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 422cf78bc927d..798c0742f03e5 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -50,7 +50,7 @@ class providing the base-class of operations. from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, Substitution, cache_readonly, doc -from pandas.core.dtypes.cast import maybe_cast_result, maybe_downcast_to_dtype +from pandas.core.dtypes.cast import maybe_downcast_to_dtype from pandas.core.dtypes.common import ( ensure_float, is_bool_dtype, @@ -994,7 +994,7 @@ def _cython_transform( continue try: - result, _ = self.grouper._cython_operation( + result = self.grouper._cython_operation( "transform", obj._values, how, axis, **kwargs ) except NotImplementedError: @@ -1069,12 +1069,13 @@ def _cython_agg_general( if numeric_only and not is_numeric: continue - result, agg_names = self.grouper._cython_operation( + result = self.grouper._cython_operation( "aggregate", obj._values, how, axis=0, min_count=min_count ) - if agg_names: + if how == "ohlc": # e.g. ohlc + agg_names = ["open", "high", "low", "close"] assert len(agg_names) == result.shape[1] for result_column, result_name in zip(result.T, agg_names): key = base.OutputKey(label=result_name, position=idx) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 8046be669ea51..d98c55755042e 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -370,8 +370,6 @@ def get_group_levels(self) -> List[Index]: _cython_arity = {"ohlc": 4} # OHLC - _name_functions = {"ohlc": ["open", "high", "low", "close"]} - def _is_builtin_func(self, arg): """ if we define a builtin function for this argument, return it, @@ -492,36 +490,33 @@ def _ea_wrap_cython_operation( # All of the functions implemented here are ordinal, so we can # operate on the tz-naive equivalents values = values.view("M8[ns]") - res_values, names = self._cython_operation( + res_values = self._cython_operation( kind, values, how, axis, min_count, **kwargs ) if how in ["rank"]: # preserve float64 dtype - return res_values, names + return res_values res_values = res_values.astype("i8", copy=False) result = type(orig_values)._simple_new(res_values, dtype=orig_values.dtype) - return result, names + return result elif is_integer_dtype(values.dtype) or is_bool_dtype(values.dtype): # IntegerArray or BooleanArray values = ensure_int_or_float(values) - res_values, names = self._cython_operation( + res_values = self._cython_operation( kind, values, how, axis, min_count, **kwargs ) result = maybe_cast_result(result=res_values, obj=orig_values, how=how) - return result, names + return result raise NotImplementedError(values.dtype) def _cython_operation( self, kind: str, values, how: str, axis: int, min_count: int = -1, **kwargs - ) -> Tuple[np.ndarray, Optional[List[str]]]: + ) -> np.ndarray: """ - Returns the values of a cython operation as a Tuple of [data, names]. - - Names is only useful when dealing with 2D results, like ohlc - (see self._name_functions). + Returns the values of a cython operation. """ orig_values = values assert kind in ["transform", "aggregate"] @@ -619,8 +614,6 @@ def _cython_operation( if vdim == 1 and arity == 1: result = result[:, 0] - names: Optional[List[str]] = self._name_functions.get(how, None) - if swapped: result = result.swapaxes(0, axis) @@ -630,7 +623,7 @@ def _cython_operation( dtype = maybe_cast_result_dtype(orig_values.dtype, how) result = maybe_downcast_to_dtype(result, dtype) - return result, names + return result def _aggregate( self, result, counts, values, comp_ids, agg_func, min_count: int = -1
https://api.github.com/repos/pandas-dev/pandas/pulls/38253
2020-12-03T01:24:09Z
2020-12-03T14:29:29Z
2020-12-03T14:29:29Z
2020-12-03T15:51:02Z
CI: delete unused import in groupby/groupby.py
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 422cf78bc927d..583fc6bf8ddb7 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -50,7 +50,7 @@ class providing the base-class of operations. from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, Substitution, cache_readonly, doc -from pandas.core.dtypes.cast import maybe_cast_result, maybe_downcast_to_dtype +from pandas.core.dtypes.cast import maybe_downcast_to_dtype from pandas.core.dtypes.common import ( ensure_float, is_bool_dtype,
Fixes a `flake8` bug on current master: ``` (pandas-dev) andrewwieteska@Andrews-MacBook-Pro pandas % flake8 pandas/core/groupby/groupby.py pandas/core/groupby/groupby.py:53:1: F401 'pandas.core.dtypes.cast.maybe_cast_result' imported but unused ```
https://api.github.com/repos/pandas-dev/pandas/pulls/38252
2020-12-03T00:15:45Z
2020-12-03T02:24:55Z
2020-12-03T02:24:55Z
2020-12-03T02:35:19Z
ENH: implement _should_compare/_is_comparable_dtype for all Index subclasses
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 40fcc824992b7..874ece8742451 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4904,16 +4904,31 @@ def get_indexer_non_unique(self, target): # Treat boolean labels passed to a numeric index as not found. Without # this fix False and True would be treated as 0 and 1 respectively. # (GH #16877) - no_matches = -1 * np.ones(self.shape, dtype=np.intp) - return no_matches, no_matches + return self._get_indexer_non_comparable(target, method=None, unique=False) pself, ptarget = self._maybe_promote(target) if pself is not self or ptarget is not target: return pself.get_indexer_non_unique(ptarget) - if not self._is_comparable_dtype(target.dtype): - no_matches = -1 * np.ones(self.shape, dtype=np.intp) - return no_matches, no_matches + if not self._should_compare(target): + return self._get_indexer_non_comparable(target, method=None, unique=False) + + if not is_dtype_equal(self.dtype, target.dtype): + # TODO: if object, could use infer_dtype to pre-empt costly + # conversion if still non-comparable? + dtype = find_common_type([self.dtype, target.dtype]) + if ( + dtype.kind in ["i", "u"] + and is_categorical_dtype(target.dtype) + and target.hasnans + ): + # FIXME: find_common_type incorrect with Categorical GH#38240 + # FIXME: some cases where float64 cast can be lossy? + dtype = np.dtype(np.float64) + + this = self.astype(dtype, copy=False) + that = target.astype(dtype, copy=False) + return this.get_indexer_non_unique(that) if is_categorical_dtype(target.dtype): tgt_values = np.asarray(target) @@ -4966,7 +4981,7 @@ def _get_indexer_non_comparable(self, target: "Index", method, unique: bool = Tr If doing an inequality check, i.e. method is not None. """ if method is not None: - other = _unpack_nested_dtype(target) + other = unpack_nested_dtype(target) raise TypeError(f"Cannot compare dtypes {self.dtype} and {other.dtype}") no_matches = -1 * np.ones(target.shape, dtype=np.intp) @@ -5017,7 +5032,7 @@ def _should_compare(self, other: "Index") -> bool: """ Check if `self == other` can ever have non-False entries. """ - other = _unpack_nested_dtype(other) + other = unpack_nested_dtype(other) dtype = other.dtype return self._is_comparable_dtype(dtype) or is_object_dtype(dtype) @@ -6170,7 +6185,7 @@ def get_unanimous_names(*indexes: Index) -> Tuple[Label, ...]: return names -def _unpack_nested_dtype(other: Index) -> Index: +def unpack_nested_dtype(other: Index) -> Index: """ When checking if our dtype is comparable with another, we need to unpack CategoricalDtype to look at its categories.dtype. diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index abf70fd150345..377fff5f85e92 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -554,6 +554,9 @@ def _maybe_cast_slice_bound(self, label, side: str, kind): # -------------------------------------------------------------------- + def _is_comparable_dtype(self, dtype): + return self.categories._is_comparable_dtype(dtype) + def take_nd(self, *args, **kwargs): """Alias for `take`""" warnings.warn( diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 18be4bf225da5..049391ed1ad57 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -11,7 +11,7 @@ from pandas._libs import lib from pandas._libs.interval import Interval, IntervalMixin, IntervalTree from pandas._libs.tslibs import BaseOffset, Timedelta, Timestamp, to_offset -from pandas._typing import AnyArrayLike, Label +from pandas._typing import AnyArrayLike, DtypeObj, Label from pandas.errors import InvalidIndexError from pandas.util._decorators import Appender, Substitution, cache_readonly from pandas.util._exceptions import rewrite_exception @@ -38,6 +38,7 @@ is_object_dtype, is_scalar, ) +from pandas.core.dtypes.dtypes import IntervalDtype from pandas.core.algorithms import take_1d from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs @@ -50,6 +51,7 @@ default_pprint, ensure_index, maybe_extract_name, + unpack_nested_dtype, ) from pandas.core.indexes.datetimes import DatetimeIndex, date_range from pandas.core.indexes.extension import ExtensionIndex, inherit_names @@ -807,6 +809,19 @@ def _convert_list_indexer(self, keyarr): return locs + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + if not isinstance(dtype, IntervalDtype): + return False + common_subtype = find_common_type([self.dtype.subtype, dtype.subtype]) + return not is_object_dtype(common_subtype) + + def _should_compare(self, other) -> bool: + if not super()._should_compare(other): + return False + other = unpack_nested_dtype(other) + return other.closed == self.closed + + # TODO: use should_compare and get rid of _is_non_comparable_own_type def _is_non_comparable_own_type(self, other: "IntervalIndex") -> bool: # different closed or incompatible subtype -> no matches @@ -814,8 +829,7 @@ def _is_non_comparable_own_type(self, other: "IntervalIndex") -> bool: # is_comparable_dtype GH#19371 if self.closed != other.closed: return True - common_subtype = find_common_type([self.dtype.subtype, other.dtype.subtype]) - return is_object_dtype(common_subtype) + return not self._is_comparable_dtype(other.dtype) # -------------------------------------------------------------------- diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 6af6555007c2f..0287f6f282685 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -20,7 +20,7 @@ from pandas._libs import algos as libalgos, index as libindex, lib from pandas._libs.hashtable import duplicated_int64 -from pandas._typing import AnyArrayLike, Label, Scalar, Shape +from pandas._typing import AnyArrayLike, DtypeObj, Label, Scalar, Shape from pandas.compat.numpy import function as nv from pandas.errors import InvalidIndexError, PerformanceWarning, UnsortedIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -3582,6 +3582,9 @@ def union(self, other, sort=None): zip(*uniq_tuples), sortorder=0, names=result_names ) + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + return is_object_dtype(dtype) + def intersection(self, other, sort=False): """ Form the intersection of two MultiIndex objects. @@ -3617,15 +3620,9 @@ def intersection(self, other, sort=False): def _intersection(self, other, sort=False): other, result_names = self._convert_can_do_setop(other) - if not is_object_dtype(other.dtype): + if not self._is_comparable_dtype(other.dtype): # The intersection is empty - # TODO: we have no tests that get here - return MultiIndex( - levels=self.levels, - codes=[[]] * self.nlevels, - names=result_names, - verify_integrity=False, - ) + return self[:0].rename(result_names) lvals = self._values rvals = other._values diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 12f61fc44582d..d4562162f7c10 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -4,7 +4,7 @@ import numpy as np from pandas._libs import index as libindex, lib -from pandas._typing import Dtype, Label +from pandas._typing import Dtype, DtypeObj, Label from pandas.util._decorators import doc from pandas.core.dtypes.cast import astype_nansafe @@ -148,6 +148,10 @@ def _convert_tolerance(self, tolerance, target): ) return tolerance + def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: + # If we ever have BoolIndex or ComplexIndex, this may need to be tightened + return is_numeric_dtype(dtype) + @classmethod def _assert_safe_casting(cls, data, subarr): """ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index ba49c51c9db8e..27ee370d1c036 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1249,10 +1249,9 @@ def test_get_indexer_numeric_index_boolean_target(self, method, idx_class): if method == "get_indexer": tm.assert_numpy_array_equal(result, expected) else: - expected = np.array([-1, -1, -1, -1], dtype=np.intp) - + missing = np.arange(3, dtype=np.intp) tm.assert_numpy_array_equal(result[0], expected) - tm.assert_numpy_array_equal(result[1], expected) + tm.assert_numpy_array_equal(result[1], missing) def test_get_indexer_with_NA_values( self, unique_nulls_fixture, unique_nulls_fixture2 @@ -2346,5 +2345,6 @@ def construct(dtype): else: no_matches = np.array([-1] * 6, dtype=np.intp) + missing = np.arange(6, dtype=np.intp) tm.assert_numpy_array_equal(result[0], no_matches) - tm.assert_numpy_array_equal(result[1], no_matches) + tm.assert_numpy_array_equal(result[1], missing)
Fixes some problems in get_indexer_non_unique that AFAICT are not actually causing any problems. Categorical kludge is needed because of #38240.
https://api.github.com/repos/pandas-dev/pandas/pulls/38251
2020-12-02T22:27:22Z
2020-12-04T14:20:41Z
2020-12-04T14:20:41Z
2020-12-04T15:20:27Z
PERF: timeseries comparison ops
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 979ca70bad9b3..66906f8463336 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -936,7 +936,8 @@ def _cmp_method(self, other, op): return result other_vals = self._unbox(other) - result = op(self._ndarray, other_vals) + # GH#37462 comparison on i8 values is almost 2x faster than M8/m8 + result = op(self._ndarray.view("i8"), other_vals.view("i8")) o_mask = isna(other) if self._hasnans | np.any(o_mask):
- [x] closes #37462 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Locally this gets me to within 3-4% of 1.1.4 on the asv mentioned in #37462
https://api.github.com/repos/pandas-dev/pandas/pulls/38248
2020-12-02T19:20:27Z
2020-12-03T14:19:36Z
2020-12-03T14:19:35Z
2020-12-03T15:51:22Z
BUG: Limited available colors
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 13ddeb2a89133..0262199fd1b22 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -292,6 +292,7 @@ Other enhancements - Improved error reporting for subsetting columns of a :class:`.DataFrameGroupBy` with ``axis=1`` (:issue:`37725`) - Implement method ``cross`` for :meth:`DataFrame.merge` and :meth:`DataFrame.join` (:issue:`5401`) - When :func:`read_csv/sas/json` are called with ``chuncksize``/``iterator`` they can be used in a ``with`` statement as they return context-managers (:issue:`38225`) +- Augmented the list of named colors available for styling Excel exports, enabling all of CSS4 colors (:issue:`38247`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/formats/_color_data.py b/pandas/io/formats/_color_data.py new file mode 100644 index 0000000000000..e5b72b2befa4f --- /dev/null +++ b/pandas/io/formats/_color_data.py @@ -0,0 +1,155 @@ +# GH37967: Enable the use of CSS named colors, as defined in +# matplotlib.colors.CSS4_COLORS, when exporting to Excel. +# This data has been copied here, instead of being imported from matplotlib, +# not to have ``to_excel`` methods require matplotlib. +# source: matplotlib._color_data (3.3.3) +CSS4_COLORS = { + "aliceblue": "F0F8FF", + "antiquewhite": "FAEBD7", + "aqua": "00FFFF", + "aquamarine": "7FFFD4", + "azure": "F0FFFF", + "beige": "F5F5DC", + "bisque": "FFE4C4", + "black": "000000", + "blanchedalmond": "FFEBCD", + "blue": "0000FF", + "blueviolet": "8A2BE2", + "brown": "A52A2A", + "burlywood": "DEB887", + "cadetblue": "5F9EA0", + "chartreuse": "7FFF00", + "chocolate": "D2691E", + "coral": "FF7F50", + "cornflowerblue": "6495ED", + "cornsilk": "FFF8DC", + "crimson": "DC143C", + "cyan": "00FFFF", + "darkblue": "00008B", + "darkcyan": "008B8B", + "darkgoldenrod": "B8860B", + "darkgray": "A9A9A9", + "darkgreen": "006400", + "darkgrey": "A9A9A9", + "darkkhaki": "BDB76B", + "darkmagenta": "8B008B", + "darkolivegreen": "556B2F", + "darkorange": "FF8C00", + "darkorchid": "9932CC", + "darkred": "8B0000", + "darksalmon": "E9967A", + "darkseagreen": "8FBC8F", + "darkslateblue": "483D8B", + "darkslategray": "2F4F4F", + "darkslategrey": "2F4F4F", + "darkturquoise": "00CED1", + "darkviolet": "9400D3", + "deeppink": "FF1493", + "deepskyblue": "00BFFF", + "dimgray": "696969", + "dimgrey": "696969", + "dodgerblue": "1E90FF", + "firebrick": "B22222", + "floralwhite": "FFFAF0", + "forestgreen": "228B22", + "fuchsia": "FF00FF", + "gainsboro": "DCDCDC", + "ghostwhite": "F8F8FF", + "gold": "FFD700", + "goldenrod": "DAA520", + "gray": "808080", + "green": "008000", + "greenyellow": "ADFF2F", + "grey": "808080", + "honeydew": "F0FFF0", + "hotpink": "FF69B4", + "indianred": "CD5C5C", + "indigo": "4B0082", + "ivory": "FFFFF0", + "khaki": "F0E68C", + "lavender": "E6E6FA", + "lavenderblush": "FFF0F5", + "lawngreen": "7CFC00", + "lemonchiffon": "FFFACD", + "lightblue": "ADD8E6", + "lightcoral": "F08080", + "lightcyan": "E0FFFF", + "lightgoldenrodyellow": "FAFAD2", + "lightgray": "D3D3D3", + "lightgreen": "90EE90", + "lightgrey": "D3D3D3", + "lightpink": "FFB6C1", + "lightsalmon": "FFA07A", + "lightseagreen": "20B2AA", + "lightskyblue": "87CEFA", + "lightslategray": "778899", + "lightslategrey": "778899", + "lightsteelblue": "B0C4DE", + "lightyellow": "FFFFE0", + "lime": "00FF00", + "limegreen": "32CD32", + "linen": "FAF0E6", + "magenta": "FF00FF", + "maroon": "800000", + "mediumaquamarine": "66CDAA", + "mediumblue": "0000CD", + "mediumorchid": "BA55D3", + "mediumpurple": "9370DB", + "mediumseagreen": "3CB371", + "mediumslateblue": "7B68EE", + "mediumspringgreen": "00FA9A", + "mediumturquoise": "48D1CC", + "mediumvioletred": "C71585", + "midnightblue": "191970", + "mintcream": "F5FFFA", + "mistyrose": "FFE4E1", + "moccasin": "FFE4B5", + "navajowhite": "FFDEAD", + "navy": "000080", + "oldlace": "FDF5E6", + "olive": "808000", + "olivedrab": "6B8E23", + "orange": "FFA500", + "orangered": "FF4500", + "orchid": "DA70D6", + "palegoldenrod": "EEE8AA", + "palegreen": "98FB98", + "paleturquoise": "AFEEEE", + "palevioletred": "DB7093", + "papayawhip": "FFEFD5", + "peachpuff": "FFDAB9", + "peru": "CD853F", + "pink": "FFC0CB", + "plum": "DDA0DD", + "powderblue": "B0E0E6", + "purple": "800080", + "rebeccapurple": "663399", + "red": "FF0000", + "rosybrown": "BC8F8F", + "royalblue": "4169E1", + "saddlebrown": "8B4513", + "salmon": "FA8072", + "sandybrown": "F4A460", + "seagreen": "2E8B57", + "seashell": "FFF5EE", + "sienna": "A0522D", + "silver": "C0C0C0", + "skyblue": "87CEEB", + "slateblue": "6A5ACD", + "slategray": "708090", + "slategrey": "708090", + "snow": "FFFAFA", + "springgreen": "00FF7F", + "steelblue": "4682B4", + "tan": "D2B48C", + "teal": "008080", + "thistle": "D8BFD8", + "tomato": "FF6347", + "turquoise": "40E0D0", + "violet": "EE82EE", + "wheat": "F5DEB3", + "white": "FFFFFF", + "whitesmoke": "F5F5F5", + "yellow": "FFFF00", + "yellowgreen": "9ACD32", +} diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index bded853f383e0..c59c964c62da0 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -21,6 +21,7 @@ from pandas.core import generic import pandas.core.common as com +from pandas.io.formats._color_data import CSS4_COLORS from pandas.io.formats.css import CSSResolver, CSSWarning from pandas.io.formats.format import get_level_lengths from pandas.io.formats.printing import pprint_thing @@ -65,28 +66,7 @@ class CSSToExcelConverter: CSS processed by :meth:`__call__`. """ - NAMED_COLORS = { - "maroon": "800000", - "brown": "A52A2A", - "red": "FF0000", - "pink": "FFC0CB", - "orange": "FFA500", - "yellow": "FFFF00", - "olive": "808000", - "green": "008000", - "purple": "800080", - "fuchsia": "FF00FF", - "lime": "00FF00", - "teal": "008080", - "aqua": "00FFFF", - "blue": "0000FF", - "navy": "000080", - "black": "000000", - "gray": "808080", - "grey": "808080", - "silver": "C0C0C0", - "white": "FFFFFF", - } + NAMED_COLORS = CSS4_COLORS VERTICAL_MAP = { "top": "top", diff --git a/pandas/tests/io/formats/test_to_excel.py b/pandas/tests/io/formats/test_to_excel.py index 4f1af132204bb..968ad63eaceef 100644 --- a/pandas/tests/io/formats/test_to_excel.py +++ b/pandas/tests/io/formats/test_to_excel.py @@ -2,9 +2,12 @@ ExcelFormatter is tested implicitly in pandas/tests/io/excel """ +import string import pytest +import pandas.util._test_decorators as td + import pandas._testing as tm from pandas.io.formats.css import CSSWarning @@ -313,3 +316,18 @@ def test_css_to_excel_bad_colors(input_color): with tm.assert_produces_warning(CSSWarning): convert = CSSToExcelConverter() assert expected == convert(css) + + +def tests_css_named_colors_valid(): + upper_hexs = set(map(str.upper, string.hexdigits)) + for color in CSSToExcelConverter.NAMED_COLORS.values(): + assert len(color) == 6 and all(c in upper_hexs for c in color) + + +@td.skip_if_no_mpl +def test_css_named_colors_from_mpl_present(): + from matplotlib.colors import CSS4_COLORS as mpl_colors + + pd_colors = CSSToExcelConverter.NAMED_COLORS + for name, color in mpl_colors.items(): + assert name in pd_colors and pd_colors[name] == color[1:]
(GH37967) - [x] closes #37967 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38247
2020-12-02T19:05:31Z
2020-12-12T23:31:27Z
2020-12-12T23:31:26Z
2021-03-22T20:24:55Z
BUG: Allow numeric ExtensionDtypes in DataFrame.select_dtypes
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 05d3b1c797375..020d3091929db 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -174,7 +174,7 @@ Timezones Numeric ^^^^^^^ - Bug in :meth:`DataFrame.quantile`, :meth:`DataFrame.sort_values` causing incorrect subsequent indexing behavior (:issue:`38351`) -- +- Bug in :meth:`DataFrame.select_dtypes` with ``include=np.number`` now retains numeric ``ExtensionDtype`` columns (:issue:`35340`) - Conversion diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d698edbb0b8ad..d123e0735ded1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3719,12 +3719,14 @@ def extract_unique_dtypes_from_dtypes_set( extracted_dtypes = [ unique_dtype for unique_dtype in unique_dtypes - # error: Argument 1 to "tuple" has incompatible type - # "FrozenSet[Union[ExtensionDtype, str, Any, Type[str], - # Type[float], Type[int], Type[complex], Type[bool]]]"; - # expected "Iterable[Union[type, Tuple[Any, ...]]]" - if issubclass( - unique_dtype.type, tuple(dtypes_set) # type: ignore[arg-type] + if ( + issubclass( + unique_dtype.type, tuple(dtypes_set) # type: ignore[arg-type] + ) + or ( + np.number in dtypes_set + and getattr(unique_dtype, "_is_numeric", False) + ) ) ] return extracted_dtypes diff --git a/pandas/tests/frame/methods/test_select_dtypes.py b/pandas/tests/frame/methods/test_select_dtypes.py index 2a8826cedd50a..f2dbe4a799a17 100644 --- a/pandas/tests/frame/methods/test_select_dtypes.py +++ b/pandas/tests/frame/methods/test_select_dtypes.py @@ -1,9 +1,46 @@ import numpy as np import pytest +from pandas.core.dtypes.dtypes import ExtensionDtype + import pandas as pd from pandas import DataFrame, Timestamp import pandas._testing as tm +from pandas.core.arrays import ExtensionArray + + +class DummyDtype(ExtensionDtype): + type = int + + def __init__(self, numeric): + self._numeric = numeric + + @property + def name(self): + return "Dummy" + + @property + def _is_numeric(self): + return self._numeric + + +class DummyArray(ExtensionArray): + def __init__(self, data, dtype): + self.data = data + self._dtype = dtype + + def __array__(self, dtype): + return self.data + + @property + def dtype(self): + return self._dtype + + def __len__(self) -> int: + return len(self.data) + + def __getitem__(self, item): + pass class TestSelectDtypes: @@ -322,3 +359,20 @@ def test_select_dtypes_typecodes(self): expected = df FLOAT_TYPES = list(np.typecodes["AllFloat"]) tm.assert_frame_equal(df.select_dtypes(FLOAT_TYPES), expected) + + @pytest.mark.parametrize( + "arr,expected", + ( + (np.array([1, 2], dtype=np.int32), True), + (pd.array([1, 2], dtype="Int32"), True), + (pd.array(["a", "b"], dtype="string"), False), + (DummyArray([1, 2], dtype=DummyDtype(numeric=True)), True), + (DummyArray([1, 2], dtype=DummyDtype(numeric=False)), False), + ), + ) + def test_select_dtypes_numeric(self, arr, expected): + # GH 35340 + + df = DataFrame(arr) + is_selected = df.select_dtypes(np.number).shape == df.shape + assert is_selected == expected
- [x] closes #35340 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Picking up #35341 (original PR addressed all comments - here I merged master + added whatsnew note) cc @simonjayhawkins @jreback @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/38246
2020-12-02T18:57:00Z
2020-12-14T17:58:22Z
2020-12-14T17:58:22Z
2022-05-11T15:24:55Z
BUG: CategoricalDtype.__repr__ with RangeIndex categories
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 07280702cf06f..136c8032094b1 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -399,10 +399,14 @@ def __eq__(self, other: Any) -> bool: def __repr__(self) -> str_type: if self.categories is None: - data = "None, " + data = "None" else: data = self.categories._format_data(name=type(self).__name__) - return f"CategoricalDtype(categories={data}ordered={self.ordered})" + if data is None: + # self.categories is RangeIndex + data = str(self.categories._range) + data = data.rstrip(", ") + return f"CategoricalDtype(categories={data}, ordered={self.ordered})" @staticmethod def _hash_categories(categories, ordered: Ordered = True) -> int: diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index a419cb0dded79..872dd03768833 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -199,6 +199,14 @@ def test_not_string(self): # though CategoricalDtype has object kind, it cannot be string assert not is_string_dtype(CategoricalDtype()) + def test_repr_range_categories(self): + rng = pd.Index(range(3)) + dtype = CategoricalDtype(categories=rng, ordered=False) + result = repr(dtype) + + expected = "CategoricalDtype(categories=range(0, 3), ordered=False)" + assert result == expected + class TestDatetimeTZDtype(Base): @pytest.fixture
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry The problem was introduced a couple weeks ago, so shouldn't need a whatsnew.
https://api.github.com/repos/pandas-dev/pandas/pulls/38245
2020-12-02T18:47:11Z
2020-12-03T15:55:03Z
2020-12-03T15:55:03Z
2020-12-03T16:01:44Z
REGR: unstack on 'int' dtype prevent fillna to work
diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst index 0e2e510147603..fbb12cb38448a 100644 --- a/doc/source/whatsnew/v1.1.5.rst +++ b/doc/source/whatsnew/v1.1.5.rst @@ -20,6 +20,7 @@ Fixed regressions - Fixed regression in inplace operations on :class:`Series` with ``ExtensionDtype`` with NumPy dtyped operand (:issue:`37910`) - Fixed regression in metadata propagation for ``groupby`` iterator (:issue:`37343`) - Fixed regression in :class:`MultiIndex` constructed from a :class:`DatetimeIndex` not retaining frequency (:issue:`35563`) +- Fixed regression in :meth:`DataFrame.unstack` with columns with integer dtype (:issue:`37115`) - Fixed regression in indexing on a :class:`Series` with ``CategoricalDtype`` after unpickling (:issue:`37631`) - Fixed regression in :meth:`DataFrame.groupby` aggregation with out-of-bounds datetime objects in an object-dtype column (:issue:`36003`) - Fixed regression in ``df.groupby(..).rolling(..)`` with the resulting :class:`MultiIndex` when grouping by a label that is in the index (:issue:`37641`) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 1c08888aa85fd..fe07823a80783 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1542,7 +1542,7 @@ def _unstack(self, unstacker, fill_value, new_placement): new_values = new_values.T[mask] new_placement = new_placement[mask] - blocks = [self.make_block_same_class(new_values, placement=new_placement)] + blocks = [make_block(new_values, placement=new_placement)] return blocks, mask def quantile(self, qs, interpolation="linear", axis: int = 0): diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index c9e737a9dcb0f..06e5169fc6016 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -1880,3 +1880,30 @@ def test_unstack_group_index_overflow(self): s = Series(np.arange(1000), index=index) result = s.unstack(4) assert result.shape == (500, 2) + + def test_unstack_with_missing_int_cast_to_float(self): + # https://github.com/pandas-dev/pandas/issues/37115 + df = DataFrame( + { + "a": ["A", "A", "B"], + "b": ["ca", "cb", "cb"], + "v": [10] * 3, + } + ).set_index(["a", "b"]) + + # add another int column to get 2 blocks + df["is_"] = 1 + assert len(df._mgr.blocks) == 2 + + result = df.unstack("b") + result[("is_", "ca")] = result[("is_", "ca")].fillna(0) + + expected = DataFrame( + [[10.0, 10.0, 1.0, 1.0], [np.nan, 10.0, 0.0, 1.0]], + index=Index(["A", "B"], dtype="object", name="a"), + columns=MultiIndex.from_tuples( + [("v", "ca"), ("v", "cb"), ("is_", "ca"), ("is_", "cb")], + names=[None, "b"], + ), + ) + tm.assert_frame_equal(result, expected)
- [ ] closes #37115 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38244
2020-12-02T18:14:43Z
2020-12-02T23:30:04Z
2020-12-02T23:30:04Z
2020-12-03T11:11:12Z
TST: string representation of IntervalIndex
diff --git a/pandas/tests/indexes/interval/test_formats.py b/pandas/tests/indexes/interval/test_formats.py index 0e8d7d1ba5aba..fb59334b2e129 100644 --- a/pandas/tests/indexes/interval/test_formats.py +++ b/pandas/tests/indexes/interval/test_formats.py @@ -1,7 +1,15 @@ import numpy as np import pytest -from pandas import DataFrame, IntervalIndex, Series, Timedelta, Timestamp +from pandas import ( + DataFrame, + Float64Index, + Interval, + IntervalIndex, + Series, + Timedelta, + Timestamp, +) import pandas._testing as tm @@ -37,6 +45,25 @@ def test_repr_missing(self, constructor, expected): result = repr(obj) assert result == expected + def test_repr_floats(self): + # GH 32553 + + markers = Series( + ["foo", "bar"], + index=IntervalIndex( + [ + Interval(left, right) + for left, right in zip( + Float64Index([329.973, 345.137], dtype="float64"), + Float64Index([345.137, 360.191], dtype="float64"), + ) + ] + ), + ) + result = str(markers) + expected = "(329.973, 345.137] foo\n(345.137, 360.191] bar\ndtype: object" + assert result == expected + @pytest.mark.parametrize( "tuples, closed, expected_data", [
- [x] closes #32553 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Picking up #36628
https://api.github.com/repos/pandas-dev/pandas/pulls/38242
2020-12-02T17:52:12Z
2020-12-03T14:23:34Z
2020-12-03T14:23:34Z
2020-12-03T14:23:38Z
TST: setitem in presence of duplicate cols
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 6d4129a1a2a55..49eb570c4ffe0 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -241,6 +241,24 @@ def inc(x): expected = DataFrame([[-1, inc], [inc, -1]]) tm.assert_frame_equal(df, expected) + @pytest.mark.parametrize( + "cols, values, expected", + [ + (["C", "D", "D", "a"], [1, 2, 3, 4], 4), # with duplicates + (["D", "C", "D", "a"], [1, 2, 3, 4], 4), # mixed order + (["C", "B", "B", "a"], [1, 2, 3, 4], 4), # other duplicate cols + (["C", "B", "a"], [1, 2, 3], 3), # no duplicates + (["B", "C", "a"], [3, 2, 1], 1), # alphabetical order + (["C", "a", "B"], [3, 2, 1], 2), # in the middle + ], + ) + def test_setitem_same_column(self, cols, values, expected): + # GH 23239 + df = DataFrame([values], columns=cols) + df["a"] = df["a"] + result = df["a"].values[0] + assert result == expected + def test_getitem_boolean( self, float_string_frame, mixed_float_frame, mixed_int_frame, datetime_frame ):
- [ ] closes #23239 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Add tests required to close the issue. The tests are based on the example in the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/38241
2020-12-02T17:50:01Z
2020-12-02T23:37:07Z
2020-12-02T23:37:06Z
2020-12-03T07:55:24Z
TST: revert too-ambitious part of #38223
diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index a63a98cf9858b..c20955227d05e 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1631,7 +1631,8 @@ def check_col(key, name, size): & (df_new.A > 0) & (df_new.B < 0) ] - tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected, check_freq=False) + # FIXME: 2020-05-07 freq check randomly fails in the CI # yield an empty frame result = store.select("df", "string='foo' and string2='cool'")
https://api.github.com/repos/pandas-dev/pandas/pulls/38238
2020-12-02T15:33:20Z
2020-12-02T23:35:47Z
2020-12-02T23:35:47Z
2020-12-02T23:44:51Z
REF: consolidate result-casting in _cython_operation
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 184fa3a2b4204..b077c7889049f 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1000,9 +1000,6 @@ def _cython_transform( except NotImplementedError: continue - if self._transform_should_cast(how): - result = maybe_cast_result(result, obj, how=how) - key = base.OutputKey(label=name, position=idx) output[key] = result @@ -1081,12 +1078,12 @@ def _cython_agg_general( assert len(agg_names) == result.shape[1] for result_column, result_name in zip(result.T, agg_names): key = base.OutputKey(label=result_name, position=idx) - output[key] = maybe_cast_result(result_column, obj, how=how) + output[key] = result_column idx += 1 else: assert result.ndim == 1 key = base.OutputKey(label=name, position=idx) - output[key] = maybe_cast_result(result, obj, how=how) + output[key] = result idx += 1 if not output: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index ded5f610b850e..62002f62afbcd 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -28,7 +28,11 @@ from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly -from pandas.core.dtypes.cast import maybe_cast_result +from pandas.core.dtypes.cast import ( + maybe_cast_result, + maybe_cast_result_dtype, + maybe_downcast_to_dtype, +) from pandas.core.dtypes.common import ( ensure_float, ensure_float64, @@ -620,8 +624,11 @@ def _cython_operation( if swapped: result = result.swapaxes(0, axis) - if is_datetimelike and kind == "aggregate": - result = result.astype(orig_values.dtype) + if how not in base.cython_cast_blocklist: + # e.g. if we are int64 and need to restore to datetime64/timedelta64 + # "rank" is the only member of cython_cast_blocklist we get here + dtype = maybe_cast_result_dtype(orig_values.dtype, how) + result = maybe_downcast_to_dtype(result, dtype) return result, names
Orthogonal to #38235. After this and 38235, we'll be down to only two usages of maybe_cast_result, only one of which is sketchy.
https://api.github.com/repos/pandas-dev/pandas/pulls/38237
2020-12-02T15:17:11Z
2020-12-02T23:35:19Z
2020-12-02T23:35:19Z
2020-12-02T23:48:48Z
TYP: handle mypy ignore in pandas/_testing
diff --git a/pandas/_testing.py b/pandas/_testing.py index 964c8d4d3d61a..2d74cc89b8063 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -10,7 +10,17 @@ from shutil import rmtree import string import tempfile -from typing import Any, Callable, ContextManager, List, Optional, Type, Union, cast +from typing import ( + Any, + Callable, + ContextManager, + List, + Optional, + Tuple, + Type, + Union, + cast, +) import warnings import zipfile @@ -301,35 +311,25 @@ def write_to_compressed(compression, path, data, dest="test"): ------ ValueError : An invalid compression value was passed in. """ + args: Tuple[Any, ...] = (data,) + mode = "wb" + method = "write" + compress_method: Callable + if compression == "zip": compress_method = zipfile.ZipFile + mode = "w" + args = (dest, data) + method = "writestr" elif compression == "gzip": - # pandas\_testing.py:288: error: Incompatible types in assignment - # (expression has type "Type[GzipFile]", variable has type - # "Type[ZipFile]") - compress_method = gzip.GzipFile # type: ignore[assignment] + compress_method = gzip.GzipFile elif compression == "bz2": - # pandas\_testing.py:290: error: Incompatible types in assignment - # (expression has type "Type[BZ2File]", variable has type - # "Type[ZipFile]") - compress_method = bz2.BZ2File # type: ignore[assignment] + compress_method = bz2.BZ2File elif compression == "xz": compress_method = get_lzma_file(lzma) else: raise ValueError(f"Unrecognized compression type: {compression}") - if compression == "zip": - mode = "w" - args = (dest, data) - method = "writestr" - else: - mode = "wb" - # pandas\_testing.py:302: error: Incompatible types in assignment - # (expression has type "Tuple[Any]", variable has type "Tuple[Any, - # Any]") - args = (data,) # type: ignore[assignment] - method = "write" - with compress_method(path, mode=mode) as f: getattr(f, method)(*args)
- [ ] xref #37715 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Handle mypy ignore comments in ``pandas/_testing.py``, function ``write_to_compressed``.
https://api.github.com/repos/pandas-dev/pandas/pulls/38236
2020-12-02T15:12:33Z
2020-12-19T02:22:44Z
2020-12-19T02:22:44Z
2020-12-19T02:22:44Z
REF: casting in _python_agg_general
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 184fa3a2b4204..efc9a6f148fc0 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -50,7 +50,7 @@ class providing the base-class of operations. from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, Substitution, cache_readonly, doc -from pandas.core.dtypes.cast import maybe_cast_result +from pandas.core.dtypes.cast import maybe_cast_result, maybe_downcast_to_dtype from pandas.core.dtypes.common import ( ensure_float, is_bool_dtype, @@ -1185,22 +1185,24 @@ def _python_agg_general(self, func, *args, **kwargs): assert result is not None key = base.OutputKey(label=name, position=idx) - output[key] = maybe_cast_result(result, obj, numeric_only=True) - if not output: - return self._python_apply_general(f, self._selected_obj) + if is_numeric_dtype(obj.dtype): + result = maybe_downcast_to_dtype(result, obj.dtype) - if self.grouper._filter_empty_groups: - - mask = counts.ravel() > 0 - for key, result in output.items(): + if self.grouper._filter_empty_groups: + mask = counts.ravel() > 0 # since we are masking, make sure that we have a float object values = result if is_numeric_dtype(values.dtype): values = ensure_float(values) - output[key] = maybe_cast_result(values[mask], result) + result = maybe_downcast_to_dtype(values[mask], result.dtype) + + output[key] = result + + if not output: + return self._python_apply_general(f, self._selected_obj) return self._wrap_aggregated_output(output, index=self.grouper.result_index) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index ded5f610b850e..fb60bd8e3b3c1 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -718,7 +718,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F): result[label] = res result = lib.maybe_convert_objects(result, try_float=0) - # TODO: maybe_cast_to_extension_array? + result = maybe_cast_result(result, obj, numeric_only=True) return result, counts
Consolidate two for-loops into one. Instead of using maybe_cast_result in two places, use it only once, immediately after the function call being wrapped. Replace those two usages with the less-invasive `maybe_downcast_to_dtype`
https://api.github.com/repos/pandas-dev/pandas/pulls/38235
2020-12-02T14:59:53Z
2020-12-02T23:33:28Z
2020-12-02T23:33:28Z
2020-12-02T23:59:59Z
TST: Assert msg with pytest raises in pandas/tests/extension/base
diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 251376798efc3..bfd6da0fc864d 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -160,11 +160,12 @@ def test_getitem_mask(self, data): def test_getitem_mask_raises(self, data): mask = np.array([True, False]) - with pytest.raises(IndexError): + msg = f"Boolean index has wrong length: 2 instead of {len(data)}" + with pytest.raises(IndexError, match=msg): data[mask] mask = pd.array(mask, dtype="boolean") - with pytest.raises(IndexError): + with pytest.raises(IndexError, match=msg): data[mask] def test_getitem_boolean_array_mask(self, data): @@ -305,7 +306,9 @@ def test_take_empty(self, data, na_value, na_cmp): result = empty.take([-1], allow_fill=True) assert na_cmp(result[0], na_value) - with pytest.raises(IndexError): + msg = "cannot do a non-empty take from an empty axes|out of bounds" + + with pytest.raises(IndexError, match=msg): empty.take([-1]) with pytest.raises(IndexError, match="cannot do a non-empty take"): @@ -330,13 +333,14 @@ def test_take_non_na_fill_value(self, data_missing): self.assert_extension_array_equal(result, expected) def test_take_pandas_style_negative_raises(self, data, na_value): - with pytest.raises(ValueError): + with pytest.raises(ValueError, match=""): data.take([0, -2], fill_value=na_value, allow_fill=True) @pytest.mark.parametrize("allow_fill", [True, False]) def test_take_out_of_bounds_raises(self, data, allow_fill): arr = data[:3] - with pytest.raises(IndexError): + + with pytest.raises(IndexError, match="out of bounds|out-of-bounds"): arr.take(np.asarray([0, 3]), allow_fill=allow_fill) def test_take_series(self, data): diff --git a/pandas/tests/extension/base/reduce.py b/pandas/tests/extension/base/reduce.py index 6f433d659575a..55f8aca1b8ae0 100644 --- a/pandas/tests/extension/base/reduce.py +++ b/pandas/tests/extension/base/reduce.py @@ -28,7 +28,12 @@ def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna): op_name = all_numeric_reductions s = pd.Series(data) - with pytest.raises(TypeError): + msg = ( + "[Cc]annot perform|Categorical is not ordered for operation|" + "'Categorical' does not implement reduction|" + ) + + with pytest.raises(TypeError, match=msg): getattr(s, op_name)(skipna=skipna) @pytest.mark.parametrize("skipna", [True, False]) @@ -36,7 +41,12 @@ def test_reduce_series_boolean(self, data, all_boolean_reductions, skipna): op_name = all_boolean_reductions s = pd.Series(data) - with pytest.raises(TypeError): + msg = ( + "[Cc]annot perform|Categorical is not ordered for operation|" + "'Categorical' does not implement reduction|" + ) + + with pytest.raises(TypeError, match=msg): getattr(s, op_name)(skipna=skipna)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This PR adds messages to the bare pytest raises in reduce.py and getitem.py in pandas/test/extension/base. This PR references #30999.
https://api.github.com/repos/pandas-dev/pandas/pulls/38232
2020-12-02T11:45:09Z
2020-12-12T23:00:24Z
2020-12-12T23:00:24Z
2020-12-12T23:00:28Z
Backport PR #38209 on branch 1.1.x (CI/TST: fix CI with numpy dev for changed error message / dev version)
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 3b66939d9ddd2..9d5491fe2f5fc 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -369,8 +369,7 @@ def test_2d_to_1d_assignment_raises(): msg = "|".join( [ - r"shape mismatch: value array of shape \(2,2\) could not be " - r"broadcast to indexing result of shape \(2,\)", + r"shape mismatch: value array of shape \(2,2\)", r"cannot reshape array of size 4 into shape \(2,\)", ] ) diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py index fe5fc3e21d960..4ea3ebe5000ad 100644 --- a/pandas/tests/util/test_show_versions.py +++ b/pandas/tests/util/test_show_versions.py @@ -39,7 +39,7 @@ def test_show_versions(capsys): assert re.search(r"commit\s*:\s[0-9a-f]{40}\n", result) # check required dependency - assert re.search(r"numpy\s*:\s([0-9\.\+a-f]|dev)+\n", result) + assert re.search(r"numpy\s*:\s([0-9\.\+a-f\_]|dev)+\n", result) # check optional dependency assert re.search(r"pyarrow\s*:\s([0-9\.]+|None)\n", result)
Backport PR #38209: CI/TST: fix CI with numpy dev for changed error message / dev version
https://api.github.com/repos/pandas-dev/pandas/pulls/38231
2020-12-02T10:16:10Z
2020-12-02T11:38:41Z
2020-12-02T11:38:41Z
2020-12-02T11:38:41Z
Backport PR #38228 on branch 1.1.x (CI: pin pip to 20.2 on numpy-dev build)
diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 7248b1740058f..b2009e84df12e 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -12,7 +12,7 @@ dependencies: # pandas dependencies - pytz - - pip + - pip=20.2 - pip: - cython==0.29.21 # GH#34014 - "git+git://github.com/dateutil/dateutil.git"
Backport PR #38228: CI: pin pip to 20.2 on numpy-dev build
https://api.github.com/repos/pandas-dev/pandas/pulls/38230
2020-12-02T10:15:59Z
2020-12-02T11:16:48Z
2020-12-02T11:16:48Z
2020-12-02T11:16:48Z
CI: pin pip to 20.2 on numpy-dev build
diff --git a/ci/deps/azure-38-numpydev.yaml b/ci/deps/azure-38-numpydev.yaml index 274be0361c2e5..f11a3bcb28ab2 100644 --- a/ci/deps/azure-38-numpydev.yaml +++ b/ci/deps/azure-38-numpydev.yaml @@ -12,7 +12,7 @@ dependencies: # pandas dependencies - pytz - - pip + - pip=20.2 - pip: - cython==0.29.21 # GH#34014 - "git+git://github.com/dateutil/dateutil.git"
See https://github.com/pandas-dev/pandas/issues/38221
https://api.github.com/repos/pandas-dev/pandas/pulls/38228
2020-12-02T08:45:21Z
2020-12-02T10:08:14Z
2020-12-02T10:08:14Z
2020-12-02T12:02:39Z
ENH: context-manager for chunksize/iterator-reader
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 1bd35131622ab..2b324a74fffaf 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -1577,19 +1577,21 @@ value will be an iterable object of type ``TextFileReader``: .. ipython:: python - reader = pd.read_csv("tmp.sv", sep="|", chunksize=4) - reader + with pd.read_csv("tmp.sv", sep="|", chunksize=4) as reader: + reader + for chunk in reader: + print(chunk) - for chunk in reader: - print(chunk) +.. versionchanged:: 1.2 + ``read_csv/json/sas`` return a context-manager when iterating through a file. Specifying ``iterator=True`` will also return the ``TextFileReader`` object: .. ipython:: python - reader = pd.read_csv("tmp.sv", sep="|", iterator=True) - reader.get_chunk(5) + with pd.read_csv("tmp.sv", sep="|", iterator=True) as reader: + reader.get_chunk(5) .. ipython:: python :suppress: @@ -2238,10 +2240,10 @@ For line-delimited json files, pandas can also return an iterator which reads in df.to_json(orient="records", lines=True) # reader is an iterator that returns ``chunksize`` lines each iteration - reader = pd.read_json(StringIO(jsonl), lines=True, chunksize=1) - reader - for chunk in reader: - print(chunk) + with pd.read_json(StringIO(jsonl), lines=True, chunksize=1) as reader: + reader + for chunk in reader: + print(chunk) .. _io.table_schema: @@ -5471,9 +5473,9 @@ object can be used as an iterator. .. ipython:: python - reader = pd.read_stata("stata.dta", chunksize=3) - for df in reader: - print(df.shape) + with pd.read_stata("stata.dta", chunksize=3) as reader: + for df in reader: + print(df.shape) For more fine-grained control, use ``iterator=True`` and specify ``chunksize`` with each call to @@ -5481,9 +5483,9 @@ For more fine-grained control, use ``iterator=True`` and specify .. ipython:: python - reader = pd.read_stata("stata.dta", iterator=True) - chunk1 = reader.read(5) - chunk2 = reader.read(5) + with pd.read_stata("stata.dta", iterator=True) as reader: + chunk1 = reader.read(5) + chunk2 = reader.read(5) Currently the ``index`` is retrieved as a column. @@ -5595,9 +5597,9 @@ Obtain an iterator and read an XPORT file 100,000 lines at a time: pass - rdr = pd.read_sas("sas_xport.xpt", chunk=100000) - for chunk in rdr: - do_something(chunk) + with pd.read_sas("sas_xport.xpt", chunk=100000) as rdr: + for chunk in rdr: + do_something(chunk) The specification_ for the xport file format is available from the SAS web site. diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 8182dfa4bce40..13ddeb2a89133 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -291,6 +291,7 @@ Other enhancements - Improve numerical stability for :meth:`.Rolling.skew`, :meth:`.Rolling.kurt`, :meth:`Expanding.skew` and :meth:`Expanding.kurt` through implementation of Kahan summation (:issue:`6929`) - Improved error reporting for subsetting columns of a :class:`.DataFrameGroupBy` with ``axis=1`` (:issue:`37725`) - Implement method ``cross`` for :meth:`DataFrame.merge` and :meth:`DataFrame.join` (:issue:`5401`) +- When :func:`read_csv/sas/json` are called with ``chuncksize``/``iterator`` they can be used in a ``with`` statement as they return context-managers (:issue:`38225`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/html.py b/pandas/io/html.py index 334a3dab6c13a..4a2d4af62f3e9 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -794,9 +794,8 @@ def _data_to_frame(**kwargs): # fill out elements of body that are "ragged" _expand_elements(body) - tp = TextParser(body, header=header, **kwargs) - df = tp.read() - return df + with TextParser(body, header=header, **kwargs) as tp: + return tp.read() _valid_parsers = { diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index b1d705439e300..da085d0d0eb2f 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -437,6 +437,10 @@ def read_json( This can only be passed if `lines=True`. If this is None, the file will be read into memory all at once. + .. versionchanged:: 1.2 + + ``JsonReader`` is a context manager. + compression : {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer', then use gzip, bz2, zip or xz if path_or_buf is a string ending in @@ -555,7 +559,8 @@ def read_json( if chunksize: return json_reader - return json_reader.read() + with json_reader: + return json_reader.read() class JsonReader(abc.Iterator): @@ -747,6 +752,12 @@ def __next__(self): self.close() raise StopIteration + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + class Parser: _split_keys: Tuple[str, ...] diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 9cdc9871e1e07..5b623c360c3ef 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -276,11 +276,19 @@ iterator : bool, default False Return TextFileReader object for iteration or getting chunks with ``get_chunk()``. + + .. versionchanged:: 1.2 + + ``TextFileReader`` is a context manager. chunksize : int, optional Return TextFileReader object for iteration. See the `IO Tools docs <https://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ for more information on ``iterator`` and ``chunksize``. + + .. versionchanged:: 1.2 + + ``TextFileReader`` is a context manager. compression : {{'infer', 'gzip', 'bz2', 'zip', 'xz', None}}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer' and `filepath_or_buffer` is path-like, then detect compression from the @@ -451,12 +459,8 @@ def _read(filepath_or_buffer: FilePathOrBuffer, kwds): if chunksize or iterator: return parser - try: - data = parser.read(nrows) - finally: - parser.close() - - return data + with parser: + return parser.read(nrows) _parser_defaults = { @@ -1074,6 +1078,12 @@ def get_chunk(self, size=None): size = min(size, self.nrows - self._currow) return self.read(nrows=size) + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + def _is_index_col(col): return col is not None and col is not False diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py index d9cb9902b930a..243218129fda6 100644 --- a/pandas/io/sas/sasreader.py +++ b/pandas/io/sas/sasreader.py @@ -6,7 +6,7 @@ from pandas._typing import FilePathOrBuffer, Label -from pandas.io.common import IOHandles, stringify_path +from pandas.io.common import stringify_path if TYPE_CHECKING: from pandas import DataFrame @@ -18,8 +18,6 @@ class ReaderBase(metaclass=ABCMeta): Protocol for XportReader and SAS7BDATReader classes. """ - handles: IOHandles - @abstractmethod def read(self, nrows=None): pass @@ -28,6 +26,12 @@ def read(self, nrows=None): def close(self): pass + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close() + @overload def read_sas( @@ -87,9 +91,17 @@ def read_sas( Encoding for text data. If None, text data are stored as raw bytes. chunksize : int Read file `chunksize` lines at a time, returns iterator. + + .. versionchanged:: 1.2 + + ``TextFileReader`` is a context manager. iterator : bool, defaults to False If True, returns an iterator for reading the file incrementally. + .. versionchanged:: 1.2 + + ``TextFileReader`` is a context manager. + Returns ------- DataFrame if iterator=False and chunksize=None, else SAS7BDATReader @@ -136,5 +148,5 @@ def read_sas( if iterator or chunksize: return reader - with reader.handles: + with reader: return reader.read() diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index a41af9886c617..5faca6bd89dad 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -65,8 +65,10 @@ def test_chunksize_with_compression(compression): df = pd.read_json('{"a": ["foo", "bar", "baz"], "b": [4, 5, 6]}') df.to_json(path, orient="records", lines=True, compression=compression) - res = pd.read_json(path, lines=True, chunksize=1, compression=compression) - roundtripped_df = pd.concat(res) + with pd.read_json( + path, lines=True, chunksize=1, compression=compression + ) as res: + roundtripped_df = pd.concat(res) tm.assert_frame_equal(df, roundtripped_df) diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index 2e68d3306c7d1..4bbd81ada995b 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -77,8 +77,8 @@ def test_readjson_chunks(lines_json_df, chunksize): # GH17048: memory usage when lines=True unchunked = read_json(StringIO(lines_json_df), lines=True) - reader = read_json(StringIO(lines_json_df), lines=True, chunksize=chunksize) - chunked = pd.concat(reader) + with read_json(StringIO(lines_json_df), lines=True, chunksize=chunksize) as reader: + chunked = pd.concat(reader) tm.assert_frame_equal(chunked, unchunked) @@ -86,7 +86,8 @@ def test_readjson_chunks(lines_json_df, chunksize): def test_readjson_chunksize_requires_lines(lines_json_df): msg = "chunksize can only be passed if lines=True" with pytest.raises(ValueError, match=msg): - pd.read_json(StringIO(lines_json_df), lines=False, chunksize=2) + with pd.read_json(StringIO(lines_json_df), lines=False, chunksize=2) as _: + pass def test_readjson_chunks_series(): @@ -97,7 +98,8 @@ def test_readjson_chunks_series(): unchunked = pd.read_json(strio, lines=True, typ="Series") strio = StringIO(s.to_json(lines=True, orient="records")) - chunked = pd.concat(pd.read_json(strio, lines=True, typ="Series", chunksize=1)) + with pd.read_json(strio, lines=True, typ="Series", chunksize=1) as reader: + chunked = pd.concat(reader) tm.assert_series_equal(chunked, unchunked) @@ -105,7 +107,8 @@ def test_readjson_chunks_series(): def test_readjson_each_chunk(lines_json_df): # Other tests check that the final result of read_json(chunksize=True) # is correct. This checks the intermediate chunks. - chunks = list(pd.read_json(StringIO(lines_json_df), lines=True, chunksize=2)) + with pd.read_json(StringIO(lines_json_df), lines=True, chunksize=2) as reader: + chunks = list(reader) assert chunks[0].shape == (2, 2) assert chunks[1].shape == (1, 2) @@ -114,7 +117,8 @@ def test_readjson_chunks_from_file(): with tm.ensure_clean("test.json") as path: df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) df.to_json(path, lines=True, orient="records") - chunked = pd.concat(pd.read_json(path, lines=True, chunksize=1)) + with pd.read_json(path, lines=True, chunksize=1) as reader: + chunked = pd.concat(reader) unchunked = pd.read_json(path, lines=True) tm.assert_frame_equal(unchunked, chunked) @@ -141,7 +145,8 @@ def test_readjson_chunks_closes(chunksize): compression=None, nrows=None, ) - reader.read() + with reader: + reader.read() assert ( reader.handles.handle.closed ), f"didn't close stream with chunksize = {chunksize}" @@ -152,7 +157,10 @@ def test_readjson_invalid_chunksize(lines_json_df, chunksize): msg = r"'chunksize' must be an integer >=1" with pytest.raises(ValueError, match=msg): - pd.read_json(StringIO(lines_json_df), lines=True, chunksize=chunksize) + with pd.read_json( + StringIO(lines_json_df), lines=True, chunksize=chunksize + ) as _: + pass @pytest.mark.parametrize("chunksize", [None, 1, 2]) @@ -176,7 +184,8 @@ def test_readjson_chunks_multiple_empty_lines(chunksize): orig = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) test = pd.read_json(j, lines=True, chunksize=chunksize) if chunksize is not None: - test = pd.concat(test) + with test: + test = pd.concat(test) tm.assert_frame_equal(orig, test, obj=f"chunksize: {chunksize}") @@ -212,8 +221,8 @@ def test_readjson_nrows_chunks(nrows, chunksize): {"a": 3, "b": 4} {"a": 5, "b": 6} {"a": 7, "b": 8}""" - reader = read_json(jsonl, lines=True, nrows=nrows, chunksize=chunksize) - chunked = pd.concat(reader) + with read_json(jsonl, lines=True, nrows=nrows, chunksize=chunksize) as reader: + chunked = pd.concat(reader) expected = DataFrame({"a": [1, 3, 5, 7], "b": [2, 4, 6, 8]}).iloc[:nrows] tm.assert_frame_equal(chunked, expected) @@ -240,6 +249,6 @@ def test_readjson_lines_chunks_fileurl(datapath): ] os_path = datapath("io", "json", "data", "line_delimited.json") file_url = Path(os_path).as_uri() - url_reader = pd.read_json(file_url, lines=True, chunksize=1) - for index, chuck in enumerate(url_reader): - tm.assert_frame_equal(chuck, df_list_expected[index]) + with pd.read_json(file_url, lines=True, chunksize=1) as url_reader: + for index, chuck in enumerate(url_reader): + tm.assert_frame_equal(chuck, df_list_expected[index]) diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py index eee111dd4579c..06ccfa7f62863 100644 --- a/pandas/tests/io/parser/test_c_parser_only.py +++ b/pandas/tests/io/parser/test_c_parser_only.py @@ -376,10 +376,10 @@ def test_parse_trim_buffers(c_parser_only): ) # Iterate over the CSV file in chunks of `chunksize` lines - chunks_ = parser.read_csv( + with parser.read_csv( StringIO(csv_data), header=None, dtype=object, chunksize=chunksize - ) - result = concat(chunks_, axis=0, ignore_index=True) + ) as chunks_: + result = concat(chunks_, axis=0, ignore_index=True) # Check for data corruption if there was no segfault tm.assert_frame_equal(result, expected) @@ -387,14 +387,14 @@ def test_parse_trim_buffers(c_parser_only): # This extra test was added to replicate the fault in gh-5291. # Force 'utf-8' encoding, so that `_string_convert` would take # a different execution branch. - chunks_ = parser.read_csv( + with parser.read_csv( StringIO(csv_data), header=None, dtype=object, chunksize=chunksize, encoding="utf_8", - ) - result = concat(chunks_, axis=0, ignore_index=True) + ) as chunks_: + result = concat(chunks_, axis=0, ignore_index=True) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index 8f63d06859f62..c8ed0d75b13a2 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -195,12 +195,11 @@ def test_malformed_chunks(all_parsers, nrows): """ parser = all_parsers msg = "Expected 3 fields in line 6, saw 5" - reader = parser.read_csv( + with parser.read_csv( StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2] - ) - - with pytest.raises(ParserError, match=msg): - reader.read(nrows) + ) as reader: + with pytest.raises(ParserError, match=msg): + reader.read(nrows) def test_unnamed_columns(all_parsers): @@ -471,7 +470,6 @@ def test_read_chunksize_with_index(all_parsers, index_col): bar2,12,13,14,15 """ - reader = parser.read_csv(StringIO(data), index_col=0, chunksize=2) expected = DataFrame( [ ["foo", 2, 3, 4, 5], @@ -485,7 +483,8 @@ def test_read_chunksize_with_index(all_parsers, index_col): ) expected = expected.set_index("index") - chunks = list(reader) + with parser.read_csv(StringIO(data), index_col=0, chunksize=2) as reader: + chunks = list(reader) tm.assert_frame_equal(chunks[0], expected[:2]) tm.assert_frame_equal(chunks[1], expected[2:4]) tm.assert_frame_equal(chunks[2], expected[4:]) @@ -505,7 +504,8 @@ def test_read_chunksize_bad(all_parsers, chunksize): msg = r"'chunksize' must be an integer >=1" with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), chunksize=chunksize) + with parser.read_csv(StringIO(data), chunksize=chunksize) as _: + pass @pytest.mark.parametrize("chunksize", [2, 8]) @@ -522,9 +522,9 @@ def test_read_chunksize_and_nrows(all_parsers, chunksize): parser = all_parsers kwargs = dict(index_col=0, nrows=5) - reader = parser.read_csv(StringIO(data), chunksize=chunksize, **kwargs) expected = parser.read_csv(StringIO(data), **kwargs) - tm.assert_frame_equal(concat(reader), expected) + with parser.read_csv(StringIO(data), chunksize=chunksize, **kwargs) as reader: + tm.assert_frame_equal(concat(reader), expected) def test_read_chunksize_and_nrows_changing_size(all_parsers): @@ -539,14 +539,13 @@ def test_read_chunksize_and_nrows_changing_size(all_parsers): parser = all_parsers kwargs = dict(index_col=0, nrows=5) - reader = parser.read_csv(StringIO(data), chunksize=8, **kwargs) expected = parser.read_csv(StringIO(data), **kwargs) + with parser.read_csv(StringIO(data), chunksize=8, **kwargs) as reader: + tm.assert_frame_equal(reader.get_chunk(size=2), expected.iloc[:2]) + tm.assert_frame_equal(reader.get_chunk(size=4), expected.iloc[2:5]) - tm.assert_frame_equal(reader.get_chunk(size=2), expected.iloc[:2]) - tm.assert_frame_equal(reader.get_chunk(size=4), expected.iloc[2:5]) - - with pytest.raises(StopIteration, match=""): - reader.get_chunk(size=3) + with pytest.raises(StopIteration, match=""): + reader.get_chunk(size=3) def test_get_chunk_passed_chunksize(all_parsers): @@ -557,8 +556,8 @@ def test_get_chunk_passed_chunksize(all_parsers): 7,8,9 1,2,3""" - reader = parser.read_csv(StringIO(data), chunksize=2) - result = reader.get_chunk() + with parser.read_csv(StringIO(data), chunksize=2) as reader: + result = reader.get_chunk() expected = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @@ -576,10 +575,9 @@ def test_read_chunksize_compat(all_parsers, kwargs): bar2,12,13,14,15 """ parser = all_parsers - reader = parser.read_csv(StringIO(data), chunksize=2, **kwargs) - result = parser.read_csv(StringIO(data), **kwargs) - tm.assert_frame_equal(concat(reader), result) + with parser.read_csv(StringIO(data), chunksize=2, **kwargs) as reader: + tm.assert_frame_equal(concat(reader), result) def test_read_chunksize_jagged_names(all_parsers): @@ -588,9 +586,8 @@ def test_read_chunksize_jagged_names(all_parsers): data = "\n".join(["0"] * 7 + [",".join(["0"] * 10)]) expected = DataFrame([[0] + [np.nan] * 9] * 7 + [[0] * 10]) - reader = parser.read_csv(StringIO(data), names=range(10), chunksize=4) - - result = concat(reader) + with parser.read_csv(StringIO(data), names=range(10), chunksize=4) as reader: + result = concat(reader) tm.assert_frame_equal(result, expected) @@ -602,8 +599,8 @@ def test_read_data_list(all_parsers): data_list = [["A", "B", "C"], ["foo", "1", "2", "3"], ["bar", "4", "5", "6"]] expected = parser.read_csv(StringIO(data), **kwargs) - parser = TextParser(data_list, chunksize=2, **kwargs) - result = parser.read() + with TextParser(data_list, chunksize=2, **kwargs) as parser: + result = parser.read() tm.assert_frame_equal(result, expected) @@ -622,12 +619,12 @@ def test_iterator(all_parsers): kwargs = dict(index_col=0) expected = parser.read_csv(StringIO(data), **kwargs) - reader = parser.read_csv(StringIO(data), iterator=True, **kwargs) + with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader: - first_chunk = reader.read(3) - tm.assert_frame_equal(first_chunk, expected[:3]) + first_chunk = reader.read(3) + tm.assert_frame_equal(first_chunk, expected[:3]) - last_chunk = reader.read(5) + last_chunk = reader.read(5) tm.assert_frame_equal(last_chunk, expected[3:]) @@ -639,8 +636,8 @@ def test_iterator2(all_parsers): baz,7,8,9 """ - reader = parser.read_csv(StringIO(data), iterator=True) - result = list(reader) + with parser.read_csv(StringIO(data), iterator=True) as reader: + result = list(reader) expected = DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], @@ -663,10 +660,10 @@ def test_reader_list(all_parsers): kwargs = dict(index_col=0) lines = list(csv.reader(StringIO(data))) - reader = TextParser(lines, chunksize=2, **kwargs) + with TextParser(lines, chunksize=2, **kwargs) as reader: + chunks = list(reader) expected = parser.read_csv(StringIO(data), **kwargs) - chunks = list(reader) tm.assert_frame_equal(chunks[0], expected[:2]) tm.assert_frame_equal(chunks[1], expected[2:4]) @@ -686,10 +683,10 @@ def test_reader_list_skiprows(all_parsers): kwargs = dict(index_col=0) lines = list(csv.reader(StringIO(data))) - reader = TextParser(lines, chunksize=2, skiprows=[1], **kwargs) + with TextParser(lines, chunksize=2, skiprows=[1], **kwargs) as reader: + chunks = list(reader) expected = parser.read_csv(StringIO(data), **kwargs) - chunks = list(reader) tm.assert_frame_equal(chunks[0], expected[1:3]) @@ -703,8 +700,8 @@ def test_iterator_stop_on_chunksize(all_parsers): baz,7,8,9 """ - reader = parser.read_csv(StringIO(data), chunksize=1) - result = list(reader) + with parser.read_csv(StringIO(data), chunksize=1) as reader: + result = list(reader) assert len(result) == 3 expected = DataFrame( @@ -724,7 +721,8 @@ def test_iterator_skipfooter_errors(all_parsers, kwargs): data = "a\n1\n2" with pytest.raises(ValueError, match=msg): - parser.read_csv(StringIO(data), skipfooter=1, **kwargs) + with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _: + pass def test_nrows_skipfooter_errors(all_parsers): @@ -1362,7 +1360,8 @@ def test_empty_with_nrows_chunksize(all_parsers, iterator): data = StringIO("foo,bar\n") if iterator: - result = next(iter(parser.read_csv(data, chunksize=nrows))) + with parser.read_csv(data, chunksize=nrows) as reader: + result = next(iter(reader)) else: result = parser.read_csv(data, nrows=nrows) @@ -2056,10 +2055,9 @@ def test_read_csv_memory_growth_chunksize(all_parsers): for i in range(1000): f.write(str(i) + "\n") - result = parser.read_csv(path, chunksize=20) - - for _ in result: - pass + with parser.read_csv(path, chunksize=20) as result: + for _ in result: + pass def test_read_csv_raises_on_header_prefix(all_parsers): @@ -2310,3 +2308,35 @@ def test_memory_map_compression(all_parsers, compression): parser.read_csv(path, memory_map=True, compression=compression), expected, ) + + +def test_context_manager(all_parsers, datapath): + # make sure that opened files are closed + parser = all_parsers + + path = datapath("io", "data", "csv", "iris.csv") + + reader = parser.read_csv(path, chunksize=1) + assert not reader._engine.handles.handle.closed + try: + with reader: + next(reader) + assert False + except AssertionError: + assert reader._engine.handles.handle.closed + + +def test_context_manageri_user_provided(all_parsers, datapath): + # make sure that user-provided handles are not closed + parser = all_parsers + + with open(datapath("io", "data", "csv", "iris.csv"), mode="r") as path: + + reader = parser.read_csv(path, chunksize=1) + assert not reader._engine.handles.handle.closed + try: + with reader: + next(reader) + assert False + except AssertionError: + assert not reader._engine.handles.handle.closed diff --git a/pandas/tests/io/parser/test_dtypes.py b/pandas/tests/io/parser/test_dtypes.py index 930ce1a695e1f..1e68e54b413b0 100644 --- a/pandas/tests/io/parser/test_dtypes.py +++ b/pandas/tests/io/parser/test_dtypes.py @@ -213,10 +213,11 @@ def test_categorical_dtype_chunksize_infer_categories(all_parsers): DataFrame({"a": [1, 1], "b": Categorical(["a", "b"])}), DataFrame({"a": [1, 2], "b": Categorical(["b", "c"])}, index=[2, 3]), ] - actuals = parser.read_csv(StringIO(data), dtype={"b": "category"}, chunksize=2) - - for actual, expected in zip(actuals, expecteds): - tm.assert_frame_equal(actual, expected) + with parser.read_csv( + StringIO(data), dtype={"b": "category"}, chunksize=2 + ) as actuals: + for actual, expected in zip(actuals, expecteds): + tm.assert_frame_equal(actual, expected) def test_categorical_dtype_chunksize_explicit_categories(all_parsers): @@ -235,10 +236,9 @@ def test_categorical_dtype_chunksize_explicit_categories(all_parsers): ), ] dtype = CategoricalDtype(cats) - actuals = parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) - - for actual, expected in zip(actuals, expecteds): - tm.assert_frame_equal(actual, expected) + with parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) as actuals: + for actual, expected in zip(actuals, expecteds): + tm.assert_frame_equal(actual, expected) @pytest.mark.parametrize("ordered", [False, True]) diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index b8b03cbd14a1d..97f82b9a01a9a 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -122,41 +122,45 @@ def test_parse_public_s3_bucket_chunked(self, tips_df, s3so): # Read with a chunksize chunksize = 5 for ext, comp in [("", None), (".gz", "gzip"), (".bz2", "bz2")]: - df_reader = read_csv( + with read_csv( "s3://pandas-test/tips.csv" + ext, chunksize=chunksize, compression=comp, storage_options=s3so, - ) - assert df_reader.chunksize == chunksize - for i_chunk in [0, 1, 2]: - # Read a couple of chunks and make sure we see them - # properly. - df = df_reader.get_chunk() - assert isinstance(df, DataFrame) - assert not df.empty - true_df = tips_df.iloc[chunksize * i_chunk : chunksize * (i_chunk + 1)] - tm.assert_frame_equal(true_df, df) + ) as df_reader: + assert df_reader.chunksize == chunksize + for i_chunk in [0, 1, 2]: + # Read a couple of chunks and make sure we see them + # properly. + df = df_reader.get_chunk() + assert isinstance(df, DataFrame) + assert not df.empty + true_df = tips_df.iloc[ + chunksize * i_chunk : chunksize * (i_chunk + 1) + ] + tm.assert_frame_equal(true_df, df) def test_parse_public_s3_bucket_chunked_python(self, tips_df, s3so): # Read with a chunksize using the Python parser chunksize = 5 for ext, comp in [("", None), (".gz", "gzip"), (".bz2", "bz2")]: - df_reader = read_csv( + with read_csv( "s3://pandas-test/tips.csv" + ext, chunksize=chunksize, compression=comp, engine="python", storage_options=s3so, - ) - assert df_reader.chunksize == chunksize - for i_chunk in [0, 1, 2]: - # Read a couple of chunks and make sure we see them properly. - df = df_reader.get_chunk() - assert isinstance(df, DataFrame) - assert not df.empty - true_df = tips_df.iloc[chunksize * i_chunk : chunksize * (i_chunk + 1)] - tm.assert_frame_equal(true_df, df) + ) as df_reader: + assert df_reader.chunksize == chunksize + for i_chunk in [0, 1, 2]: + # Read a couple of chunks and make sure we see them properly. + df = df_reader.get_chunk() + assert isinstance(df, DataFrame) + assert not df.empty + true_df = tips_df.iloc[ + chunksize * i_chunk : chunksize * (i_chunk + 1) + ] + tm.assert_frame_equal(true_df, df) def test_parse_public_s3_bucket_python(self, tips_df, s3so): for ext, comp in [("", None), (".gz", "gzip"), (".bz2", "bz2")]: diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 7a5203ca86520..a20ca508ebbfe 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -1020,13 +1020,13 @@ def test_multiple_date_cols_chunked(all_parsers): ) expected = expected.set_index("nominal") - reader = parser.read_csv( + with parser.read_csv( StringIO(data), parse_dates={"nominal": [1, 2]}, index_col="nominal", chunksize=2, - ) - chunks = list(reader) + ) as reader: + chunks = list(reader) tm.assert_frame_equal(chunks[0], expected[:2]) tm.assert_frame_equal(chunks[1], expected[2:4]) diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index 413b78a52ad38..1af69785c7584 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -336,8 +336,10 @@ def test_empty_field_eof(self): def test_empty_csv_input(self): # GH14867 - df = read_csv(StringIO(), chunksize=20, header=None, names=["a", "b", "c"]) - assert isinstance(df, TextFileReader) + with read_csv( + StringIO(), chunksize=20, header=None, names=["a", "b", "c"] + ) as df: + assert isinstance(df, TextFileReader) def assert_array_dicts_equal(left, right): diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py index 9de6ca75fd4d9..cca62c5af59a1 100644 --- a/pandas/tests/io/sas/test_sas7bdat.py +++ b/pandas/tests/io/sas/test_sas7bdat.py @@ -52,24 +52,22 @@ def test_from_buffer(self): with open(fname, "rb") as f: byts = f.read() buf = io.BytesIO(byts) - rdr = pd.read_sas( + with pd.read_sas( buf, format="sas7bdat", iterator=True, encoding="utf-8" - ) - df = rdr.read() + ) as rdr: + df = rdr.read() tm.assert_frame_equal(df, df0, check_exact=False) - rdr.close() def test_from_iterator(self): for j in 0, 1: df0 = self.data[j] for k in self.test_ix[j]: fname = os.path.join(self.dirpath, f"test{k}.sas7bdat") - rdr = pd.read_sas(fname, iterator=True, encoding="utf-8") - df = rdr.read(2) - tm.assert_frame_equal(df, df0.iloc[0:2, :]) - df = rdr.read(3) - tm.assert_frame_equal(df, df0.iloc[2:5, :]) - rdr.close() + with pd.read_sas(fname, iterator=True, encoding="utf-8") as rdr: + df = rdr.read(2) + tm.assert_frame_equal(df, df0.iloc[0:2, :]) + df = rdr.read(3) + tm.assert_frame_equal(df, df0.iloc[2:5, :]) def test_path_pathlib(self): for j in 0, 1: @@ -96,25 +94,24 @@ def test_iterator_loop(self): for k in self.test_ix[j]: for chunksize in 3, 5, 10, 11: fname = os.path.join(self.dirpath, f"test{k}.sas7bdat") - rdr = pd.read_sas(fname, chunksize=10, encoding="utf-8") - y = 0 - for x in rdr: - y += x.shape[0] + with pd.read_sas(fname, chunksize=10, encoding="utf-8") as rdr: + y = 0 + for x in rdr: + y += x.shape[0] assert y == rdr.row_count - rdr.close() def test_iterator_read_too_much(self): # github #14734 k = self.test_ix[0][0] fname = os.path.join(self.dirpath, f"test{k}.sas7bdat") - rdr = pd.read_sas(fname, format="sas7bdat", iterator=True, encoding="utf-8") - d1 = rdr.read(rdr.row_count + 20) - rdr.close() + with pd.read_sas( + fname, format="sas7bdat", iterator=True, encoding="utf-8" + ) as rdr: + d1 = rdr.read(rdr.row_count + 20) - rdr = pd.read_sas(fname, iterator=True, encoding="utf-8") - d2 = rdr.read(rdr.row_count + 20) + with pd.read_sas(fname, iterator=True, encoding="utf-8") as rdr: + d2 = rdr.read(rdr.row_count + 20) tm.assert_frame_equal(d1, d2) - rdr.close() def test_encoding_options(datapath): diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py index 939edb3d8e0b4..a8713f5bf36c9 100644 --- a/pandas/tests/io/sas/test_xport.py +++ b/pandas/tests/io/sas/test_xport.py @@ -47,29 +47,25 @@ def test1_basic(self): num_rows = data.shape[0] # Test reading beyond end of file - reader = read_sas(self.file01, format="xport", iterator=True) - data = reader.read(num_rows + 100) + with read_sas(self.file01, format="xport", iterator=True) as reader: + data = reader.read(num_rows + 100) assert data.shape[0] == num_rows - reader.close() # Test incremental read with `read` method. - reader = read_sas(self.file01, format="xport", iterator=True) - data = reader.read(10) - reader.close() + with read_sas(self.file01, format="xport", iterator=True) as reader: + data = reader.read(10) tm.assert_frame_equal(data, data_csv.iloc[0:10, :]) # Test incremental read with `get_chunk` method. - reader = read_sas(self.file01, format="xport", chunksize=10) - data = reader.get_chunk() - reader.close() + with read_sas(self.file01, format="xport", chunksize=10) as reader: + data = reader.get_chunk() tm.assert_frame_equal(data, data_csv.iloc[0:10, :]) # Test read in loop m = 0 - reader = read_sas(self.file01, format="xport", chunksize=100) - for x in reader: - m += x.shape[0] - reader.close() + with read_sas(self.file01, format="xport", chunksize=100) as reader: + for x in reader: + m += x.shape[0] assert m == num_rows # Read full file with `read_sas` method @@ -89,15 +85,17 @@ def test1_index(self): tm.assert_frame_equal(data, data_csv, check_index_type=False) # Test incremental read with `read` method. - reader = read_sas(self.file01, index="SEQN", format="xport", iterator=True) - data = reader.read(10) - reader.close() + with read_sas( + self.file01, index="SEQN", format="xport", iterator=True + ) as reader: + data = reader.read(10) tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) # Test incremental read with `get_chunk` method. - reader = read_sas(self.file01, index="SEQN", format="xport", chunksize=10) - data = reader.get_chunk() - reader.close() + with read_sas( + self.file01, index="SEQN", format="xport", chunksize=10 + ) as reader: + data = reader.get_chunk() tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) def test1_incremental(self): @@ -107,9 +105,8 @@ def test1_incremental(self): data_csv = data_csv.set_index("SEQN") numeric_as_float(data_csv) - reader = read_sas(self.file01, index="SEQN", chunksize=1000) - - all_data = list(reader) + with read_sas(self.file01, index="SEQN", chunksize=1000) as reader: + all_data = list(reader) data = pd.concat(all_data, axis=0) tm.assert_frame_equal(data, data_csv, check_index_type=False) diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index c7a7101b5fe17..c3b21daa0ac04 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -121,16 +121,16 @@ def test_get_handle_with_buffer(self): input_buffer.close() def test_iterator(self): - reader = pd.read_csv(StringIO(self.data1), chunksize=1) - result = pd.concat(reader, ignore_index=True) + with pd.read_csv(StringIO(self.data1), chunksize=1) as reader: + result = pd.concat(reader, ignore_index=True) expected = pd.read_csv(StringIO(self.data1)) tm.assert_frame_equal(result, expected) # GH12153 - it = pd.read_csv(StringIO(self.data1), chunksize=1) - first = next(it) - tm.assert_frame_equal(first, expected.iloc[[0]]) - tm.assert_frame_equal(pd.concat(it), expected.iloc[1:]) + with pd.read_csv(StringIO(self.data1), chunksize=1) as it: + first = next(it) + tm.assert_frame_equal(first, expected.iloc[[0]]) + tm.assert_frame_equal(pd.concat(it), expected.iloc[1:]) @pytest.mark.parametrize( "reader, module, error_class, fn_ext", diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index b065aa187f5fb..24944281419c3 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -1974,12 +1974,12 @@ def test_iterator_value_labels(): df = DataFrame({f"col{k}": pd.Categorical(values, ordered=True) for k in range(2)}) with tm.ensure_clean() as path: df.to_stata(path, write_index=False) - reader = pd.read_stata(path, chunksize=100) expected = pd.Index(["a_label", "b_label", "c_label"], dtype="object") - for j, chunk in enumerate(reader): - for i in range(2): - tm.assert_index_equal(chunk.dtypes[i].categories, expected) - tm.assert_frame_equal(chunk, df.iloc[j * 100 : (j + 1) * 100]) + with pd.read_stata(path, chunksize=100) as reader: + for j, chunk in enumerate(reader): + for i in range(2): + tm.assert_index_equal(chunk.dtypes[i].categories, expected) + tm.assert_frame_equal(chunk, df.iloc[j * 100 : (j + 1) * 100]) def test_precision_loss(): diff --git a/pandas/tests/reshape/concat/test_invalid.py b/pandas/tests/reshape/concat/test_invalid.py index ec8167906a60c..cc9f09c16fb43 100644 --- a/pandas/tests/reshape/concat/test_invalid.py +++ b/pandas/tests/reshape/concat/test_invalid.py @@ -45,7 +45,7 @@ def test_concat_invalid_first_argument(self): bar2,12,13,14,15 """ - reader = read_csv(StringIO(data), chunksize=1) - result = concat(reader, ignore_index=True) + with read_csv(StringIO(data), chunksize=1) as reader: + result = concat(reader, ignore_index=True) expected = read_csv(StringIO(data)) tm.assert_frame_equal(result, expected)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Allows (and encourages) the following use: ```py import pandas as pd filename = "pandas/tests/io/data/csv/iris.csv" chunksize = 2 with pd.read_csv(filename, chunksize=chunksize) as reader: for chunk in reader: # risky code that might raise ``` Same can be done for `read_json/sas` (I think these are all methods that support `chunksize`). If this PR should make it into 1.2, I can quickly add the changes for json/sas as well. Are there more places to promote this new context manager?
https://api.github.com/repos/pandas-dev/pandas/pulls/38225
2020-12-02T02:54:26Z
2020-12-04T18:58:48Z
2020-12-04T18:58:48Z
2020-12-04T20:40:23Z
TST: tighten testing assertions
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 4aefb73bf912c..1d2208592a06d 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -307,9 +307,8 @@ def test_groupby_levels_and_columns(self): # reset_index changes columns dtype to object by_columns = df.reset_index().groupby(idx_names).mean() - tm.assert_frame_equal(by_levels, by_columns, check_column_type=False) - - by_columns.columns = Index(by_columns.columns, dtype=np.int64) + # without casting, by_columns.columns is object-dtype + by_columns.columns = by_columns.columns.astype(np.int64) tm.assert_frame_equal(by_levels, by_columns) def test_groupby_categorical_index_and_columns(self, observed): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index cf6c2878acd9a..f6aa2371cf13a 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1782,21 +1782,23 @@ def test_series_getitem_label_list_missing_integer_values(): @pytest.mark.parametrize( - "columns, column_key, expected_columns, check_column_type", + "columns, column_key, expected_columns", [ - ([2011, 2012, 2013], [2011, 2012], [0, 1], True), - ([2011, 2012, "All"], [2011, 2012], [0, 1], False), - ([2011, 2012, "All"], [2011, "All"], [0, 2], True), + ([2011, 2012, 2013], [2011, 2012], [0, 1]), + ([2011, 2012, "All"], [2011, 2012], [0, 1]), + ([2011, 2012, "All"], [2011, "All"], [0, 2]), ], ) -def test_loc_getitem_label_list_integer_labels( - columns, column_key, expected_columns, check_column_type -): +def test_loc_getitem_label_list_integer_labels(columns, column_key, expected_columns): # gh-14836 df = DataFrame(np.random.rand(3, 3), columns=columns, index=list("ABC")) expected = df.iloc[:, expected_columns] result = df.loc[["A", "B", "C"], column_key] - tm.assert_frame_equal(result, expected, check_column_type=check_column_type) + + if df.columns.is_object() and all(isinstance(x, int) for x in column_key): + expected.columns = expected.columns.astype(int) + + tm.assert_frame_equal(result, expected, check_column_type=True) def test_loc_setitem_float_intindex(): diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index f15a64947d83d..80ebeb4c03d89 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -472,12 +472,12 @@ def test_int_types(self, np_type, path): # Test with convert_float=False comes back as float. float_frame = df.astype(float) + float_frame.columns = float_frame.columns.astype(float) + float_frame.index = float_frame.index.astype(float) recons = pd.read_excel( path, sheet_name="test1", convert_float=False, index_col=0 ) - tm.assert_frame_equal( - recons, float_frame, check_index_type=False, check_column_type=False - ) + tm.assert_frame_equal(recons, float_frame) @pytest.mark.parametrize("np_type", [np.float16, np.float32, np.float64]) def test_float_types(self, np_type, path): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 7a5aca13b33f5..ce95eb59ed3c4 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -727,9 +727,7 @@ def test_series_with_dtype_datetime(self, dtype, expected): def test_frame_from_json_precise_float(self): df = DataFrame([[4.56, 4.56, 4.56], [4.56, 4.56, 4.56]]) result = read_json(df.to_json(), precise_float=True) - tm.assert_frame_equal( - result, df, check_index_type=False, check_column_type=False - ) + tm.assert_frame_equal(result, df) def test_typ(self): diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index afd2f56efb935..a63a98cf9858b 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1631,16 +1631,12 @@ def check_col(key, name, size): & (df_new.A > 0) & (df_new.B < 0) ] - tm.assert_frame_equal( - result, expected, check_index_type=False, check_freq=False - ) + tm.assert_frame_equal(result, expected) # yield an empty frame result = store.select("df", "string='foo' and string2='cool'") expected = df_new[(df_new.string == "foo") & (df_new.string2 == "cool")] - tm.assert_frame_equal( - result, expected, check_index_type=False, check_freq=False - ) + tm.assert_frame_equal(result, expected) with ensure_clean_store(setup_path) as store: # doc example @@ -1660,16 +1656,11 @@ def check_col(key, name, size): result = store.select("df_dc", "B>0") expected = df_dc[df_dc.B > 0] - tm.assert_frame_equal( - result, expected, check_index_type=False, check_freq=False - ) + tm.assert_frame_equal(result, expected) result = store.select("df_dc", ["B > 0", "C > 0", "string == foo"]) expected = df_dc[(df_dc.B > 0) & (df_dc.C > 0) & (df_dc.string == "foo")] - tm.assert_frame_equal( - result, expected, check_index_type=False, check_freq=False - ) - # FIXME: 2020-05-07 freq check randomly fails in the CI + tm.assert_frame_equal(result, expected) with ensure_clean_store(setup_path) as store: # doc example part 2 @@ -2374,9 +2365,7 @@ def test_series(self, setup_path): ts3 = Series( ts.values, Index(np.asarray(ts.index, dtype=object), dtype=object) ) - self._check_roundtrip( - ts3, tm.assert_series_equal, path=setup_path, check_index_type=False - ) + self._check_roundtrip(ts3, tm.assert_series_equal, path=setup_path) def test_float_index(self, setup_path):
https://api.github.com/repos/pandas-dev/pandas/pulls/38223
2020-12-02T01:21:51Z
2020-12-02T12:09:00Z
2020-12-02T12:09:00Z
2020-12-02T14:48:19Z
BUG: DataFrame.drop raising TypeError for string label with non-unique MultiIndex and no level provided
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d0afc24aaecac..3fe8327df8c50 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -140,7 +140,7 @@ Missing MultiIndex ^^^^^^^^^^ -- +- Bug in :meth:`DataFrame.drop` raising ``TypeError`` when :class:`MultiIndex` is non-unique and no level is provided (:issue:`36293`) - I/O diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 41cb76d88957e..f9aa5ca9e8ea9 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4182,6 +4182,10 @@ def _drop_axis( # GH 18561 MultiIndex.drop should raise if label is absent if errors == "raise" and indexer.all(): raise KeyError(f"{labels} not found in axis") + elif isinstance(axis, MultiIndex) and labels.dtype == "object": + # Set level to zero in case of MultiIndex and label is string, + # because isin can't handle strings for MultiIndexes GH#36293 + indexer = ~axis.get_level_values(0).isin(labels) else: indexer = ~axis.isin(labels) # Check if label doesn't exist along axis diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index eb5bc31f3aa8f..dd93eac8b7110 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -441,3 +441,11 @@ def test_inplace_drop_and_operation(self, operation, inplace): # Perform operation and check result getattr(y, operation)(1) tm.assert_frame_equal(df, expected) + + def test_drop_with_non_unique_multiindex(self): + # GH#36293 + mi = MultiIndex.from_arrays([["x", "y", "x"], ["i", "j", "i"]]) + df = DataFrame([1, 2, 3], index=mi) + result = df.drop(index="x") + expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]])) + tm.assert_frame_equal(result, expected)
- [x] closes #36293 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry As far as I know, isin needs a level input when only a string is given for a MultiIndex. If this should not change, we have to set level=0 in this case.
https://api.github.com/repos/pandas-dev/pandas/pulls/38220
2020-12-01T22:49:48Z
2020-12-14T23:55:16Z
2020-12-14T23:55:16Z
2020-12-15T18:46:47Z
Update Dockerfile to use conda-forge compilers
diff --git a/Dockerfile b/Dockerfile index 5d7a2b9e6b743..de1c564921de9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM continuumio/miniconda3 +FROM quay.io/condaforge/miniforge3 # if you forked pandas, you can pass in your own GitHub username to use your fork # i.e. gh_username=myname @@ -15,10 +15,6 @@ RUN apt-get update \ # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed && apt-get -y install git iproute2 procps iproute2 lsb-release \ # - # Install C compilers (gcc not enough, so just went with build-essential which admittedly might be overkill), - # needed to build pandas C extensions - && apt-get -y install build-essential \ - # # cleanup && apt-get autoremove -y \ && apt-get clean -y \ @@ -39,9 +35,14 @@ RUN mkdir "$pandas_home" \ # we just update the base/root one from the 'environment.yml' file instead of creating a new one. # # Set up environment -RUN conda env update -n base -f "$pandas_home/environment.yml" +RUN conda install -y mamba +RUN mamba env update -n base -f "$pandas_home/environment.yml" # Build C extensions and pandas -RUN cd "$pandas_home" \ +SHELL ["/bin/bash", "-c"] +RUN . /opt/conda/etc/profile.d/conda.sh \ + && conda activate base \ + && cd "$pandas_home" \ + && export \ && python setup.py build_ext -j 4 \ && python -m pip install -e .
Additionally I switched to the miniforge3 image as this bases its installation on conda-forge and I also have used `mamba` to install the environment as this massively saves time. - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38219
2020-12-01T22:29:33Z
2020-12-02T12:09:14Z
2020-12-02T12:09:14Z
2021-01-24T05:32:54Z
Corrected the grammar in Exception
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index c5260deafc0c3..ee21ff01c06fa 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -355,7 +355,7 @@ def wrap_results_for_axis( try: result = self.obj._constructor(data=results) except ValueError as err: - if "arrays must all be same length" in str(err): + if "All arrays must be of the same length" in str(err): # e.g. result = [[2, 3], [1.5], ['foo', 'bar']] # see test_agg_listlike_result GH#29587 res = self.obj._constructor_sliced(results) diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index eefd1a604f894..35279a8beebba 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -398,7 +398,7 @@ def extract_index(data) -> Index: if have_raw_arrays: lengths = list(set(raw_lengths)) if len(lengths) > 1: - raise ValueError("arrays must all be same length") + raise ValueError("All arrays must be of the same length") if have_dicts: raise ValueError( diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index a98723e9e31f8..1c31988324cba 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1367,7 +1367,7 @@ class CustomDict(dict): def test_constructor_ragged(self): data = {"A": np.random.randn(10), "B": np.random.randn(8)} - with pytest.raises(ValueError, match="arrays must all be same length"): + with pytest.raises(ValueError, match="All arrays must be of the same length"): DataFrame(data) def test_constructor_scalar(self):
Exception on different arrays' length corrected - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38216
2020-12-01T19:26:51Z
2020-12-10T00:02:47Z
2020-12-10T00:02:47Z
2020-12-10T00:03:45Z
TST: add cases for nearest_workday and before_nearest_workday
diff --git a/pandas/tests/tseries/holiday/test_observance.py b/pandas/tests/tseries/holiday/test_observance.py index 9ee63d2a36556..83038ad254b77 100644 --- a/pandas/tests/tseries/holiday/test_observance.py +++ b/pandas/tests/tseries/holiday/test_observance.py @@ -22,6 +22,7 @@ _SUNDAY = datetime(2014, 4, 13) _MONDAY = datetime(2014, 4, 14) _TUESDAY = datetime(2014, 4, 15) +_NEXT_WEDNESDAY = datetime(2014, 4, 16) @pytest.mark.parametrize("day", [_SATURDAY, _SUNDAY]) @@ -60,7 +61,15 @@ def test_weekend_to_monday(day, expected): @pytest.mark.parametrize( - "day,expected", [(_SATURDAY, _MONDAY), (_SUNDAY, _MONDAY), (_MONDAY, _TUESDAY)] + "day,expected", + [ + (_WEDNESDAY, _THURSDAY), + (_THURSDAY, _FRIDAY), + (_SATURDAY, _MONDAY), + (_SUNDAY, _MONDAY), + (_MONDAY, _TUESDAY), + (_TUESDAY, _NEXT_WEDNESDAY), # WED is same week as TUE + ], ) def test_next_workday(day, expected): assert next_workday(day) == expected @@ -74,7 +83,16 @@ def test_previous_workday(day, expected): @pytest.mark.parametrize( - "day,expected", [(_SATURDAY, _THURSDAY), (_SUNDAY, _FRIDAY), (_TUESDAY, _MONDAY)] + "day,expected", + [ + (_THURSDAY, _WEDNESDAY), + (_FRIDAY, _THURSDAY), + (_SATURDAY, _THURSDAY), + (_SUNDAY, _FRIDAY), + (_MONDAY, _FRIDAY), # last week Friday + (_TUESDAY, _MONDAY), + (_NEXT_WEDNESDAY, _TUESDAY), # WED is same week as TUE + ], ) def test_before_nearest_workday(day, expected): assert before_nearest_workday(day) == expected
- [ ] xref #38139 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Add cases for testing observance rules ``nearest_workday`` and ``before_nearest_workday`` for their full coverage.
https://api.github.com/repos/pandas-dev/pandas/pulls/38215
2020-12-01T18:49:07Z
2020-12-02T12:09:40Z
2020-12-02T12:09:40Z
2020-12-02T14:27:49Z
CI: xfail test_area_lim
diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 9e4004355f26c..dc7478fe6ef4a 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -456,22 +456,28 @@ def test_line_lim(self): assert xmin <= lines[0].get_data()[0][0] assert xmax >= lines[0].get_data()[0][-1] - def test_area_lim(self): + @pytest.mark.xfail( + strict=False, + reason="2020-12-01 this has been failing periodically on the " + "ymin==0 assertion for a week or so.", + ) + @pytest.mark.parametrize("stacked", [True, False]) + def test_area_lim(self, stacked): df = DataFrame(np.random.rand(6, 4), columns=["x", "y", "z", "four"]) neg_df = -df - for stacked in [True, False]: - ax = _check_plot_works(df.plot.area, stacked=stacked) - xmin, xmax = ax.get_xlim() - ymin, ymax = ax.get_ylim() - lines = ax.get_lines() - assert xmin <= lines[0].get_data()[0][0] - assert xmax >= lines[0].get_data()[0][-1] - assert ymin == 0 - ax = _check_plot_works(neg_df.plot.area, stacked=stacked) - ymin, ymax = ax.get_ylim() - assert ymax == 0 + ax = _check_plot_works(df.plot.area, stacked=stacked) + xmin, xmax = ax.get_xlim() + ymin, ymax = ax.get_ylim() + lines = ax.get_lines() + assert xmin <= lines[0].get_data()[0][0] + assert xmax >= lines[0].get_data()[0][-1] + assert ymin == 0 + + ax = _check_plot_works(neg_df.plot.area, stacked=stacked) + ymin, ymax = ax.get_ylim() + assert ymax == 0 def test_area_sharey_dont_overwrite(self): # GH37942
https://api.github.com/repos/pandas-dev/pandas/pulls/38212
2020-12-01T16:21:26Z
2020-12-01T22:04:21Z
2020-12-01T22:04:21Z
2020-12-01T23:47:35Z
Backport PR #38057: PERF: fix regression in creation of resulting index in RollingGroupby
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index f0dd908f81043..0075b7095aa93 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -216,4 +216,18 @@ def time_rolling_offset(self, method): getattr(self.groupby_roll_offset, method)() +class GroupbyLargeGroups: + # https://github.com/pandas-dev/pandas/issues/38038 + # specific example where the rolling operation on a larger dataframe + # is relatively cheap (few but large groups), but creation of + # MultiIndex of result can be expensive + + def setup(self): + N = 100000 + self.df = pd.DataFrame({"A": [1, 2] * int(N / 2), "B": np.random.randn(N)}) + + def time_rolling_multiindex_creation(self): + self.df.groupby("A").rolling(3).mean() + + from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst index 4770ab37e08d2..0e2e510147603 100644 --- a/doc/source/whatsnew/v1.1.5.rst +++ b/doc/source/whatsnew/v1.1.5.rst @@ -24,6 +24,7 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.groupby` aggregation with out-of-bounds datetime objects in an object-dtype column (:issue:`36003`) - Fixed regression in ``df.groupby(..).rolling(..)`` with the resulting :class:`MultiIndex` when grouping by a label that is in the index (:issue:`37641`) - Fixed regression in :meth:`DataFrame.fillna` not filling ``NaN`` after other operations such as :meth:`DataFrame.pivot` (:issue:`36495`). +- Fixed performance regression in ``df.groupby(..).rolling(..)`` (:issue:`38038`) - Fixed regression in :meth:`MultiIndex.intersection` returning duplicates when at least one of the indexes had duplicates (:issue:`36915`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index ce7281988e105..237c29a9b0c26 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -2216,22 +2216,29 @@ def _apply( # Our result will have still kept the column in the result result = result.drop(columns=column_keys, errors="ignore") - result_index_data = [] - for key, values in self._groupby.grouper.indices.items(): - for value in values: - data = [ - *com.maybe_make_list(key), - *com.maybe_make_list( - grouped_object_index[value] - if grouped_object_index is not None - else [] - ), - ] - result_index_data.append(tuple(data)) - - result_index = MultiIndex.from_tuples( - result_index_data, names=result_index_names + codes = self._groupby.grouper.codes + levels = self._groupby.grouper.levels + + group_indices = self._groupby.grouper.indices.values() + if group_indices: + indexer = np.concatenate(list(group_indices)) + else: + indexer = np.array([], dtype=np.intp) + codes = [c.take(indexer) for c in codes] + + # if the index of the original dataframe needs to be preserved, append + # this index (but reordered) to the codes/levels from the groupby + if grouped_object_index is not None: + idx = grouped_object_index.take(indexer) + if not isinstance(idx, MultiIndex): + idx = MultiIndex.from_arrays([idx]) + codes.extend(list(idx.codes)) + levels.extend(list(idx.levels)) + + result_index = MultiIndex( + levels, codes, names=result_index_names, verify_integrity=False ) + result.index = result_index return result diff --git a/pandas/tests/window/test_grouper.py b/pandas/tests/window/test_grouper.py index da31fbaddc6e4..a5f759fb90dab 100644 --- a/pandas/tests/window/test_grouper.py +++ b/pandas/tests/window/test_grouper.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, MultiIndex, Series +from pandas import DataFrame, Index, MultiIndex, Series import pandas._testing as tm from pandas.core.groupby.groupby import get_groupby @@ -396,14 +396,25 @@ def test_groupby_rolling_index_changed(self, func): def test_groupby_rolling_empty_frame(self): # GH 36197 - expected = pd.DataFrame({"s1": []}) + expected = DataFrame({"s1": []}) result = expected.groupby("s1").rolling(window=1).sum() - expected.index = pd.MultiIndex.from_tuples([], names=["s1", None]) + # GH-38057 from_tuples gives empty object dtype, we now get float/int levels + # expected.index = MultiIndex.from_tuples([], names=["s1", None]) + expected.index = MultiIndex.from_product( + [Index([], dtype="float64"), Index([], dtype="int64")], names=["s1", None] + ) tm.assert_frame_equal(result, expected) - expected = pd.DataFrame({"s1": [], "s2": []}) + expected = DataFrame({"s1": [], "s2": []}) result = expected.groupby(["s1", "s2"]).rolling(window=1).sum() - expected.index = pd.MultiIndex.from_tuples([], names=["s1", "s2", None]) + expected.index = MultiIndex.from_product( + [ + Index([], dtype="float64"), + Index([], dtype="float64"), + Index([], dtype="int64"), + ], + names=["s1", "s2", None], + ) tm.assert_frame_equal(result, expected) def test_groupby_rolling_string_index(self): @@ -479,3 +490,57 @@ def test_groupby_rolling_index_level_and_column_label(self): ), ) tm.assert_frame_equal(result, expected) + + def test_groupby_rolling_resulting_multiindex(self): + # a few different cases checking the created MultiIndex of the result + # https://github.com/pandas-dev/pandas/pull/38057 + + # grouping by 1 columns -> 2-level MI as result + df = DataFrame({"a": np.arange(8.0), "b": [1, 2] * 4}) + result = df.groupby("b").rolling(3).mean() + expected_index = MultiIndex.from_tuples( + [(1, 0), (1, 2), (1, 4), (1, 6), (2, 1), (2, 3), (2, 5), (2, 7)], + names=["b", None], + ) + tm.assert_index_equal(result.index, expected_index) + + # grouping by 2 columns -> 3-level MI as result + df = DataFrame({"a": np.arange(12.0), "b": [1, 2] * 6, "c": [1, 2, 3, 4] * 3}) + result = df.groupby(["b", "c"]).rolling(2).sum() + expected_index = MultiIndex.from_tuples( + [ + (1, 1, 0), + (1, 1, 4), + (1, 1, 8), + (1, 3, 2), + (1, 3, 6), + (1, 3, 10), + (2, 2, 1), + (2, 2, 5), + (2, 2, 9), + (2, 4, 3), + (2, 4, 7), + (2, 4, 11), + ], + names=["b", "c", None], + ) + tm.assert_index_equal(result.index, expected_index) + + # grouping with 1 level on dataframe with 2-level MI -> 3-level MI as result + df = DataFrame({"a": np.arange(8.0), "b": [1, 2] * 4, "c": [1, 2, 3, 4] * 2}) + df = df.set_index("c", append=True) + result = df.groupby("b").rolling(3).mean() + expected_index = MultiIndex.from_tuples( + [ + (1, 0, 1), + (1, 2, 3), + (1, 4, 1), + (1, 6, 3), + (2, 1, 2), + (2, 3, 4), + (2, 5, 2), + (2, 7, 4), + ], + names=["b", None, "c"], + ) + tm.assert_index_equal(result.index, expected_index)
Backport PR #38057
https://api.github.com/repos/pandas-dev/pandas/pulls/38211
2020-12-01T11:42:22Z
2020-12-01T12:57:49Z
2020-12-01T12:57:49Z
2020-12-01T12:57:53Z
Backport PR #38099: BUG: fix wrong error message in deprecated 2D indexing of Series with datetime values
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 12806170a9f6d..709924d800ebc 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2295,6 +2295,28 @@ def quantile(self, qs, interpolation="linear", axis=0): aware = self._holder(res_blk.values.ravel(), dtype=self.dtype) return self.make_block_same_class(aware, ndim=res_blk.ndim) + def _check_ndim(self, values, ndim): + """ + ndim inference and validation. + + This is overriden by the DatetimeTZBlock to check the case of 2D + data (values.ndim == 2), which should only be allowed if ndim is + also 2. + The case of 1D array is still allowed with both ndim of 1 or 2, as + if the case for other EAs. Therefore, we are only checking + `values.ndim > ndim` instead of `values.ndim != ndim` as for + consolidated blocks. + """ + if ndim is None: + ndim = values.ndim + + if values.ndim > ndim: + raise ValueError( + "Wrong number of dimensions. " + f"values.ndim != ndim [{values.ndim} != {ndim}]" + ) + return ndim + class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): __slots__ = () diff --git a/pandas/core/series.py b/pandas/core/series.py index 277aa1d095350..00fcd44d11cb4 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -967,7 +967,8 @@ def _get_values(self, indexer): except ValueError: # mpl compat if we look up e.g. ser[:, np.newaxis]; # see tests.series.timeseries.test_mpl_compat_hack - return self._values[indexer] + # the asarray is needed to avoid returning a 2D DatetimeArray + return np.asarray(self._values)[indexer] def _get_value(self, label, takeable: bool = False): """ diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index cf03dfb8ca9b7..246f27b566c43 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -133,10 +133,20 @@ def test_getitem_generator(string_series): tm.assert_series_equal(result2, expected) -def test_getitem_ndim_deprecated(): - s = pd.Series([0, 1]) +@pytest.mark.parametrize( + "series", + [ + Series([0, 1]), + Series(date_range("2012-01-01", periods=2)), + Series(date_range("2012-01-01", periods=2, tz="CET")), + ], +) +def test_getitem_ndim_deprecated(series): with tm.assert_produces_warning(FutureWarning): - s[:, None] + result = series[:, None] + + expected = np.asarray(series)[:, None] + tm.assert_numpy_array_equal(result, expected) def test_getitem_assignment_series_aligment():
Backport PR #38099 on branch 1.1.x
https://api.github.com/repos/pandas-dev/pandas/pulls/38210
2020-12-01T09:58:27Z
2020-12-01T12:53:01Z
2020-12-01T12:53:01Z
2020-12-01T12:54:04Z
CI/TST: fix CI with numpy dev for changed error message / dev version
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 3bb87a8346c78..159b42621f970 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -309,8 +309,7 @@ def test_loc_setitem_2d_to_1d_raises(): msg = "|".join( [ - r"shape mismatch: value array of shape \(2,2\) could not be " - r"broadcast to indexing result of shape \(2,\)", + r"shape mismatch: value array of shape \(2,2\)", r"cannot reshape array of size 4 into shape \(2,\)", ] ) diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py index fe5fc3e21d960..4ea3ebe5000ad 100644 --- a/pandas/tests/util/test_show_versions.py +++ b/pandas/tests/util/test_show_versions.py @@ -39,7 +39,7 @@ def test_show_versions(capsys): assert re.search(r"commit\s*:\s[0-9a-f]{40}\n", result) # check required dependency - assert re.search(r"numpy\s*:\s([0-9\.\+a-f]|dev)+\n", result) + assert re.search(r"numpy\s*:\s([0-9\.\+a-f\_]|dev)+\n", result) # check optional dependency assert re.search(r"pyarrow\s*:\s([0-9\.]+|None)\n", result)
https://api.github.com/repos/pandas-dev/pandas/pulls/38209
2020-12-01T09:50:12Z
2020-12-01T20:37:59Z
2020-12-01T20:37:59Z
2020-12-02T10:15:59Z
Revert "ENH: Improve performance for df.__setitem__ with list-like indexers"
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 4fd91c8aafe4b..74e0a3a434cde 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -358,14 +358,6 @@ def time_assign_with_setitem(self): for i in range(100): self.df[i] = np.random.randn(self.N) - def time_assign_list_like_with_setitem(self): - np.random.seed(1234) - self.df[list(range(100))] = np.random.randn(self.N, 100) - - def time_assign_list_of_columns_concat(self): - df = DataFrame(np.random.randn(self.N, 100)) - concat([self.df, df], axis=1) - class ChainIndexing: diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst index d36d20d4fd1db..0e2e510147603 100644 --- a/doc/source/whatsnew/v1.1.5.rst +++ b/doc/source/whatsnew/v1.1.5.rst @@ -24,7 +24,6 @@ Fixed regressions - Fixed regression in :meth:`DataFrame.groupby` aggregation with out-of-bounds datetime objects in an object-dtype column (:issue:`36003`) - Fixed regression in ``df.groupby(..).rolling(..)`` with the resulting :class:`MultiIndex` when grouping by a label that is in the index (:issue:`37641`) - Fixed regression in :meth:`DataFrame.fillna` not filling ``NaN`` after other operations such as :meth:`DataFrame.pivot` (:issue:`36495`). -- Fixed performance regression for :meth:`DataFrame.__setitem__` with list-like indexers (:issue:`37954`) - Fixed performance regression in ``df.groupby(..).rolling(..)`` (:issue:`38038`) - Fixed regression in :meth:`MultiIndex.intersection` returning duplicates when at least one of the indexes had duplicates (:issue:`36915`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 28e59df995a83..f6cf691ea911c 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -672,8 +672,17 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None): and not com.is_bool_indexer(key) and all(is_hashable(k) for k in key) ): - keys = self.obj.columns.union(key, sort=False) - self.obj._mgr = self.obj._mgr.reindex_axis(keys, 0) + for i, k in enumerate(key): + if k not in self.obj: + if value is None: + self.obj[k] = np.nan + elif is_array_like(value) and value.ndim == 2: + # GH#37964 have to select columnwise in case of array + self.obj[k] = value[:, i] + elif is_list_like(value): + self.obj[k] = value[i] + else: + self.obj[k] = value def __setitem__(self, key, value): if isinstance(key, tuple):
Reverts pandas-dev/pandas#38148 xref https://github.com/pandas-dev/pandas/issues/37784#issuecomment-736200698
https://api.github.com/repos/pandas-dev/pandas/pulls/38208
2020-12-01T08:55:12Z
2020-12-01T10:53:59Z
2020-12-01T10:53:59Z
2020-12-01T10:54:05Z
Rewrite dict literal for files in pandas/tests/frame
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index e33009f4597f0..6d4129a1a2a55 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -714,7 +714,7 @@ def test_setitem_empty(self): tm.assert_frame_equal(result, df) @pytest.mark.parametrize("dtype", ["float", "int64"]) - @pytest.mark.parametrize("kwargs", [dict(), dict(index=[1]), dict(columns=["A"])]) + @pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}]) def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): # see gh-10126 kwargs["dtype"] = dtype @@ -1238,7 +1238,7 @@ def test_single_element_ix_dont_upcast(self, float_frame): assert is_integer(result) # GH 11617 - df = DataFrame(dict(a=[1.23])) + df = DataFrame({"a": [1.23]}) df["b"] = 666 result = df.loc[0, "b"] diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 3495247585236..acdb5726e4adb 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -356,11 +356,11 @@ def test_where_datetime(self): # GH 3311 df = DataFrame( - dict( - A=date_range("20130102", periods=5), - B=date_range("20130104", periods=5), - C=np.random.randn(5), - ) + { + "A": date_range("20130102", periods=5), + "B": date_range("20130104", periods=5), + "C": np.random.randn(5), + } ) stamp = datetime(2013, 1, 3) @@ -618,7 +618,7 @@ def test_df_where_change_dtype(self): tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize("kwargs", [dict(), dict(other=None)]) + @pytest.mark.parametrize("kwargs", [{}, {"other": None}]) def test_df_where_with_category(self, kwargs): # GH#16979 df = DataFrame(np.arange(2 * 3).reshape(2, 3), columns=list("ABC")) diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index d59b70fa91a57..b427611099be3 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -53,10 +53,10 @@ def test_fillna_mixed_float(self, mixed_float_frame): mf = mixed_float_frame.reindex(columns=["A", "B", "D"]) mf.loc[mf.index[-10:], "A"] = np.nan result = mf.fillna(value=0) - _check_mixed_float(result, dtype=dict(C=None)) + _check_mixed_float(result, dtype={"C": None}) result = mf.fillna(method="pad") - _check_mixed_float(result, dtype=dict(C=None)) + _check_mixed_float(result, dtype={"C": None}) def test_fillna_empty(self): # empty frame (GH#2778) @@ -262,7 +262,7 @@ def test_fillna_dtype_conversion(self): tm.assert_frame_equal(result, expected) # equiv of replace - df = DataFrame(dict(A=[1, np.nan], B=[1.0, 2.0])) + df = DataFrame({"A": [1, np.nan], "B": [1.0, 2.0]}) for v in ["", 1, np.nan, 1.0]: expected = df.replace(np.nan, v) result = df.fillna(v) diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index be5f3ee9c8191..b94f54a4819c0 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -305,11 +305,11 @@ def test_sort_values_nat_values_in_int_column(self): float_values = (2.0, -1.797693e308) df = DataFrame( - dict(int=int_values, float=float_values), columns=["int", "float"] + {"int": int_values, "float": float_values}, columns=["int", "float"] ) df_reversed = DataFrame( - dict(int=int_values[::-1], float=float_values[::-1]), + {"int": int_values[::-1], "float": float_values[::-1]}, columns=["int", "float"], index=[1, 0], ) @@ -329,12 +329,12 @@ def test_sort_values_nat_values_in_int_column(self): # and now check if NaT is still considered as "na" for datetime64 # columns: df = DataFrame( - dict(datetime=[Timestamp("2016-01-01"), NaT], float=float_values), + {"datetime": [Timestamp("2016-01-01"), NaT], "float": float_values}, columns=["datetime", "float"], ) df_reversed = DataFrame( - dict(datetime=[NaT, Timestamp("2016-01-01")], float=float_values[::-1]), + {"datetime": [NaT, Timestamp("2016-01-01")], "float": float_values[::-1]}, columns=["datetime", "float"], index=[1, 0], ) diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py index fbe6d1f595874..4cf0b1febf0af 100644 --- a/pandas/tests/frame/methods/test_to_csv.py +++ b/pandas/tests/frame/methods/test_to_csv.py @@ -38,7 +38,7 @@ class TestDataFrameToCSV: def read_csv(self, path, **kwargs): - params = dict(index_col=0, parse_dates=True) + params = {"index_col": 0, "parse_dates": True} params.update(**kwargs) return pd.read_csv(path, **params) @@ -248,7 +248,7 @@ def make_dtnat_arr(n, nnat=None): # s3=make_dtnjat_arr(chunksize+5,0) with tm.ensure_clean("1.csv") as pth: - df = DataFrame(dict(a=s1, b=s2)) + df = DataFrame({"a": s1, "b": s2}) df.to_csv(pth, chunksize=chunksize) recons = self.read_csv(pth).apply(to_datetime) @@ -260,7 +260,7 @@ def _do_test( df, r_dtype=None, c_dtype=None, rnlvl=None, cnlvl=None, dupe_col=False ): - kwargs = dict(parse_dates=False) + kwargs = {"parse_dates": False} if cnlvl: if rnlvl is not None: kwargs["index_col"] = list(range(rnlvl)) @@ -291,7 +291,7 @@ def _to_uni(x): recons.index = ix recons = recons.iloc[:, rnlvl - 1 :] - type_map = dict(i="i", f="f", s="O", u="O", dt="O", p="O") + type_map = {"i": "i", "f": "f", "s": "O", "u": "O", "dt": "O", "p": "O"} if r_dtype: if r_dtype == "u": # unicode r_dtype = "O" @@ -738,7 +738,7 @@ def create_cols(name): df = pd.concat([df_float, df_int, df_bool, df_object, df_dt], axis=1) # dtype - dtypes = dict() + dtypes = {} for n, dtype in [ ("float", np.float64), ("int", np.int64), diff --git a/pandas/tests/frame/methods/test_to_records.py b/pandas/tests/frame/methods/test_to_records.py index d9c999c9119f4..4d40f191a904b 100644 --- a/pandas/tests/frame/methods/test_to_records.py +++ b/pandas/tests/frame/methods/test_to_records.py @@ -131,7 +131,7 @@ def test_to_records_with_categorical(self): [ # No dtypes --> default to array dtypes. ( - dict(), + {}, np.rec.array( [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], dtype=[("index", "<i8"), ("A", "<i8"), ("B", "<f8"), ("C", "O")], @@ -139,7 +139,7 @@ def test_to_records_with_categorical(self): ), # Should have no effect in this case. ( - dict(index=True), + {"index": True}, np.rec.array( [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], dtype=[("index", "<i8"), ("A", "<i8"), ("B", "<f8"), ("C", "O")], @@ -147,7 +147,7 @@ def test_to_records_with_categorical(self): ), # Column dtype applied across the board. Index unaffected. ( - dict(column_dtypes="<U4"), + {"column_dtypes": "<U4"}, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<i8"), ("A", "<U4"), ("B", "<U4"), ("C", "<U4")], @@ -155,7 +155,7 @@ def test_to_records_with_categorical(self): ), # Index dtype applied across the board. Columns unaffected. ( - dict(index_dtypes="<U1"), + {"index_dtypes": "<U1"}, np.rec.array( [("0", 1, 0.2, "a"), ("1", 2, 1.5, "bc")], dtype=[("index", "<U1"), ("A", "<i8"), ("B", "<f8"), ("C", "O")], @@ -163,7 +163,7 @@ def test_to_records_with_categorical(self): ), # Pass in a type instance. ( - dict(column_dtypes=str), + {"column_dtypes": str}, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")], @@ -171,7 +171,7 @@ def test_to_records_with_categorical(self): ), # Pass in a dtype instance. ( - dict(column_dtypes=np.dtype("unicode")), + {"column_dtypes": np.dtype("unicode")}, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<i8"), ("A", "<U"), ("B", "<U"), ("C", "<U")], @@ -179,7 +179,7 @@ def test_to_records_with_categorical(self): ), # Pass in a dictionary (name-only). ( - dict(column_dtypes={"A": np.int8, "B": np.float32, "C": "<U2"}), + {"column_dtypes": {"A": np.int8, "B": np.float32, "C": "<U2"}}, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<i8"), ("A", "i1"), ("B", "<f4"), ("C", "<U2")], @@ -187,7 +187,7 @@ def test_to_records_with_categorical(self): ), # Pass in a dictionary (indices-only). ( - dict(index_dtypes={0: "int16"}), + {"index_dtypes": {0: "int16"}}, np.rec.array( [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], dtype=[("index", "i2"), ("A", "<i8"), ("B", "<f8"), ("C", "O")], @@ -195,7 +195,7 @@ def test_to_records_with_categorical(self): ), # Ignore index mappings if index is not True. ( - dict(index=False, index_dtypes="<U2"), + {"index": False, "index_dtypes": "<U2"}, np.rec.array( [(1, 0.2, "a"), (2, 1.5, "bc")], dtype=[("A", "<i8"), ("B", "<f8"), ("C", "O")], @@ -203,7 +203,7 @@ def test_to_records_with_categorical(self): ), # Non-existent names / indices in mapping should not error. ( - dict(index_dtypes={0: "int16", "not-there": "float32"}), + {"index_dtypes": {0: "int16", "not-there": "float32"}}, np.rec.array( [(0, 1, 0.2, "a"), (1, 2, 1.5, "bc")], dtype=[("index", "i2"), ("A", "<i8"), ("B", "<f8"), ("C", "O")], @@ -211,7 +211,7 @@ def test_to_records_with_categorical(self): ), # Names / indices not in mapping default to array dtype. ( - dict(column_dtypes={"A": np.int8, "B": np.float32}), + {"column_dtypes": {"A": np.int8, "B": np.float32}}, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<i8"), ("A", "i1"), ("B", "<f4"), ("C", "O")], @@ -219,7 +219,7 @@ def test_to_records_with_categorical(self): ), # Names / indices not in dtype mapping default to array dtype. ( - dict(column_dtypes={"A": np.dtype("int8"), "B": np.dtype("float32")}), + {"column_dtypes": {"A": np.dtype("int8"), "B": np.dtype("float32")}}, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<i8"), ("A", "i1"), ("B", "<f4"), ("C", "O")], @@ -227,7 +227,10 @@ def test_to_records_with_categorical(self): ), # Mixture of everything. ( - dict(column_dtypes={"A": np.int8, "B": np.float32}, index_dtypes="<U2"), + { + "column_dtypes": {"A": np.int8, "B": np.float32}, + "index_dtypes": "<U2", + }, np.rec.array( [("0", "1", "0.2", "a"), ("1", "2", "1.5", "bc")], dtype=[("index", "<U2"), ("A", "i1"), ("B", "<f4"), ("C", "O")], @@ -235,24 +238,24 @@ def test_to_records_with_categorical(self): ), # Invalid dype values. ( - dict(index=False, column_dtypes=list()), + {"index": False, "column_dtypes": list()}, (ValueError, "Invalid dtype \\[\\] specified for column A"), ), ( - dict(index=False, column_dtypes={"A": "int32", "B": 5}), + {"index": False, "column_dtypes": {"A": "int32", "B": 5}}, (ValueError, "Invalid dtype 5 specified for column B"), ), # Numpy can't handle EA types, so check error is raised ( - dict( - index=False, - column_dtypes={"A": "int32", "B": CategoricalDtype(["a", "b"])}, - ), + { + "index": False, + "column_dtypes": {"A": "int32", "B": CategoricalDtype(["a", "b"])}, + }, (ValueError, "Invalid dtype category specified for column B"), ), # Check that bad types raise ( - dict(index=False, column_dtypes={"A": "int32", "B": "foo"}), + {"index": False, "column_dtypes": {"A": "int32", "B": "foo"}}, (TypeError, "data type [\"']foo[\"'] not understood"), ), ], @@ -276,7 +279,7 @@ def test_to_records_dtype(self, kwargs, expected): DataFrame( [[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=list("abc") ).set_index(["a", "b"]), - dict(column_dtypes="float64", index_dtypes={0: "int32", 1: "int8"}), + {"column_dtypes": "float64", "index_dtypes": {0: "int32", 1: "int8"}}, np.rec.array( [(1, 2, 3.0), (4, 5, 6.0), (7, 8, 9.0)], dtype=[("a", "<i4"), ("b", "i1"), ("c", "<f8")], @@ -290,7 +293,7 @@ def test_to_records_dtype(self, kwargs, expected): [("a", "d"), ("b", "e"), ("c", "f")] ), ), - dict(column_dtypes={0: "<U1", 2: "float32"}, index_dtypes="float32"), + {"column_dtypes": {0: "<U1", 2: "float32"}, "index_dtypes": "float32"}, np.rec.array( [(0.0, "1", 2, 3.0), (1.0, "4", 5, 6.0), (2.0, "7", 8, 9.0)], dtype=[ @@ -312,7 +315,7 @@ def test_to_records_dtype(self, kwargs, expected): [("d", -4), ("d", -5), ("f", -6)], names=list("cd") ), ), - dict(column_dtypes="float64", index_dtypes={0: "<U2", 1: "int8"}), + {"column_dtypes": "float64", "index_dtypes": {0: "<U2", 1: "int8"}}, np.rec.array( [ ("d", -4, 1.0, 2.0, 3.0), @@ -352,10 +355,10 @@ def keys(self): df = DataFrame({"A": [1, 2], "B": [0.2, 1.5], "C": ["a", "bc"]}) - dtype_mappings = dict( - column_dtypes=DictLike(**{"A": np.int8, "B": np.float32}), - index_dtypes="<U2", - ) + dtype_mappings = { + "column_dtypes": DictLike(**{"A": np.int8, "B": np.float32}), + "index_dtypes": "<U2", + } result = df.to_records(**dtype_mappings) expected = np.rec.array( diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 350b8d01d849a..b422f2daadb78 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -473,7 +473,7 @@ def f(x, y): result = getattr(mixed_float_frame, op)(2 * mixed_float_frame) expected = f(mixed_float_frame, 2 * mixed_float_frame) tm.assert_frame_equal(result, expected) - _check_mixed_float(result, dtype=dict(C=None)) + _check_mixed_float(result, dtype={"C": None}) @pytest.mark.parametrize("op", ["__add__", "__sub__", "__mul__"]) def test_arith_flex_frame_mixed( @@ -488,9 +488,9 @@ def test_arith_flex_frame_mixed( # no overflow in the uint dtype = None if op in ["__sub__"]: - dtype = dict(B="uint64", C=None) + dtype = {"B": "uint64", "C": None} elif op in ["__add__", "__mul__"]: - dtype = dict(C=None) + dtype = {"C": None} tm.assert_frame_equal(result, expected) _check_mixed_int(result, dtype=dtype) @@ -498,7 +498,7 @@ def test_arith_flex_frame_mixed( result = getattr(mixed_float_frame, op)(2 * mixed_float_frame) expected = f(mixed_float_frame, 2 * mixed_float_frame) tm.assert_frame_equal(result, expected) - _check_mixed_float(result, dtype=dict(C=None)) + _check_mixed_float(result, dtype={"C": None}) # vs plain int result = getattr(int_frame, op)(2 * int_frame) @@ -1126,7 +1126,7 @@ def test_combineFrame(self, float_frame, mixed_float_frame, mixed_int_frame): # mix vs mix added = mixed_float_frame + mixed_float_frame - _check_mixed_float(added, dtype=dict(C=None)) + _check_mixed_float(added, dtype={"C": None}) # with int added = float_frame + mixed_int_frame @@ -1160,20 +1160,20 @@ def test_combine_series( # vs mix (upcast) as needed added = mixed_float_frame + series.astype("float32") - _check_mixed_float(added, dtype=dict(C=None)) + _check_mixed_float(added, dtype={"C": None}) added = mixed_float_frame + series.astype("float16") - _check_mixed_float(added, dtype=dict(C=None)) + _check_mixed_float(added, dtype={"C": None}) # FIXME: don't leave commented-out # these raise with numexpr.....as we are adding an int64 to an # uint64....weird vs int # added = mixed_int_frame + (100*series).astype('int64') - # _check_mixed_int(added, dtype = dict(A = 'int64', B = 'float64', C = - # 'int64', D = 'int64')) + # _check_mixed_int(added, dtype = {"A": 'int64', "B": 'float64', "C": + # 'int64', "D": 'int64'}) # added = mixed_int_frame + (100*series).astype('int32') - # _check_mixed_int(added, dtype = dict(A = 'int32', B = 'float64', C = - # 'int32', D = 'int64')) + # _check_mixed_int(added, dtype = {"A": 'int32', "B": 'float64', "C": + # 'int32', "D": 'int64'}) # TimeSeries ts = datetime_frame["A"] @@ -1228,7 +1228,7 @@ def test_combineFunc(self, float_frame, mixed_float_frame): result = mixed_float_frame * 2 for c, s in result.items(): tm.assert_numpy_array_equal(s.values, mixed_float_frame[c].values * 2) - _check_mixed_float(result, dtype=dict(C=None)) + _check_mixed_float(result, dtype={"C": None}) result = DataFrame() * 2 assert result.index.equals(DataFrame().index) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 299f00e818105..1cb4ca9a30511 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -671,14 +671,14 @@ def test_mode_sortwarning(self): def test_operators_timedelta64(self): df = DataFrame( - dict( - A=date_range("2012-1-1", periods=3, freq="D"), - B=date_range("2012-1-2", periods=3, freq="D"), - C=Timestamp("20120101") - timedelta(minutes=5, seconds=5), - ) + { + "A": date_range("2012-1-1", periods=3, freq="D"), + "B": date_range("2012-1-2", periods=3, freq="D"), + "C": Timestamp("20120101") - timedelta(minutes=5, seconds=5), + } ) - diffs = DataFrame(dict(A=df["A"] - df["C"], B=df["A"] - df["B"])) + diffs = DataFrame({"A": df["A"] - df["C"], "B": df["A"] - df["B"]}) # min result = diffs.min() @@ -699,7 +699,7 @@ def test_operators_timedelta64(self): # abs result = diffs.abs() result2 = abs(diffs) - expected = DataFrame(dict(A=df["A"] - df["C"], B=df["B"] - df["A"])) + expected = DataFrame({"A": df["A"] - df["C"], "B": df["B"] - df["A"]}) tm.assert_frame_equal(result, expected) tm.assert_frame_equal(result2, expected) @@ -1241,7 +1241,7 @@ def test_min_max_dt64_api_consistency_with_NaT(self): # returned NaT for series. These tests check that the API is consistent in # min/max calls on empty Series/DataFrames. See GH:33704 for more # information - df = DataFrame(dict(x=pd.to_datetime([]))) + df = DataFrame({"x": pd.to_datetime([])}) expected_dt_series = Series(pd.to_datetime([])) # check axis 0 assert (df.min(axis=0).x is pd.NaT) == (expected_dt_series.min() is pd.NaT) @@ -1254,7 +1254,7 @@ def test_min_max_dt64_api_consistency_with_NaT(self): def test_min_max_dt64_api_consistency_empty_df(self): # check DataFrame/Series api consistency when calling min/max on an empty # DataFrame/Series. - df = DataFrame(dict(x=[])) + df = DataFrame({"x": []}) expected_float_series = Series([], dtype=float) # check axis 0 assert np.isnan(df.min(axis=0).x) == np.isnan(expected_float_series.min())
- [ ] xref #38138 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry identify unnecessary dict call - rewrite as a literal Rewrites as dictionary literals for the following files: modified: pandas/tests/frame/indexing/test_indexing.py modified: pandas/tests/frame/indexing/test_where.py modified: pandas/tests/frame/methods/test_fillna.py modified: pandas/tests/frame/methods/test_sort_values.py modified: pandas/tests/frame/methods/test_to_csv.py modified: pandas/tests/frame/methods/test_to_records.py modified: pandas/tests/frame/test_arithmetic.py modified: pandas/tests/frame/test_reductions.py However, I did not change it to literal in the following two places, as they seem like valid dict call: 1. pandas/tests/frame/indexing/test_indexing.py ``` lambda l: dict(zip(l, range(len(l)))), # line 76 lambda l: dict(zip(l, range(len(l)))).keys(), # line 77 ``` 2. pandas/tests/frame/indexing/test_where.py ``` return DataFrame(dict((c, s + 1) if is_ok(s) else (c, s) for c, s in df.items())) # line 32 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/38207
2020-12-01T08:19:29Z
2020-12-02T03:12:42Z
2020-12-02T03:12:42Z
2020-12-02T03:13:02Z
TST: Added dataframe constructor tests confirming order is preserved with standard Python dicts
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index a98723e9e31f8..2300a8937991e 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1238,32 +1238,34 @@ def test_constructor_single_row(self): ) tm.assert_frame_equal(result, expected) - def test_constructor_ordered_dict_preserve_order(self): + @pytest.mark.parametrize("dict_type", [dict, OrderedDict]) + def test_constructor_ordered_dict_preserve_order(self, dict_type): # see gh-13304 expected = DataFrame([[2, 1]], columns=["b", "a"]) - data = OrderedDict() + data = dict_type() data["b"] = [2] data["a"] = [1] result = DataFrame(data) tm.assert_frame_equal(result, expected) - data = OrderedDict() + data = dict_type() data["b"] = 2 data["a"] = 1 result = DataFrame([data]) tm.assert_frame_equal(result, expected) - def test_constructor_ordered_dict_conflicting_orders(self): + @pytest.mark.parametrize("dict_type", [dict, OrderedDict]) + def test_constructor_ordered_dict_conflicting_orders(self, dict_type): # the first dict element sets the ordering for the DataFrame, # even if there are conflicting orders from subsequent ones - row_one = OrderedDict() + row_one = dict_type() row_one["b"] = 2 row_one["a"] = 1 - row_two = OrderedDict() + row_two = dict_type() row_two["a"] = 1 row_two["b"] = 2
- [ ] closes #38033 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Adds additional test scenarios that confirm dataframes created with standard Python dicts preserve order as expected.
https://api.github.com/repos/pandas-dev/pandas/pulls/38206
2020-12-01T07:21:28Z
2020-12-02T03:04:37Z
2020-12-02T03:04:37Z
2020-12-02T03:04:46Z
Rewrite dict literal for files in tests/groupby & ./pandas/tests/dtypes
diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 27fac95a16b7a..c9ca5cb34d271 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -68,7 +68,7 @@ def coerce(request): ((1,), True, "tuple"), (tuple(), True, "tuple-empty"), ({"a": 1}, True, "dict"), - (dict(), True, "dict-empty"), + ({}, True, "dict-empty"), ({"a", 1}, "set", "set"), (set(), "set", "set-empty"), (frozenset({"a", 1}), "set", "frozenset"), @@ -1489,7 +1489,7 @@ def test_datetimeindex_from_empty_datetime64_array(): def test_nan_to_nat_conversions(): df = DataFrame( - dict({"A": np.asarray(range(10), dtype="float64"), "B": Timestamp("20010101")}) + {"A": np.asarray(range(10), dtype="float64"), "B": Timestamp("20010101")} ) df.iloc[3:6, :] = np.nan result = df.loc[4, "B"] diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index e49e69a39b315..720c7f8c2324d 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -692,14 +692,14 @@ def test_cummin(numpy_dtypes_for_minmax): tm.assert_frame_equal(result, expected) # GH 15561 - df = DataFrame(dict(a=[1], b=pd.to_datetime(["2001"]))) + df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) expected = Series(pd.to_datetime("2001"), index=[0], name="b") result = df.groupby("a")["b"].cummin() tm.assert_series_equal(expected, result) # GH 15635 - df = DataFrame(dict(a=[1, 2, 1], b=[1, 2, 2])) + df = DataFrame({"a": [1, 2, 1], "b": [1, 2, 2]}) result = df.groupby("a").b.cummin() expected = Series([1, 2, 1], name="b") tm.assert_series_equal(result, expected) @@ -748,14 +748,14 @@ def test_cummax(numpy_dtypes_for_minmax): tm.assert_frame_equal(result, expected) # GH 15561 - df = DataFrame(dict(a=[1], b=pd.to_datetime(["2001"]))) + df = DataFrame({"a": [1], "b": pd.to_datetime(["2001"])}) expected = Series(pd.to_datetime("2001"), index=[0], name="b") result = df.groupby("a")["b"].cummax() tm.assert_series_equal(expected, result) # GH 15635 - df = DataFrame(dict(a=[1, 2, 1], b=[2, 1, 1])) + df = DataFrame({"a": [1, 2, 1], "b": [2, 1, 1]}) result = df.groupby("a").b.cummax() expected = Series([2, 1, 2], name="b") tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index b4e023f569844..8acd051fbc643 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -228,7 +228,7 @@ def test_transform_dtype(): def test_transform_bug(): # GH 5712 # transforming on a datetime column - df = DataFrame(dict(A=Timestamp("20130101"), B=np.arange(5))) + df = DataFrame({"A": Timestamp("20130101"), "B": np.arange(5)}) result = df.groupby("A")["B"].transform(lambda x: x.rank(ascending=False)) expected = Series(np.arange(5, 0, step=-1), name="B") tm.assert_series_equal(result, expected) @@ -251,7 +251,7 @@ def test_transform_numeric_to_boolean(): def test_transform_datetime_to_timedelta(): # GH 15429 # transforming a datetime to timedelta - df = DataFrame(dict(A=Timestamp("20130101"), B=np.arange(5))) + df = DataFrame({"A": Timestamp("20130101"), "B": np.arange(5)}) expected = Series([Timestamp("20130101") - Timestamp("20130101")] * 5, name="A") # this does date math without changing result type in transform @@ -442,7 +442,7 @@ def test_transform_coercion(): # 14457 # when we are transforming be sure to not coerce # via assignment - df = DataFrame(dict(A=["a", "a"], B=[0, 1])) + df = DataFrame({"A": ["a", "a"], "B": [0, 1]}) g = df.groupby("A") expected = g.transform(np.mean) @@ -456,30 +456,37 @@ def test_groupby_transform_with_int(): # floats df = DataFrame( - dict( - A=[1, 1, 1, 2, 2, 2], - B=Series(1, dtype="float64"), - C=Series([1, 2, 3, 1, 2, 3], dtype="float64"), - D="foo", - ) + { + "A": [1, 1, 1, 2, 2, 2], + "B": Series(1, dtype="float64"), + "C": Series([1, 2, 3, 1, 2, 3], dtype="float64"), + "D": "foo", + } ) with np.errstate(all="ignore"): result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) expected = DataFrame( - dict(B=np.nan, C=Series([-1, 0, 1, -1, 0, 1], dtype="float64")) + {"B": np.nan, "C": Series([-1, 0, 1, -1, 0, 1], dtype="float64")} ) tm.assert_frame_equal(result, expected) # int case - df = DataFrame(dict(A=[1, 1, 1, 2, 2, 2], B=1, C=[1, 2, 3, 1, 2, 3], D="foo")) + df = DataFrame( + { + "A": [1, 1, 1, 2, 2, 2], + "B": 1, + "C": [1, 2, 3, 1, 2, 3], + "D": "foo", + } + ) with np.errstate(all="ignore"): result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) - expected = DataFrame(dict(B=np.nan, C=[-1, 0, 1, -1, 0, 1])) + expected = DataFrame({"B": np.nan, "C": [-1, 0, 1, -1, 0, 1]}) tm.assert_frame_equal(result, expected) # int that needs float conversion s = Series([2, 3, 4, 10, 5, -1]) - df = DataFrame(dict(A=[1, 1, 1, 2, 2, 2], B=1, C=s, D="foo")) + df = DataFrame({"A": [1, 1, 1, 2, 2, 2], "B": 1, "C": s, "D": "foo"}) with np.errstate(all="ignore"): result = df.groupby("A").transform(lambda x: (x - x.mean()) / x.std()) @@ -487,12 +494,12 @@ def test_groupby_transform_with_int(): s1 = (s1 - s1.mean()) / s1.std() s2 = s.iloc[3:6] s2 = (s2 - s2.mean()) / s2.std() - expected = DataFrame(dict(B=np.nan, C=concat([s1, s2]))) + expected = DataFrame({"B": np.nan, "C": concat([s1, s2])}) tm.assert_frame_equal(result, expected) # int downcasting result = df.groupby("A").transform(lambda x: x * 2 / 2) - expected = DataFrame(dict(B=1, C=[2, 3, 4, 10, 5, -1])) + expected = DataFrame({"B": 1, "C": [2, 3, 4, 10, 5, -1]}) tm.assert_frame_equal(result, expected) @@ -659,11 +666,11 @@ def test_cython_transform_frame(op, args, targop): # group by values, index level, columns for df in [df, df2]: for gb_target in [ - dict(by=labels), - dict(level=0), - dict(by="string"), - ]: # dict(by='string_missing')]: - # dict(by=['int','string'])]: + {"by": labels}, + {"level": 0}, + {"by": "string"}, + ]: # {"by": 'string_missing'}]: + # {"by": ['int','string']}]: gb = df.groupby(**gb_target) # allowlisted methods set the selection before applying @@ -986,7 +993,7 @@ def test_transform_absent_categories(func): x_vals = [1] x_cats = range(2) y = [1] - df = DataFrame(dict(x=Categorical(x_vals, x_cats), y=y)) + df = DataFrame({"x": Categorical(x_vals, x_cats), "y": y}) result = getattr(df.y.groupby(df.x), func)() expected = df.y tm.assert_series_equal(result, expected) @@ -1005,7 +1012,7 @@ def test_ffill_not_in_axis(func, key, val): def test_transform_invalid_name_raises(): # GH#27486 - df = DataFrame(dict(a=[0, 1, 1, 2])) + df = DataFrame({"a": [0, 1, 1, 2]}) g = df.groupby(["a", "b", "b", "c"]) with pytest.raises(ValueError, match="not a valid function name"): g.transform("some_arbitrary_name") @@ -1025,7 +1032,8 @@ def test_transform_invalid_name_raises(): "obj", [ DataFrame( - dict(a=[0, 0, 0, 1, 1, 1], b=range(6)), index=["A", "B", "C", "D", "E", "F"] + {"a": [0, 0, 0, 1, 1, 1], "b": range(6)}, + index=["A", "B", "C", "D", "E", "F"], ), Series([0, 0, 0, 1, 1, 1], index=["A", "B", "C", "D", "E", "F"]), ],
- [ ] xref #38138 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry identify unnecessary dict call - rewrite as a literal Rewrites as dictionary literals for the following files: ./pandas/tests/dtypes/test_inference.py ./pandas/tests/groupby/test_function.py ./pandas/tests/groupby/transform/test_transform.py
https://api.github.com/repos/pandas-dev/pandas/pulls/38205
2020-12-01T06:30:45Z
2020-12-02T03:14:16Z
2020-12-02T03:14:16Z
2020-12-02T03:14:16Z
Retain views with listlike indexers setitem
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 74e0a3a434cde..4fd91c8aafe4b 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -358,6 +358,14 @@ def time_assign_with_setitem(self): for i in range(100): self.df[i] = np.random.randn(self.N) + def time_assign_list_like_with_setitem(self): + np.random.seed(1234) + self.df[list(range(100))] = np.random.randn(self.N, 100) + + def time_assign_list_of_columns_concat(self): + df = DataFrame(np.random.randn(self.N, 100)) + concat([self.df, df], axis=1) + class ChainIndexing: diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 24db70481c136..270de56a000a0 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -548,6 +548,7 @@ Performance improvements - Performance improvement in :meth:`Series.astype` and :meth:`DataFrame.astype` for :class:`Categorical` (:issue:`8628`) - Performance improvement in :meth:`DataFrame.groupby` for ``float`` ``dtype`` (:issue:`28303`), changes of the underlying hash-function can lead to changes in float based indexes sort ordering for ties (e.g. :meth:`Index.value_counts`) - Performance improvement in :meth:`pd.isin` for inputs with more than 1e6 elements (:issue:`36611`) +- Performance improvement for :meth:`DataFrame.__setitem__` with list-like indexers (:issue:`37954`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index f6cf691ea911c..e7cf8cae28b88 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -672,17 +672,12 @@ def _ensure_listlike_indexer(self, key, axis=None, value=None): and not com.is_bool_indexer(key) and all(is_hashable(k) for k in key) ): - for i, k in enumerate(key): - if k not in self.obj: - if value is None: - self.obj[k] = np.nan - elif is_array_like(value) and value.ndim == 2: - # GH#37964 have to select columnwise in case of array - self.obj[k] = value[:, i] - elif is_list_like(value): - self.obj[k] = value[i] - else: - self.obj[k] = value + # GH#38148 + keys = self.obj.columns.union(key, sort=False) + + self.obj._mgr = self.obj._mgr.reindex_axis( + keys, axis=0, copy=False, consolidate=False, only_slice=True + ) def __setitem__(self, key, value): if isinstance(key, tuple): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 168dba25ba29c..93ab207d8ce12 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1236,6 +1236,8 @@ def reindex_axis( limit=None, fill_value=None, copy: bool = True, + consolidate: bool = True, + only_slice: bool = False, ): """ Conform block manager to new index. @@ -1246,7 +1248,13 @@ def reindex_axis( ) return self.reindex_indexer( - new_index, indexer, axis=axis, fill_value=fill_value, copy=copy + new_index, + indexer, + axis=axis, + fill_value=fill_value, + copy=copy, + consolidate=consolidate, + only_slice=only_slice, ) def reindex_indexer( @@ -1258,6 +1266,7 @@ def reindex_indexer( allow_dups: bool = False, copy: bool = True, consolidate: bool = True, + only_slice: bool = False, ) -> T: """ Parameters @@ -1270,6 +1279,8 @@ def reindex_indexer( copy : bool, default True consolidate: bool, default True Whether to consolidate inplace before reindexing. + only_slice : bool, default False + Whether to take views, not copies, along columns. pandas-indexer with -1's only. """ @@ -1293,7 +1304,9 @@ def reindex_indexer( raise IndexError("Requested axis not found in manager") if axis == 0: - new_blocks = self._slice_take_blocks_ax0(indexer, fill_value=fill_value) + new_blocks = self._slice_take_blocks_ax0( + indexer, fill_value=fill_value, only_slice=only_slice + ) else: new_blocks = [ blk.take_nd( diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index e4a66ea9133dd..884cb6c20b77e 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -319,6 +319,24 @@ def test_setitem_bool_with_numeric_index(self, dtype): tm.assert_index_equal(df.columns, expected_cols) +class TestDataFrameSetItemWithExpansion: + def test_setitem_listlike_views(self): + # GH#38148 + df = DataFrame({"a": [1, 2, 3], "b": [4, 4, 6]}) + + # get one column as a view of df + ser = df["a"] + + # add columns with list-like indexer + df[["c", "d"]] = np.array([[0.1, 0.2], [0.3, 0.4], [0.4, 0.5]]) + + # edit in place the first column to check view semantics + df.iloc[0, 0] = 100 + + expected = Series([100, 2, 3], name="a") + tm.assert_series_equal(ser, expected) + + class TestDataFrameSetItemSlicing: def test_setitem_slice_position(self): # GH#31469
- [x] closes #37954 xref #38148
https://api.github.com/repos/pandas-dev/pandas/pulls/38204
2020-12-01T05:03:22Z
2020-12-02T12:10:26Z
2020-12-02T12:10:26Z
2020-12-02T14:47:06Z
Rewrite dict literal for files in ./pandas/tests/tools/ and ./pandas/tests/resample/
diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 7e1d7fb17c8ed..fe3ca0d0937b3 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -645,7 +645,7 @@ def test_s3_roundtrip_explicit_fs(self, df_compat, s3_resource, pa, s3so): if LooseVersion(pyarrow.__version__) <= LooseVersion("0.17.0"): pytest.skip() s3 = s3fs.S3FileSystem(**s3so) - kw = dict(filesystem=s3) + kw = {"filesystem": s3} check_round_trip( df_compat, pa, @@ -658,7 +658,7 @@ def test_s3_roundtrip(self, df_compat, s3_resource, pa, s3so): if LooseVersion(pyarrow.__version__) <= LooseVersion("0.17.0"): pytest.skip() # GH #19134 - s3so = dict(storage_options=s3so) + s3so = {"storage_options": s3so} check_round_trip( df_compat, pa, @@ -710,10 +710,12 @@ def test_s3_roundtrip_for_dir( pa, expected=expected_df, path="s3://pandas-test/parquet_dir", - read_kwargs=dict(storage_options=s3so), - write_kwargs=dict( - partition_cols=partition_col, compression=None, storage_options=s3so - ), + read_kwargs={"storage_options": s3so}, + write_kwargs={ + "partition_cols": partition_col, + "compression": None, + "storage_options": s3so, + }, check_like=True, repeat=1, ) @@ -946,8 +948,8 @@ def test_s3_roundtrip(self, df_compat, s3_resource, fp, s3so): df_compat, fp, path="s3://pandas-test/fastparquet.parquet", - read_kwargs=dict(storage_options=s3so), - write_kwargs=dict(compression=None, storage_options=s3so), + read_kwargs={"storage_options": s3so}, + write_kwargs={"compression": None, "storage_options": s3so}, ) def test_partition_cols_supported(self, fp, df_full): diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 50e7cf9bd8eda..c12111e20a4b1 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -158,12 +158,12 @@ def test_aggregate_normal(resample_method): @pytest.mark.parametrize( "method, method_args, unit", [ - ("sum", dict(), 0), - ("sum", dict(min_count=0), 0), - ("sum", dict(min_count=1), np.nan), - ("prod", dict(), 1), - ("prod", dict(min_count=0), 1), - ("prod", dict(min_count=1), np.nan), + ("sum", {}, 0), + ("sum", {"min_count": 0}, 0), + ("sum", {"min_count": 1}, np.nan), + ("prod", {}, 1), + ("prod", {"min_count": 0}, 1), + ("prod", {"min_count": 1}, np.nan), ], ) def test_resample_entirely_nat_window(method, method_args, unit): @@ -267,14 +267,14 @@ def test_repr(): @pytest.mark.parametrize( "method, method_args, expected_values", [ - ("sum", dict(), [1, 0, 1]), - ("sum", dict(min_count=0), [1, 0, 1]), - ("sum", dict(min_count=1), [1, np.nan, 1]), - ("sum", dict(min_count=2), [np.nan, np.nan, np.nan]), - ("prod", dict(), [1, 1, 1]), - ("prod", dict(min_count=0), [1, 1, 1]), - ("prod", dict(min_count=1), [1, np.nan, 1]), - ("prod", dict(min_count=2), [np.nan, np.nan, np.nan]), + ("sum", {}, [1, 0, 1]), + ("sum", {"min_count": 0}, [1, 0, 1]), + ("sum", {"min_count": 1}, [1, np.nan, 1]), + ("sum", {"min_count": 2}, [np.nan, np.nan, np.nan]), + ("prod", {}, [1, 1, 1]), + ("prod", {"min_count": 0}, [1, 1, 1]), + ("prod", {"min_count": 1}, [1, np.nan, 1]), + ("prod", {"min_count": 2}, [np.nan, np.nan, np.nan]), ], ) def test_upsample_sum(method, method_args, expected_values): diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py index 713607d087bc0..f89958f7723ef 100644 --- a/pandas/tests/tools/test_to_numeric.py +++ b/pandas/tests/tools/test_to_numeric.py @@ -48,8 +48,8 @@ def transform_assert_equal(request): @pytest.mark.parametrize( "input_kwargs,result_kwargs", [ - (dict(), dict(dtype=np.int64)), - (dict(errors="coerce", downcast="integer"), dict(dtype=np.int8)), + ({}, {"dtype": np.int64}), + ({"errors": "coerce", "downcast": "integer"}, {"dtype": np.int8}), ], ) def test_empty(input_kwargs, result_kwargs): @@ -147,10 +147,10 @@ def test_list(): @pytest.mark.parametrize( "data,arr_kwargs", [ - ([1, 3, 4, 5], dict(dtype=np.int64)), - ([1.0, 3.0, 4.0, 5.0], dict()), + ([1, 3, 4, 5], {"dtype": np.int64}), + ([1.0, 3.0, 4.0, 5.0], {}), # Boolean is regarded as numeric. - ([True, False, True, True], dict()), + ([True, False, True, True], {}), ], ) def test_list_numeric(data, arr_kwargs): @@ -159,7 +159,7 @@ def test_list_numeric(data, arr_kwargs): tm.assert_numpy_array_equal(result, expected) -@pytest.mark.parametrize("kwargs", [dict(dtype="O"), dict()]) +@pytest.mark.parametrize("kwargs", [{"dtype": "O"}, {}]) def test_numeric(kwargs): data = [1, -3.14, 7] @@ -182,13 +182,13 @@ def test_numeric(kwargs): def test_numeric_df_columns(columns): # see gh-14827 df = DataFrame( - dict( - a=[1.2, decimal.Decimal(3.14), decimal.Decimal("infinity"), "0.1"], - b=[1.0, 2.0, 3.0, 4.0], - ) + { + "a": [1.2, decimal.Decimal(3.14), decimal.Decimal("infinity"), "0.1"], + "b": [1.0, 2.0, 3.0, 4.0], + } ) - expected = DataFrame(dict(a=[1.2, 3.14, np.inf, 0.1], b=[1.0, 2.0, 3.0, 4.0])) + expected = DataFrame({"a": [1.2, 3.14, np.inf, 0.1], "b": [1.0, 2.0, 3.0, 4.0]}) df_copy = df.copy() df_copy[columns] = df_copy[columns].apply(to_numeric) @@ -208,10 +208,10 @@ def test_numeric_df_columns(columns): ) def test_numeric_embedded_arr_likes(data, exp_data): # Test to_numeric with embedded lists and arrays - df = DataFrame(dict(a=data)) + df = DataFrame({"a": data}) df["a"] = df["a"].apply(to_numeric) - expected = DataFrame(dict(a=exp_data)) + expected = DataFrame({"a": exp_data}) tm.assert_frame_equal(df, expected) @@ -226,7 +226,7 @@ def test_all_nan(): def test_type_check(errors): # see gh-11776 df = DataFrame({"a": [1, -3.14, 7], "b": ["4", "5", "6"]}) - kwargs = dict(errors=errors) if errors is not None else dict() + kwargs = {"errors": errors} if errors is not None else {} error_ctx = pytest.raises(TypeError, match="1-d array") with error_ctx: @@ -241,7 +241,7 @@ def test_scalar(val, signed, transform): def test_really_large_scalar(large_val, signed, transform, errors): # see gh-24910 - kwargs = dict(errors=errors) if errors is not None else dict() + kwargs = {"errors": errors} if errors is not None else {} val = -large_val if signed else large_val val = transform(val) @@ -258,7 +258,7 @@ def test_really_large_scalar(large_val, signed, transform, errors): def test_really_large_in_arr(large_val, signed, transform, multiple_elts, errors): # see gh-24910 - kwargs = dict(errors=errors) if errors is not None else dict() + kwargs = {"errors": errors} if errors is not None else {} val = -large_val if signed else large_val val = transform(val) @@ -300,7 +300,7 @@ def test_really_large_in_arr_consistent(large_val, signed, multiple_elts, errors # # Even if we discover that we have to hold float, does not mean # we should be lenient on subsequent elements that fail to be integer. - kwargs = dict(errors=errors) if errors is not None else dict() + kwargs = {"errors": errors} if errors is not None else {} arr = [str(-large_val if signed else large_val)] if multiple_elts: @@ -452,12 +452,12 @@ def test_errors_invalid_value(): "kwargs,exp_dtype", [ # Basic function tests. - (dict(), np.int64), - (dict(downcast=None), np.int64), + ({}, np.int64), + ({"downcast": None}, np.int64), # Support below np.float32 is rare and far between. - (dict(downcast="float"), np.dtype(np.float32).char), + ({"downcast": "float"}, np.dtype(np.float32).char), # Basic dtype support. - (dict(downcast="unsigned"), np.dtype(np.typecodes["UnsignedInteger"][0])), + ({"downcast": "unsigned"}, np.dtype(np.typecodes["UnsignedInteger"][0])), ], ) def test_downcast_basic(data, kwargs, exp_dtype): diff --git a/pandas/tests/util/test_assert_extension_array_equal.py b/pandas/tests/util/test_assert_extension_array_equal.py index f9259beab5d13..545f0dcbf695f 100644 --- a/pandas/tests/util/test_assert_extension_array_equal.py +++ b/pandas/tests/util/test_assert_extension_array_equal.py @@ -9,9 +9,9 @@ @pytest.mark.parametrize( "kwargs", [ - dict(), # Default is check_exact=False - dict(check_exact=False), - dict(check_exact=True), + {}, # Default is check_exact=False + {"check_exact": False}, + {"check_exact": True}, ], ) def test_assert_extension_array_equal_not_exact(kwargs): @@ -55,7 +55,7 @@ def test_assert_extension_array_equal_less_precise(decimals): def test_assert_extension_array_equal_dtype_mismatch(check_dtype): end = 5 - kwargs = dict(check_dtype=check_dtype) + kwargs = {"check_dtype": check_dtype} arr1 = SparseArray(np.arange(end, dtype="int64")) arr2 = SparseArray(np.arange(end, dtype="int32")) diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index 21d5a456e20d0..988a0e7b24379 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -85,7 +85,7 @@ def test_index_equal_values_close(check_exact): def test_index_equal_values_less_close(check_exact, rtol): idx1 = Index([1, 2, 3.0]) idx2 = Index([1, 2, 3.0001]) - kwargs = dict(check_exact=check_exact, rtol=rtol) + kwargs = {"check_exact": check_exact, "rtol": rtol} if check_exact or rtol < 0.5e-3: msg = """Index are different @@ -103,7 +103,7 @@ def test_index_equal_values_less_close(check_exact, rtol): def test_index_equal_values_too_far(check_exact, rtol): idx1 = Index([1, 2, 3]) idx2 = Index([1, 2, 4]) - kwargs = dict(check_exact=check_exact, rtol=rtol) + kwargs = {"check_exact": check_exact, "rtol": rtol} msg = """Index are different @@ -140,7 +140,7 @@ def test_index_equal_value_oder_mismatch(check_exact, rtol, check_order): def test_index_equal_level_values_mismatch(check_exact, rtol): idx1 = MultiIndex.from_tuples([("A", 2), ("A", 2), ("B", 3), ("B", 4)]) idx2 = MultiIndex.from_tuples([("A", 1), ("A", 2), ("B", 3), ("B", 4)]) - kwargs = dict(check_exact=check_exact, rtol=rtol) + kwargs = {"check_exact": check_exact, "rtol": rtol} msg = """MultiIndex level \\[1\\] are different diff --git a/pandas/tests/util/test_assert_interval_array_equal.py b/pandas/tests/util/test_assert_interval_array_equal.py index 2e8699536c72a..8cc4ade3d7e95 100644 --- a/pandas/tests/util/test_assert_interval_array_equal.py +++ b/pandas/tests/util/test_assert_interval_array_equal.py @@ -7,9 +7,9 @@ @pytest.mark.parametrize( "kwargs", [ - dict(start=0, periods=4), - dict(start=1, periods=5), - dict(start=5, end=10, closed="left"), + {"start": 0, "periods": 4}, + {"start": 1, "periods": 5}, + {"start": 5, "end": 10, "closed": "left"}, ], ) def test_interval_array_equal(kwargs): @@ -18,7 +18,7 @@ def test_interval_array_equal(kwargs): def test_interval_array_equal_closed_mismatch(): - kwargs = dict(start=0, periods=5) + kwargs = {"start": 0, "periods": 5} arr1 = interval_range(closed="left", **kwargs).values arr2 = interval_range(closed="right", **kwargs).values @@ -34,7 +34,7 @@ def test_interval_array_equal_closed_mismatch(): def test_interval_array_equal_periods_mismatch(): - kwargs = dict(start=0) + kwargs = {"start": 0} arr1 = interval_range(periods=5, **kwargs).values arr2 = interval_range(periods=6, **kwargs).values @@ -50,7 +50,7 @@ def test_interval_array_equal_periods_mismatch(): def test_interval_array_equal_end_mismatch(): - kwargs = dict(start=0, periods=5) + kwargs = {"start": 0, "periods": 5} arr1 = interval_range(end=10, **kwargs).values arr2 = interval_range(end=20, **kwargs).values @@ -66,7 +66,7 @@ def test_interval_array_equal_end_mismatch(): def test_interval_array_equal_start_mismatch(): - kwargs = dict(periods=4) + kwargs = {"periods": 4} arr1 = interval_range(start=0, **kwargs).values arr2 = interval_range(start=1, **kwargs).values diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py index 0f56fb0b93642..ae4523014b01d 100644 --- a/pandas/tests/util/test_assert_series_equal.py +++ b/pandas/tests/util/test_assert_series_equal.py @@ -87,9 +87,9 @@ def test_series_not_equal_value_mismatch(data1, data2): @pytest.mark.parametrize( "kwargs", [ - dict(dtype="float64"), # dtype mismatch - dict(index=[1, 2, 4]), # index mismatch - dict(name="foo"), # name mismatch + {"dtype": "float64"}, # dtype mismatch + {"index": [1, 2, 4]}, # index mismatch + {"name": "foo"}, # name mismatch ], ) def test_series_not_equal_metadata_mismatch(kwargs): @@ -140,7 +140,7 @@ def test_less_precise(data1, data2, dtype, decimals): ], ) def test_series_equal_index_dtype(s1, s2, msg, check_index_type): - kwargs = dict(check_index_type=check_index_type) + kwargs = {"check_index_type": check_index_type} if check_index_type: with pytest.raises(AssertionError, match=msg):
- [ ] xref #38138 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Rewrote dict literal for the following files: ./pandas/tests/tools/test_to_numeric.py ./pandas/tests/resample/test_time_grouper.py ./pandas/tests/util/test_assert_series_equal.py ./pandas/tests/util/test_assert_interval_array_equal.py ./pandas/tests/util/test_assert_index_equal.py ./pandas/tests/util/test_assert_extension_array_equal.py ./pandas/tests/io/test_parquet.py
https://api.github.com/repos/pandas-dev/pandas/pulls/38203
2020-12-01T04:53:03Z
2020-12-02T03:14:55Z
2020-12-02T03:14:55Z
2020-12-02T03:15:00Z
PERF: fix assert_frame_equal can be very slow
diff --git a/pandas/_testing.py b/pandas/_testing.py index 7786eeeb46797..f96645b3805f0 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -1294,6 +1294,8 @@ def assert_series_equal( rtol=1.0e-5, atol=1.0e-8, obj="Series", + *, + check_index=True, ): """ Check that left and right Series are equal. @@ -1353,6 +1355,10 @@ def assert_series_equal( obj : str, default 'Series' Specify object name being compared, internally used to show appropriate assertion message. + check_index : bool, default True + Whether to check index equivalence. If False, then compare only values. + + .. versionadded:: 1.3.0 Examples -------- @@ -1388,18 +1394,20 @@ def assert_series_equal( if check_flags: assert left.flags == right.flags, f"{repr(left.flags)} != {repr(right.flags)}" - # index comparison - assert_index_equal( - left.index, - right.index, - exact=check_index_type, - check_names=check_names, - check_exact=check_exact, - check_categorical=check_categorical, - rtol=rtol, - atol=atol, - obj=f"{obj}.index", - ) + if check_index: + # GH #38183 + assert_index_equal( + left.index, + right.index, + exact=check_index_type, + check_names=check_names, + check_exact=check_exact, + check_categorical=check_categorical, + rtol=rtol, + atol=atol, + obj=f"{obj}.index", + ) + if check_freq and isinstance(left.index, (pd.DatetimeIndex, pd.TimedeltaIndex)): lidx = left.index ridx = right.index @@ -1704,6 +1712,10 @@ def assert_frame_equal( assert col in right lcol = left.iloc[:, i] rcol = right.iloc[:, i] + # GH #38183 + # use check_index=False, because we do not want to run + # assert_index_equal for each column, + # as we already checked it for the whole dataframe before. assert_series_equal( lcol, rcol, @@ -1717,6 +1729,7 @@ def assert_frame_equal( obj=f'{obj}.iloc[:, {i}] (column name="{col}")', rtol=rtol, atol=atol, + check_index=False, )
- [ ] closes #38183 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Add kwarg ``check_index`` into ``assert_series_equal`` to allow elimination of multiple index checking (for each column) in ``assert_frame_equal``. Performance wise. ``` import pandas as pd import numpy as np from string import ascii_letters idx = np.random.choice(np.array(list(ascii_letters)), size=10000).astype(object) a = np.random.random_integers(0, 100, (10000, 1000)) %time pd.testing.assert_frame_equal(pd.DataFrame(a), pd.DataFrame(a.copy())) Wall time: 319 ms %time pd.testing.assert_index_equal(pd.Index(idx), pd.Index(idx.copy())) Wall time: 993 µs %time pd.testing.assert_frame_equal(pd.DataFrame(a, index=idx), pd.DataFrame(a, index=idx)) Wall time: 281 ms ```
https://api.github.com/repos/pandas-dev/pandas/pulls/38202
2020-12-01T04:23:13Z
2020-12-24T20:40:41Z
2020-12-24T20:40:41Z
2020-12-24T20:40:45Z
TYP: @final in groupby
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 7dc0db35bf8fe..99426c55da29b 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -6,6 +6,8 @@ import collections from typing import List +from pandas._typing import final + from pandas.core.dtypes.common import is_list_like, is_scalar from pandas.core.base import PandasObject @@ -16,6 +18,7 @@ class ShallowMixin(PandasObject): _attributes: List[str] = [] + @final def _shallow_copy(self, obj, **kwargs): """ return a new object with the replacement attributes @@ -35,6 +38,7 @@ class GotItemMixin(PandasObject): _attributes: List[str] + @final def _gotitem(self, key, ndim, subset=None): """ Sub-classes to define. Return a sliced object. diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 8f1b99e929f59..23f0e178130be 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -11,6 +11,7 @@ class providing the base-class of operations. import datetime from functools import partial, wraps import inspect +from textwrap import dedent import types from typing import ( Callable, @@ -44,6 +45,7 @@ class providing the base-class of operations. IndexLabel, Label, Scalar, + final, ) from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError @@ -447,6 +449,7 @@ class providing the base-class of operations. """ +@final class GroupByPlot(PandasObject): """ Class implementing the .plot attribute for groupby objects. @@ -570,9 +573,11 @@ def __init__( self.grouper = grouper self.exclusions = exclusions or set() + @final def __len__(self) -> int: return len(self.groups) + @final def __repr__(self) -> str: # TODO: Better repr for GroupBy object return object.__repr__(self) @@ -584,6 +589,7 @@ def _assure_grouper(self) -> None: """ pass + @final @property def groups(self) -> Dict[Hashable, np.ndarray]: """ @@ -592,11 +598,13 @@ def groups(self) -> Dict[Hashable, np.ndarray]: self._assure_grouper() return self.grouper.groups + @final @property def ngroups(self) -> int: self._assure_grouper() return self.grouper.ngroups + @final @property def indices(self): """ @@ -605,6 +613,7 @@ def indices(self): self._assure_grouper() return self.grouper.indices + @final def _get_indices(self, names): """ Safe get multiple indices, translate keys for @@ -655,12 +664,14 @@ def get_converter(s): return [self.indices.get(name, []) for name in names] + @final def _get_index(self, name): """ Safe get index, translate keys for datelike to underlying repr. """ return self._get_indices([name])[0] + @final @cache_readonly def _selected_obj(self): # Note: _selected_obj is always just `self.obj` for SeriesGroupBy @@ -672,6 +683,7 @@ def _selected_obj(self): else: return self.obj[self._selection] + @final def _reset_group_selection(self) -> None: """ Clear group based selection. @@ -684,6 +696,7 @@ def _reset_group_selection(self) -> None: self._group_selection = None self._reset_cache("_selected_obj") + @final def _set_group_selection(self) -> None: """ Create group based selection. @@ -709,6 +722,7 @@ def _set_group_selection(self) -> None: self._group_selection = ax.difference(Index(groupers), sort=False).tolist() self._reset_cache("_selected_obj") + @final def _set_result_index_ordered( self, result: "OutputFrameOrSeries" ) -> "OutputFrameOrSeries": @@ -725,6 +739,7 @@ def _set_result_index_ordered( result.set_axis(self.obj._get_axis(self.axis), axis=self.axis, inplace=True) return result + @final def _dir_additions(self) -> Set[str]: return self.obj._dir_additions() | self._apply_allowlist @@ -740,23 +755,25 @@ def __getattr__(self, attr: str): @Substitution( klass="GroupBy", - examples="""\ ->>> df = pd.DataFrame({'A': 'a b a b'.split(), 'B': [1, 2, 3, 4]}) ->>> df - A B -0 a 1 -1 b 2 -2 a 3 -3 b 4 - -To get the difference between each groups maximum and minimum value in one -pass, you can do - ->>> df.groupby('A').pipe(lambda x: x.max() - x.min()) - B -A -a 2 -b 2""", + examples=dedent( + """\ + >>> df = pd.DataFrame({'A': 'a b a b'.split(), 'B': [1, 2, 3, 4]}) + >>> df + A B + 0 a 1 + 1 b 2 + 2 a 3 + 3 b 4 + + To get the difference between each groups maximum and minimum value in one + pass, you can do + + >>> df.groupby('A').pipe(lambda x: x.max() - x.min()) + B + A + a 2 + b 2""" + ), ) @Appender(_pipe_template) def pipe(self, func, *args, **kwargs): @@ -764,6 +781,7 @@ def pipe(self, func, *args, **kwargs): plot = property(GroupByPlot) + @final def _make_wrapper(self, name: str) -> Callable: assert name in self._apply_allowlist @@ -801,6 +819,7 @@ def curried(x): wrapper.__name__ = name return wrapper + @final def get_group(self, name, obj=None): """ Construct DataFrame from group with provided name. @@ -887,6 +906,7 @@ def f(g): return result + @final def _python_apply_general( self, f: F, data: FrameOrSeriesUnion ) -> FrameOrSeriesUnion: @@ -917,6 +937,7 @@ def _iterate_slices(self) -> Iterable[Series]: def transform(self, func, *args, **kwargs): raise AbstractMethodError(self) + @final def _cumcount_array(self, ascending: bool = True): """ Parameters @@ -949,6 +970,7 @@ def _cumcount_array(self, ascending: bool = True): rev[sorter] = np.arange(count, dtype=np.intp) return out[rev].astype(np.int64, copy=False) + @final def _cython_transform( self, how: str, numeric_only: bool = True, axis: int = 0, **kwargs ): @@ -986,6 +1008,7 @@ def _wrap_transformed_output(self, output: Mapping[base.OutputKey, np.ndarray]): def _wrap_applied_output(self, keys, values, not_indexed_same: bool = False): raise AbstractMethodError(self) + @final def _agg_general( self, numeric_only: bool = True, @@ -1059,6 +1082,7 @@ def _cython_agg_general( return self._wrap_aggregated_output(output, index=self.grouper.result_index) + @final def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): """ Perform groupby transform routine with the numba engine. @@ -1093,6 +1117,7 @@ def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs) # evaluated the data sorted by group return result.take(np.argsort(sorted_index), axis=0) + @final def _aggregate_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): """ Perform groupby aggregation routine with the numba engine. @@ -1129,6 +1154,7 @@ def _aggregate_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs) index = Index(group_keys, name=self.grouper.names[0]) return result, index + @final def _python_agg_general(self, func, *args, **kwargs): func = self._is_builtin_func(func) f = lambda x: func(x, *args, **kwargs) @@ -1171,6 +1197,7 @@ def _python_agg_general(self, func, *args, **kwargs): return self._wrap_aggregated_output(output, index=self.grouper.result_index) + @final def _concat_objects(self, keys, values, not_indexed_same: bool = False): from pandas.core.reshape.concat import concat @@ -1232,6 +1259,7 @@ def reset_identity(values): return result + @final def _apply_filter(self, indices, dropna): if len(indices) == 0: indices = np.array([], dtype="int64") @@ -1321,6 +1349,7 @@ class GroupBy(BaseGroupBy[FrameOrSeries]): more """ + @final @property def _obj_1d_constructor(self) -> Type["Series"]: # GH28330 preserve subclassed Series/DataFrames @@ -1329,6 +1358,7 @@ def _obj_1d_constructor(self) -> Type["Series"]: assert isinstance(self.obj, Series) return self.obj._constructor + @final def _bool_agg(self, val_test, skipna): """ Shared func to call any / all Cython GroupBy implementations. @@ -1358,6 +1388,7 @@ def result_to_bool(result: np.ndarray, inference: Type) -> np.ndarray: skipna=skipna, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def any(self, skipna: bool = True): @@ -1377,6 +1408,7 @@ def any(self, skipna: bool = True): """ return self._bool_agg("any", skipna) + @final @Substitution(name="groupby") @Appender(_common_see_also) def all(self, skipna: bool = True): @@ -1410,6 +1442,7 @@ def count(self): # defined here for API doc raise NotImplementedError + @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def mean(self, numeric_only: bool = True): @@ -1466,6 +1499,7 @@ def mean(self, numeric_only: bool = True): numeric_only=numeric_only, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def median(self, numeric_only=True): @@ -1491,6 +1525,7 @@ def median(self, numeric_only=True): numeric_only=numeric_only, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def std(self, ddof: int = 1): @@ -1520,6 +1555,7 @@ def std(self, ddof: int = 1): ddof=ddof, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def var(self, ddof: int = 1): @@ -1547,6 +1583,7 @@ def var(self, ddof: int = 1): with group_selection_context(self): return self._python_agg_general(func) + @final @Substitution(name="groupby") @Appender(_common_see_also) def sem(self, ddof: int = 1): @@ -1577,6 +1614,7 @@ def sem(self, ddof: int = 1): ) return result + @final @Substitution(name="groupby") @Appender(_common_see_also) def size(self) -> FrameOrSeriesUnion: @@ -1602,6 +1640,7 @@ def size(self) -> FrameOrSeriesUnion: return self._reindex_output(result, fill_value=0) + @final @doc(_groupby_agg_method_template, fname="sum", no=True, mc=0) def sum(self, numeric_only: bool = True, min_count: int = 0): @@ -1618,24 +1657,28 @@ def sum(self, numeric_only: bool = True, min_count: int = 0): return self._reindex_output(result, fill_value=0) + @final @doc(_groupby_agg_method_template, fname="prod", no=True, mc=0) def prod(self, numeric_only: bool = True, min_count: int = 0): return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="prod", npfunc=np.prod ) + @final @doc(_groupby_agg_method_template, fname="min", no=False, mc=-1) def min(self, numeric_only: bool = False, min_count: int = -1): return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="min", npfunc=np.min ) + @final @doc(_groupby_agg_method_template, fname="max", no=False, mc=-1) def max(self, numeric_only: bool = False, min_count: int = -1): return self._agg_general( numeric_only=numeric_only, min_count=min_count, alias="max", npfunc=np.max ) + @final @doc(_groupby_agg_method_template, fname="first", no=False, mc=-1) def first(self, numeric_only: bool = False, min_count: int = -1): def first_compat(obj: FrameOrSeries, axis: int = 0): @@ -1660,6 +1703,7 @@ def first(x: Series): npfunc=first_compat, ) + @final @doc(_groupby_agg_method_template, fname="last", no=False, mc=-1) def last(self, numeric_only: bool = False, min_count: int = -1): def last_compat(obj: FrameOrSeries, axis: int = 0): @@ -1684,6 +1728,7 @@ def last(x: Series): npfunc=last_compat, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def ohlc(self) -> DataFrame: @@ -1699,6 +1744,7 @@ def ohlc(self) -> DataFrame: """ return self._apply_to_column_groupbys(lambda x: x._cython_agg_general("ohlc")) + @final @doc(DataFrame.describe) def describe(self, **kwargs): with group_selection_context(self): @@ -1707,6 +1753,7 @@ def describe(self, **kwargs): return result.T return result.unstack() + @final def resample(self, rule, *args, **kwargs): """ Provide resampling when using a TimeGrouper. @@ -1808,6 +1855,7 @@ def resample(self, rule, *args, **kwargs): return get_resampler_for_grouping(self, rule, *args, **kwargs) + @final @Substitution(name="groupby") @Appender(_common_see_also) def rolling(self, *args, **kwargs): @@ -1818,6 +1866,7 @@ def rolling(self, *args, **kwargs): return RollingGroupby(self, *args, **kwargs) + @final @Substitution(name="groupby") @Appender(_common_see_also) def expanding(self, *args, **kwargs): @@ -1829,6 +1878,7 @@ def expanding(self, *args, **kwargs): return ExpandingGroupby(self, *args, **kwargs) + @final @Substitution(name="groupby") @Appender(_common_see_also) def ewm(self, *args, **kwargs): @@ -1839,6 +1889,7 @@ def ewm(self, *args, **kwargs): return ExponentialMovingWindowGroupby(self, *args, **kwargs) + @final def _fill(self, direction, limit=None): """ Shared function for `pad` and `backfill` to call Cython method. @@ -1877,6 +1928,7 @@ def _fill(self, direction, limit=None): dropna=self.dropna, ) + @final @Substitution(name="groupby") def pad(self, limit=None): """ @@ -1903,6 +1955,7 @@ def pad(self, limit=None): ffill = pad + @final @Substitution(name="groupby") def backfill(self, limit=None): """ @@ -1929,6 +1982,7 @@ def backfill(self, limit=None): bfill = backfill + @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFrame: @@ -2102,6 +2156,7 @@ def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFra return result + @final def quantile(self, q=0.5, interpolation: str = "linear"): """ Return group values at the given quantile, a la numpy.percentile. @@ -2230,6 +2285,7 @@ def post_processor(vals: np.ndarray, inference: Optional[Type]) -> np.ndarray: ) return result.take(indices, axis=self.axis) + @final @Substitution(name="groupby") def ngroup(self, ascending: bool = True): """ @@ -2297,6 +2353,7 @@ def ngroup(self, ascending: bool = True): result = self.ngroups - 1 - result return result + @final @Substitution(name="groupby") def cumcount(self, ascending: bool = True): """ @@ -2356,6 +2413,7 @@ def cumcount(self, ascending: bool = True): cumcounts = self._cumcount_array(ascending=ascending) return self._obj_1d_constructor(cumcounts, index) + @final @Substitution(name="groupby") @Appender(_common_see_also) def rank( @@ -2405,6 +2463,7 @@ def rank( axis=axis, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def cumprod(self, axis=0, *args, **kwargs): @@ -2421,6 +2480,7 @@ def cumprod(self, axis=0, *args, **kwargs): return self._cython_transform("cumprod", **kwargs) + @final @Substitution(name="groupby") @Appender(_common_see_also) def cumsum(self, axis=0, *args, **kwargs): @@ -2437,6 +2497,7 @@ def cumsum(self, axis=0, *args, **kwargs): return self._cython_transform("cumsum", **kwargs) + @final @Substitution(name="groupby") @Appender(_common_see_also) def cummin(self, axis=0, **kwargs): @@ -2452,6 +2513,7 @@ def cummin(self, axis=0, **kwargs): return self._cython_transform("cummin", numeric_only=False) + @final @Substitution(name="groupby") @Appender(_common_see_also) def cummax(self, axis=0, **kwargs): @@ -2467,6 +2529,7 @@ def cummax(self, axis=0, **kwargs): return self._cython_transform("cummax", numeric_only=False) + @final def _get_cythonized_result( self, how: str, @@ -2625,6 +2688,7 @@ def _get_cythonized_result( else: return self._wrap_transformed_output(output) + @final @Substitution(name="groupby") def shift(self, periods=1, freq=None, axis=0, fill_value=None): """ @@ -2668,6 +2732,7 @@ def shift(self, periods=1, freq=None, axis=0, fill_value=None): periods=periods, ) + @final @Substitution(name="groupby") @Appender(_common_see_also) def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None, axis=0): @@ -2697,6 +2762,7 @@ def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None, axis=0 shifted = fill_grp.shift(periods=periods, freq=freq, axis=self.axis) return (filled / shifted) - 1 + @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def head(self, n=5): @@ -2734,6 +2800,7 @@ def head(self, n=5): else: return self._selected_obj.iloc[:, mask] + @final @Substitution(name="groupby") @Substitution(see_also=_common_see_also) def tail(self, n=5): @@ -2771,6 +2838,7 @@ def tail(self, n=5): else: return self._selected_obj.iloc[:, mask] + @final def _reindex_output( self, output: OutputFrameOrSeries, fill_value: Scalar = np.NaN ) -> OutputFrameOrSeries: @@ -2857,6 +2925,7 @@ def _reindex_output( return output.reset_index(drop=True) + @final def sample( self, n: Optional[int] = None, diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 8b79ea2242258..d814a7cee436e 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -7,7 +7,7 @@ import numpy as np -from pandas._typing import FrameOrSeries, Label +from pandas._typing import FrameOrSeries, Label, final from pandas.errors import InvalidIndexError from pandas.util._decorators import cache_readonly @@ -289,6 +289,7 @@ def __init__( self._grouper = None self.dropna = dropna + @final @property def ax(self): return self.grouper @@ -320,6 +321,7 @@ def _get_grouper(self, obj, validate: bool = True): ) return self.binner, self.grouper, self.obj + @final def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): """ given an object and the specifications, setup the internal grouper @@ -379,12 +381,14 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): self.grouper = ax return self.grouper + @final @property def groups(self): # pandas\core\groupby\grouper.py:382: error: Item "None" of # "Optional[Any]" has no attribute "groups" [union-attr] return self.grouper.groups # type: ignore[union-attr] + @final def __repr__(self) -> str: attrs_list = ( f"{attr_name}={repr(getattr(self, attr_name))}" @@ -396,6 +400,7 @@ def __repr__(self) -> str: return f"{cls_name}({attrs})" +@final class Grouping: """ Holds the grouping information for a single key diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index d98c55755042e..c60a59916affc 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -24,7 +24,7 @@ from pandas._libs import NaT, iNaT, lib import pandas._libs.groupby as libgroupby import pandas._libs.reduction as libreduction -from pandas._typing import ArrayLike, F, FrameOrSeries, Label, Shape +from pandas._typing import ArrayLike, F, FrameOrSeries, Label, Shape, final from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly @@ -146,6 +146,7 @@ def get_iterator( for key, (i, group) in zip(keys, splitter): yield key, group.__finalize__(data, method="groupby") + @final def _get_splitter(self, data: FrameOrSeries, axis: int = 0) -> "DataSplitter": """ Returns @@ -166,6 +167,7 @@ def _get_grouper(self): """ return self.groupings[0].grouper + @final def _get_group_keys(self): if len(self.groupings) == 1: return self.levels[0] @@ -175,6 +177,7 @@ def _get_group_keys(self): # provide "flattened" iterator for multi-group setting return get_flattened_list(comp_ids, ngroups, self.levels, self.codes) + @final def apply(self, f: F, data: FrameOrSeries, axis: int = 0): mutated = self.mutated splitter = self._get_splitter(data, axis=axis) @@ -256,6 +259,7 @@ def levels(self) -> List[Index]: def names(self) -> List[Label]: return [ping.name for ping in self.groupings] + @final def size(self) -> Series: """ Compute group sizes. @@ -278,6 +282,7 @@ def groups(self) -> Dict[Hashable, np.ndarray]: to_groupby = Index(to_groupby) return self.axis.groupby(to_groupby) + @final @cache_readonly def is_monotonic(self) -> bool: # return if my group orderings are monotonic @@ -291,6 +296,7 @@ def group_info(self): comp_ids = ensure_int64(comp_ids) return comp_ids, obs_group_ids, ngroups + @final @cache_readonly def codes_info(self) -> np.ndarray: # return the codes of items in original grouped axis @@ -300,6 +306,7 @@ def codes_info(self) -> np.ndarray: codes = codes[sorter] return codes + @final def _get_compressed_codes(self) -> Tuple[np.ndarray, np.ndarray]: all_codes = self.codes if len(all_codes) > 1: @@ -309,6 +316,7 @@ def _get_compressed_codes(self) -> Tuple[np.ndarray, np.ndarray]: ping = self.groupings[0] return ping.codes, np.arange(len(ping.group_index)) + @final @cache_readonly def ngroups(self) -> int: return len(self.result_index) @@ -330,6 +338,7 @@ def result_index(self) -> Index: levels=levels, codes=codes, verify_integrity=False, names=self.names ) + @final def get_group_levels(self) -> List[Index]: if not self.compressed and len(self.groupings) == 1: return [self.groupings[0].result_index] @@ -370,6 +379,7 @@ def get_group_levels(self) -> List[Index]: _cython_arity = {"ohlc": 4} # OHLC + @final def _is_builtin_func(self, arg): """ if we define a builtin function for this argument, return it, @@ -377,6 +387,7 @@ def _is_builtin_func(self, arg): """ return SelectionMixin._builtin_table.get(arg, arg) + @final def _get_cython_function( self, kind: str, how: str, values: np.ndarray, is_numeric: bool ): @@ -413,6 +424,7 @@ def _get_cython_function( return func + @final def _get_cython_func_and_vals( self, kind: str, how: str, values: np.ndarray, is_numeric: bool ): @@ -447,6 +459,7 @@ def _get_cython_func_and_vals( raise return func, values + @final def _disallow_invalid_ops(self, values: ArrayLike, how: str): """ Check if we can do this operation with our cython functions. @@ -476,6 +489,7 @@ def _disallow_invalid_ops(self, values: ArrayLike, how: str): f"timedelta64 type does not support {how} operations" ) + @final def _ea_wrap_cython_operation( self, kind: str, values, how: str, axis: int, min_count: int = -1, **kwargs ) -> Tuple[np.ndarray, Optional[List[str]]]: @@ -512,6 +526,7 @@ def _ea_wrap_cython_operation( raise NotImplementedError(values.dtype) + @final def _cython_operation( self, kind: str, values, how: str, axis: int, min_count: int = -1, **kwargs ) -> np.ndarray: @@ -625,6 +640,7 @@ def _cython_operation( return result + @final def _aggregate( self, result, counts, values, comp_ids, agg_func, min_count: int = -1 ): @@ -636,6 +652,7 @@ def _aggregate( return result + @final def _transform( self, result, values, comp_ids, transform_func, is_datetimelike: bool, **kwargs ): @@ -674,6 +691,7 @@ def agg_series(self, obj: Series, func: F): raise return self._aggregate_series_pure_python(obj, func) + @final def _aggregate_series_fast(self, obj: Series, func: F): # At this point we have already checked that # - obj.index is not a MultiIndex @@ -693,6 +711,7 @@ def _aggregate_series_fast(self, obj: Series, func: F): result, counts = grouper.get_result() return result, counts + @final def _aggregate_series_pure_python(self, obj: Series, func: F): group_index, _, ngroups = self.group_info
https://api.github.com/repos/pandas-dev/pandas/pulls/38200
2020-12-01T02:21:11Z
2020-12-05T02:03:50Z
2020-12-05T02:03:50Z
2020-12-05T02:22:34Z
Remove duplicate entry on series.rst
diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 8d74c288bf801..cc2937695e80f 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -252,7 +252,6 @@ Combining / comparing / joining / merging Series.append Series.compare - Series.replace Series.update Time Series-related
- [x] closes #38198 - [ ] tests passed. Nothing new fails. Few tails already were failing on `master` - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry (Intentionally ignored as insignificant) Removed the duplicate entry of `Series.replace` from doc
https://api.github.com/repos/pandas-dev/pandas/pulls/38199
2020-11-30T23:49:14Z
2020-12-02T03:02:27Z
2020-12-02T03:02:26Z
2020-12-02T03:02:30Z
BUG: name attr in RangeIndex.intersection
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 24db70481c136..3ec4a82727e9e 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -815,6 +815,7 @@ Other - Fixed metadata propagation in the :class:`Series.dt`, :class:`Series.str` accessors, :class:`DataFrame.duplicated`, :class:`DataFrame.stack`, :class:`DataFrame.unstack`, :class:`DataFrame.pivot`, :class:`DataFrame.append`, :class:`DataFrame.diff`, :class:`DataFrame.applymap` and :class:`DataFrame.update` methods (:issue:`28283`, :issue:`37381`) - Fixed metadata propagation when selecting columns with ``DataFrame.__getitem__`` (:issue:`28283`) - Bug in :meth:`Index.intersection` with non-:class:`Index` failing to set the correct name on the returned :class:`Index` (:issue:`38111`) +- Bug in :meth:`RangeIndex.intersection` failing to set the correct name on the returned :class:`Index` in some corner cases (:issue:`38197`) - Bug in :meth:`Index.union` behaving differently depending on whether operand is an :class:`Index` or other list-like (:issue:`36384`) - Bug in :meth:`Index.intersection` with non-matching numeric dtypes casting to ``object`` dtype instead of minimal common dtype (:issue:`38122`) - Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError`` rather than a bare ``Exception`` (:issue:`35744`) diff --git a/pandas/conftest.py b/pandas/conftest.py index cb5b4145855d1..2bac2ed198789 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1432,3 +1432,17 @@ def __init__(self, **kwargs): registry.pop("testmem", None) TestMemoryFS.test[0] = None TestMemoryFS.store.clear() + + +@pytest.fixture( + params=[ + ("foo", None, None), + ("Egon", "Venkman", None), + ("NCC1701D", "NCC1701D", "NCC1701D"), + ] +) +def names(request): + """ + A 3-tuple of names, the first two for operands, the last for a result. + """ + return request.param diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 6380551fc202c..77de6bdaeec5a 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -508,19 +508,22 @@ def intersection(self, other, sort=False): self._assert_can_do_setop(other) other, _ = self._convert_can_do_setop(other) - if self.equals(other): + if self.equals(other) and not self.has_duplicates: + # has_duplicates check is unnecessary for RangeIndex, but + # used to match other subclasses. return self._get_reconciled_name_object(other) - return self._intersection(other, sort=sort) + if not is_dtype_equal(self.dtype, other.dtype): + return super().intersection(other, sort=sort) + + result = self._intersection(other, sort=sort) + return self._wrap_setop_result(other, result) def _intersection(self, other, sort=False): if not isinstance(other, RangeIndex): - if is_dtype_equal(other.dtype, self.dtype): - # Int64Index - result = super()._intersection(other, sort=sort) - return self._wrap_setop_result(other, result) - return super().intersection(other, sort=sort) + # Int64Index + return super()._intersection(other, sort=sort) if not len(self) or not len(other): return self._simple_new(_empty_range) @@ -562,7 +565,7 @@ def _intersection(self, other, sort=False): if sort is None: new_index = new_index.sort_values() - return self._wrap_setop_result(other, new_index) + return new_index def _min_fitting_element(self, lower_limit: int) -> int: """Returns the smallest element greater than or equal to the limit""" diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py index 149389b936def..f507c6d4f45fb 100644 --- a/pandas/tests/arithmetic/conftest.py +++ b/pandas/tests/arithmetic/conftest.py @@ -18,18 +18,6 @@ def id_func(x): # ------------------------------------------------------------------ -@pytest.fixture( - params=[ - ("foo", None, None), - ("Egon", "Venkman", None), - ("NCC1701D", "NCC1701D", "NCC1701D"), - ] -) -def names(request): - """ - A 3-tuple of names, the first two for operands, the last for a result. - """ - return request.param @pytest.fixture(params=[1, np.array(1, dtype=np.int64)]) diff --git a/pandas/tests/indexes/ranges/test_setops.py b/pandas/tests/indexes/ranges/test_setops.py index 5623b0904c0d5..660269f2d02a4 100644 --- a/pandas/tests/indexes/ranges/test_setops.py +++ b/pandas/tests/indexes/ranges/test_setops.py @@ -37,6 +37,18 @@ def test_intersection_mismatched_dtype(self, klass): result = flt[:0].intersection(index) tm.assert_index_equal(result, flt[:0], exact=True) + def test_intersection_empty(self, sort, names): + # name retention on empty intersections + index = RangeIndex(start=0, stop=20, step=2, name=names[0]) + + # empty other + result = index.intersection(index[:0].rename(names[1]), sort=sort) + tm.assert_index_equal(result, index[:0].rename(names[2]), exact=True) + + # empty self + result = index[:0].intersection(index.rename(names[1]), sort=sort) + tm.assert_index_equal(result, index[:0].rename(names[2]), exact=True) + def test_intersection(self, sort): # intersect with Int64Index index = RangeIndex(start=0, stop=20, step=2) @@ -78,12 +90,12 @@ def test_intersection(self, sort): result = other.intersection(first, sort=sort).astype(int) tm.assert_index_equal(result, expected) - index = RangeIndex(5) + index = RangeIndex(5, name="foo") # intersect of non-overlapping indices - other = RangeIndex(5, 10, 1) + other = RangeIndex(5, 10, 1, name="foo") result = index.intersection(other, sort=sort) - expected = RangeIndex(0, 0, 1) + expected = RangeIndex(0, 0, 1, name="foo") tm.assert_index_equal(result, expected) other = RangeIndex(-1, -5, -1) @@ -100,11 +112,12 @@ def test_intersection(self, sort): result = other.intersection(index, sort=sort) tm.assert_index_equal(result, expected) + def test_intersection_non_overlapping_gcd(self, sort, names): # intersection of non-overlapping values based on start value and gcd - index = RangeIndex(1, 10, 2) - other = RangeIndex(0, 10, 4) + index = RangeIndex(1, 10, 2, name=names[0]) + other = RangeIndex(0, 10, 4, name=names[1]) result = index.intersection(other, sort=sort) - expected = RangeIndex(0, 0, 1) + expected = RangeIndex(0, 0, 1, name=names[2]) tm.assert_index_equal(result, expected) def test_union_noncomparable(self, sort):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38197
2020-11-30T23:44:23Z
2020-12-02T12:03:29Z
2020-12-02T12:03:29Z
2020-12-02T14:40:30Z
BUG: Avoid duplicates in DatetimeIndex.intersection
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 28ff5a8bacc71..2dc13ff2fd682 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -686,8 +686,11 @@ def intersection(self, other, sort=False): """ self._validate_sort_keyword(sort) self._assert_can_do_setop(other) + other, _ = self._convert_can_do_setop(other) if self.equals(other): + if self.has_duplicates: + return self.unique()._get_reconciled_name_object(other) return self._get_reconciled_name_object(other) if len(self) == 0: diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index c8edd30e3f7aa..0127493888214 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -474,7 +474,7 @@ def test_intersection_list(self): values = [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-02-01")] idx = DatetimeIndex(values, name="a") res = idx.intersection(values) - tm.assert_index_equal(res, idx.rename(None)) + tm.assert_index_equal(res, idx) def test_month_range_union_tz_pytz(self, sort): from pytz import timezone @@ -509,6 +509,20 @@ def test_month_range_union_tz_dateutil(self, sort): early_dr.union(late_dr, sort=sort) + @pytest.mark.parametrize("sort", [False, None]) + def test_intersection_duplicates(self, sort): + # GH#38196 + idx1 = Index( + [ + pd.Timestamp("2019-12-13"), + pd.Timestamp("2019-12-12"), + pd.Timestamp("2019-12-12"), + ] + ) + result = idx1.intersection(idx1, sort=sort) + expected = Index([pd.Timestamp("2019-12-13"), pd.Timestamp("2019-12-12")]) + tm.assert_index_equal(result, expected) + class TestCustomDatetimeIndex: def setup_method(self, method):
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` @jbrockmendel I think we should call ``_convert_can_do_setop`` here too, but https://github.com/pandas-dev/pandas/blob/56b9a80e1e47e123eb7a7c01448d1506400f8a5b/pandas/tests/indexes/datetimes/test_setops.py#L472 tests the opposite
https://api.github.com/repos/pandas-dev/pandas/pulls/38196
2020-11-30T23:21:56Z
2020-12-02T01:48:50Z
2020-12-02T01:48:50Z
2020-12-02T12:19:55Z
BUG: DataFrame.idxmin/idxmax with mixed dtypes
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 17cdb7538dad2..9c4de5c888299 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -619,6 +619,7 @@ Numeric - Bug in :class:`DataFrame` allowing arithmetic operations with list of array-likes with undefined results. Behavior changed to raising ``ValueError`` (:issue:`36702`) - Bug in :meth:`DataFrame.std` with ``timedelta64`` dtype and ``skipna=False`` (:issue:`37392`) - Bug in :meth:`DataFrame.min` and :meth:`DataFrame.max` with ``datetime64`` dtype and ``skipna=False`` (:issue:`36907`) +- Bug in :meth:`DataFrame.idxmax` and :meth:`DataFrame.idxmin` with mixed dtypes incorrectly raising ``TypeError`` (:issue:`38195`) Conversion ^^^^^^^^^^ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 9cc9c9ef200cd..5f149f10b05d3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9001,7 +9001,11 @@ def idxmin(self, axis=0, skipna=True) -> Series: dtype: object """ axis = self._get_axis_number(axis) - indices = nanops.nanargmin(self.values, axis=axis, skipna=skipna) + + res = self._reduce( + nanops.nanargmin, "argmin", axis=axis, skipna=skipna, numeric_only=False + ) + indices = res._values # indices will always be np.ndarray since axis is not None and # values is a 2d array for DataFrame @@ -9074,7 +9078,11 @@ def idxmax(self, axis=0, skipna=True) -> Series: dtype: object """ axis = self._get_axis_number(axis) - indices = nanops.nanargmax(self.values, axis=axis, skipna=skipna) + + res = self._reduce( + nanops.nanargmax, "argmax", axis=axis, skipna=skipna, numeric_only=False + ) + indices = res._values # indices will always be np.ndarray since axis is not None and # values is a 2d array for DataFrame diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 299f00e818105..8cf1e17dfd1d0 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -969,6 +969,20 @@ def test_idxmax(self, float_frame, int_frame): with pytest.raises(ValueError, match=msg): frame.idxmax(axis=2) + def test_idxmax_mixed_dtype(self): + # don't cast to object, which would raise in nanops + dti = pd.date_range("2016-01-01", periods=3) + + df = DataFrame({1: [0, 2, 1], 2: range(3)[::-1], 3: dti}) + + result = df.idxmax() + expected = Series([1, 0, 2], index=[1, 2, 3]) + tm.assert_series_equal(result, expected) + + result = df.idxmin() + expected = Series([0, 2, 0], index=[1, 2, 3]) + tm.assert_series_equal(result, expected) + # ---------------------------------------------------------------------- # Logical reductions
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38195
2020-11-30T23:19:05Z
2020-12-02T12:11:06Z
2020-12-02T12:11:06Z
2020-12-02T14:49:20Z
DOC: Clarify development environment creation for documentation changes
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 3c5a88333be56..86d495ef2b097 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -147,8 +147,9 @@ Creating a development environment To test out code changes, you'll need to build pandas from source, which requires a C/C++ compiler and Python environment. If you're making documentation -changes, you can skip to :ref:`contributing.documentation` but you won't be able -to build the documentation locally before pushing your changes. +changes, you can skip to :ref:`contributing.documentation` but if you skip +creating the development environment you won't be able to build the documentation +locally before pushing your changes. Using a Docker container ~~~~~~~~~~~~~~~~~~~~~~~~
Changed wording on paragraph to make clear advantages/disadvantages of creating development environment. - [x] closes #38193
https://api.github.com/repos/pandas-dev/pandas/pulls/38194
2020-11-30T21:44:23Z
2020-12-02T01:52:29Z
2020-12-02T01:52:29Z
2020-12-07T22:05:28Z
DOC: Fixed to_pickle compression argument list 'gzip' > 'gz'
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 181c579e63105..4a9e020a0fe46 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2799,6 +2799,13 @@ def to_pickle( default 'infer' A string representing the compression to use in the output file. By default, infers from the file extension in specified path. + Compression mode may be any of the following possible + values: {{‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}}. If compression + mode is ‘infer’ and path_or_buf is path-like, then detect + compression mode from the following extensions: + ‘.gz’, ‘.bz2’, ‘.zip’ or ‘.xz’. (otherwise no compression). + If dict given and mode is ‘zip’ or inferred as ‘zip’, other entries + passed as additional compression options. protocol : int Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
Removed reference to gzip and replaced with correct extension of gz. - [x] closes #35364 <img width="842" alt="Screenshot 2020-11-30 at 20 43 59" src="https://user-images.githubusercontent.com/74271903/100664097-17d1f200-334f-11eb-90e3-e37ef7ce7c66.png">
https://api.github.com/repos/pandas-dev/pandas/pulls/38192
2020-11-30T20:59:11Z
2020-12-02T03:00:11Z
2020-12-02T03:00:11Z
2020-12-07T22:04:43Z
Backport PR #38172 on branch 1.1.x (CI: update tests for numpy 1.20 change to floordiv)
diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index f549a7caeab1d..d8052cd8134c8 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat.numpy import _np_version_under1p20 + import pandas as pd import pandas._testing as tm from pandas.core.arrays import integer_array @@ -197,7 +199,9 @@ def test_arith_coerce_scalar(data, all_arithmetic_operators): result = op(s, other) expected = op(s.astype(float), other) # rfloordiv results in nan instead of inf - if all_arithmetic_operators == "__rfloordiv__": + if all_arithmetic_operators == "__rfloordiv__" and _np_version_under1p20: + # for numpy 1.20 https://github.com/numpy/numpy/pull/16161 + # updated floordiv, now matches our behavior defined in core.ops expected[(expected == np.inf) | (expected == -np.inf)] = np.nan tm.assert_series_equal(result, expected) diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index c9f1dd7f589fc..61f4e3e50d09d 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.compat.numpy import _np_version_under1p20 + import pandas as pd import pandas._testing as tm from pandas.core import ops @@ -116,9 +118,15 @@ def _check_logical_ops(self, a, b, a_dense, b_dense): @pytest.mark.parametrize("scalar", [0, 1, 3]) @pytest.mark.parametrize("fill_value", [None, 0, 2]) def test_float_scalar( - self, kind, mix, all_arithmetic_functions, fill_value, scalar + self, kind, mix, all_arithmetic_functions, fill_value, scalar, request ): op = all_arithmetic_functions + + if not _np_version_under1p20: + if op in [operator.floordiv, ops.rfloordiv]: + mark = pytest.mark.xfail(strict=False, reason="GH#38172") + request.node.add_marker(mark) + values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) a = self._klass(values, kind=kind, fill_value=fill_value) @@ -142,15 +150,11 @@ def test_float_scalar_comparison(self, kind): self._check_comparison_ops(a, 0, values, 0) self._check_comparison_ops(a, 3, values, 3) - def test_float_same_index(self, kind, mix, all_arithmetic_functions): + def test_float_same_index_without_nans( + self, kind, mix, all_arithmetic_functions, request + ): # when sp_index are the same op = all_arithmetic_functions - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan]) - - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) - self._check_numeric_ops(a, b, values, rvalues, mix, op) values = self._base([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0]) rvalues = self._base([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0]) @@ -159,6 +163,24 @@ def test_float_same_index(self, kind, mix, all_arithmetic_functions): b = self._klass(rvalues, kind=kind, fill_value=0) self._check_numeric_ops(a, b, values, rvalues, mix, op) + def test_float_same_index_with_nans( + self, kind, mix, all_arithmetic_functions, request + ): + # when sp_index are the same + op = all_arithmetic_functions + + if not _np_version_under1p20: + if op in [operator.floordiv, ops.rfloordiv]: + mark = pytest.mark.xfail(strict=False, reason="GH#38172") + request.node.add_marker(mark) + + values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan]) + + a = self._klass(values, kind=kind) + b = self._klass(rvalues, kind=kind) + self._check_numeric_ops(a, b, values, rvalues, mix, op) + def test_float_same_index_comparison(self, kind): # when sp_index are the same values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) @@ -324,9 +346,14 @@ def test_bool_array_logical(self, kind, fill_value): b = self._klass(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value) self._check_logical_ops(a, b, values, rvalues) - def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions): + def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, request): op = all_arithmetic_functions + if not _np_version_under1p20: + if op in [operator.floordiv, ops.rfloordiv] and mix: + mark = pytest.mark.xfail(strict=True, reason="GH#38172") + request.node.add_marker(mark) + rdtype = "int64" values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan])
Backport PR #38172: CI: update tests for numpy 1.20 change to floordiv
https://api.github.com/repos/pandas-dev/pandas/pulls/38191
2020-11-30T18:48:37Z
2020-11-30T21:00:00Z
2020-11-30T21:00:00Z
2020-11-30T21:00:01Z
REF: IntervalIndex.intersection match pattern in other intersection methods
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 09fe885e47754..ad5de61cf665b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2828,8 +2828,8 @@ def intersection(self, other, sort=False): if not is_dtype_equal(self.dtype, other.dtype): dtype = find_common_type([self.dtype, other.dtype]) - this = self.astype(dtype) - other = other.astype(dtype) + this = self.astype(dtype, copy=False) + other = other.astype(dtype, copy=False) return this.intersection(other, sort=sort) result = self._intersection(other, sort=sort) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index bd92926941aa1..8af9d12e22ee0 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -967,9 +967,20 @@ def intersection(self, other, sort=False) -> Index: self._assert_can_do_setop(other) other, _ = self._convert_can_do_setop(other) + if self.equals(other) and not self.has_duplicates: + return self._get_reconciled_name_object(other) + if not isinstance(other, IntervalIndex): return self.astype(object).intersection(other) + result = self._intersection(other, sort=sort) + return self._wrap_setop_result(other, result) + + def _intersection(self, other, sort): + """ + intersection specialized to the case with matching dtypes. + """ + # For IntervalIndex we also know other.closed == self.closed if self.left.is_unique and self.right.is_unique: taken = self._intersection_unique(other) elif other.left.is_unique and other.right.is_unique and self.isna().sum() <= 1: @@ -983,7 +994,7 @@ def intersection(self, other, sort=False) -> Index: if sort is None: taken = taken.sort_values() - return self._wrap_setop_result(other, taken) + return taken def _intersection_unique(self, other: "IntervalIndex") -> "IntervalIndex": """ diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 4aedf03ca1800..03f6387ae2dc5 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -3723,7 +3723,7 @@ def _convert_can_do_setop(self, other): try: other = MultiIndex.from_tuples(other) except (ValueError, TypeError) as err: - # ValueError raised by tupels_to_object_array if we + # ValueError raised by tuples_to_object_array if we # have non-object dtype raise TypeError(msg) from err else:
Looking to share the boilerplate and have subclasses just implement _intersection.
https://api.github.com/repos/pandas-dev/pandas/pulls/38190
2020-11-30T17:42:05Z
2020-12-02T01:45:02Z
2020-12-02T01:45:02Z
2020-12-02T01:51:30Z
DOC: fix redirects to user guide in README
diff --git a/README.md b/README.md index 4072faffe3b3a..6d1d890c54093 100644 --- a/README.md +++ b/README.md @@ -63,24 +63,24 @@ Here are just a few of the things that pandas does well: date shifting and lagging - [missing-data]: https://pandas.pydata.org/pandas-docs/stable/missing_data.html#working-with-missing-data - [insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/dsintro.html#column-selection-addition-deletion - [alignment]: https://pandas.pydata.org/pandas-docs/stable/dsintro.html?highlight=alignment#intro-to-data-structures - [groupby]: https://pandas.pydata.org/pandas-docs/stable/groupby.html#group-by-split-apply-combine - [conversion]: https://pandas.pydata.org/pandas-docs/stable/dsintro.html#dataframe - [slicing]: https://pandas.pydata.org/pandas-docs/stable/indexing.html#slicing-ranges - [fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/indexing.html#advanced-indexing-with-ix - [subsetting]: https://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing - [merging]: https://pandas.pydata.org/pandas-docs/stable/merging.html#database-style-dataframe-joining-merging - [joining]: https://pandas.pydata.org/pandas-docs/stable/merging.html#joining-on-index - [reshape]: https://pandas.pydata.org/pandas-docs/stable/reshaping.html#reshaping-and-pivot-tables - [pivot-table]: https://pandas.pydata.org/pandas-docs/stable/reshaping.html#pivot-tables-and-cross-tabulations - [mi]: https://pandas.pydata.org/pandas-docs/stable/indexing.html#hierarchical-indexing-multiindex - [flat-files]: https://pandas.pydata.org/pandas-docs/stable/io.html#csv-text-files - [excel]: https://pandas.pydata.org/pandas-docs/stable/io.html#excel-files - [db]: https://pandas.pydata.org/pandas-docs/stable/io.html#sql-queries - [hdfstore]: https://pandas.pydata.org/pandas-docs/stable/io.html#hdf5-pytables - [timeseries]: https://pandas.pydata.org/pandas-docs/stable/timeseries.html#time-series-date-functionality + [missing-data]: https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html + [insertion-deletion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#column-selection-addition-deletion + [alignment]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html?highlight=alignment#intro-to-data-structures + [groupby]: https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#group-by-split-apply-combine + [conversion]: https://pandas.pydata.org/pandas-docs/stable/user_guide/dsintro.html#dataframe + [slicing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#slicing-ranges + [fancy-indexing]: https://pandas.pydata.org/pandas-docs/stable/user_guide/advanced.html#advanced + [subsetting]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing + [merging]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#database-style-dataframe-or-named-series-joining-merging + [joining]: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html#joining-on-index + [reshape]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html + [pivot-table]: https://pandas.pydata.org/pandas-docs/stable/user_guide/reshaping.html + [mi]: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#hierarchical-indexing-multiindex + [flat-files]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#csv-text-files + [excel]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#excel-files + [db]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#sql-queries + [hdfstore]: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#hdf5-pytables + [timeseries]: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#time-series-date-functionality ## Where to get it The source code is currently hosted on GitHub at: @@ -154,7 +154,7 @@ For usage questions, the best place to go to is [StackOverflow](https://stackove Further, general questions and discussions can also take place on the [pydata mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata). ## Discussion and Development -Most development discussions take place on github in this repo. Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Gitter channel](https://gitter.im/pydata/pandas) is available for quick development related questions. +Most development discussions take place on GitHub in this repo. Further, the [pandas-dev mailing list](https://mail.python.org/mailman/listinfo/pandas-dev) can also be used for specialized discussions or design issues, and a [Gitter channel](https://gitter.im/pydata/pandas) is available for quick development related questions. ## Contributing to pandas [![Open Source Helpers](https://www.codetriage.com/pandas-dev/pandas/badges/users.svg)](https://www.codetriage.com/pandas-dev/pandas)
Documentation pages were moved so this commit updates those links to open more directly rather than getting a "This page has been moved to..." message. - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/38189
2020-11-30T17:18:53Z
2020-12-02T01:37:35Z
2020-12-02T01:37:35Z
2020-12-02T01:44:25Z