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
Comma cleanup
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 7bb1d98086a91..8e2ac4feb7ded 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -51,7 +51,7 @@ def test_reindex_with_same_tz(self): "2010-01-02 00:00:00", ] expected1 = DatetimeIndex( - expected_list1, dtype="datetime64[ns, UTC]", freq=None, + expected_list1, dtype="datetime64[ns, UTC]", freq=None ) expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.dtype("intp")) tm.assert_index_equal(result1, expected1) diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index ea68e8759c123..233835bb4b5f7 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -799,7 +799,7 @@ def test_dti_from_tzaware_datetime(self, tz): @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_dti_tz_constructors(self, tzstr): - """ Test different DatetimeIndex constructions with timezone + """Test different DatetimeIndex constructions with timezone Follow-up of GH#4229 """ arr = ["11/10/2005 08:00:00", "11/10/2005 09:00:00"] diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py index 1157c7f8bb962..16af884c89e9e 100644 --- a/pandas/tests/indexes/multi/test_constructors.py +++ b/pandas/tests/indexes/multi/test_constructors.py @@ -741,18 +741,18 @@ def test_raise_invalid_sortorder(): with pytest.raises(ValueError, match=r".* sortorder 2 with lexsort_depth 1.*"): MultiIndex( - levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=2, + levels=levels, codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 2, 1]], sortorder=2 ) with pytest.raises(ValueError, match=r".* sortorder 1 with lexsort_depth 0.*"): MultiIndex( - levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=1, + levels=levels, codes=[[0, 0, 1, 0, 1, 1], [0, 1, 0, 2, 2, 1]], sortorder=1 ) def test_datetimeindex(): idx1 = pd.DatetimeIndex( - ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"] * 2, tz="Asia/Tokyo", + ["2013-04-01 9:00", "2013-04-02 9:00", "2013-04-03 9:00"] * 2, tz="Asia/Tokyo" ) idx2 = pd.date_range("2010/01/01", periods=6, freq="M", tz="US/Eastern") idx = MultiIndex.from_arrays([idx1, idx2]) diff --git a/pandas/tests/indexes/multi/test_isin.py b/pandas/tests/indexes/multi/test_isin.py index 122263e6ec198..b369b9a50954e 100644 --- a/pandas/tests/indexes/multi/test_isin.py +++ b/pandas/tests/indexes/multi/test_isin.py @@ -78,7 +78,7 @@ def test_isin_level_kwarg(): @pytest.mark.parametrize( "labels,expected,level", [ - ([("b", np.nan)], np.array([False, False, True]), None,), + ([("b", np.nan)], np.array([False, False, True]), None), ([np.nan, "a"], np.array([True, True, False]), 0), (["d", np.nan], np.array([False, True, True]), 1), ], diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index aee4b16621b4d..7720db9d98ebf 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2426,7 +2426,7 @@ def test_index_with_tuple_bool(self): # TODO: remove tupleize_cols=False once correct behaviour is restored # TODO: also this op right now produces FutureWarning from numpy idx = Index([("a", "b"), ("b", "c"), ("c", "a")], tupleize_cols=False) - result = idx == ("c", "a",) + result = idx == ("c", "a") expected = np.array([False, False, True]) tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/indexes/timedeltas/test_scalar_compat.py b/pandas/tests/indexes/timedeltas/test_scalar_compat.py index 16c19b8d00380..6a2238d90b590 100644 --- a/pandas/tests/indexes/timedeltas/test_scalar_compat.py +++ b/pandas/tests/indexes/timedeltas/test_scalar_compat.py @@ -104,18 +104,18 @@ def test_round(self): "L", t1a, TimedeltaIndex( - ["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"], + ["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"] ), ), ( "S", t1a, TimedeltaIndex( - ["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"], + ["-1 days +00:00:00", "-2 days +23:58:58", "-2 days +23:57:56"] ), ), - ("12T", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"],),), - ("H", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"],),), + ("12T", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"])), + ("H", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"])), ("d", t1c, TimedeltaIndex([-1, -1, -1], unit="D")), ]: diff --git a/pandas/tests/indexes/timedeltas/test_searchsorted.py b/pandas/tests/indexes/timedeltas/test_searchsorted.py index 4806a9acff96f..3cf45931cf6b7 100644 --- a/pandas/tests/indexes/timedeltas/test_searchsorted.py +++ b/pandas/tests/indexes/timedeltas/test_searchsorted.py @@ -17,7 +17,7 @@ def test_searchsorted_different_argument_classes(self, klass): tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize( - "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2], + "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2] ) def test_searchsorted_invalid_argument_dtype(self, arg): idx = TimedeltaIndex(["1 day", "2 days", "3 days"]) diff --git a/pandas/tests/indexing/common.py b/pandas/tests/indexing/common.py index 9cc031001f81c..656d25bec2a6b 100644 --- a/pandas/tests/indexing/common.py +++ b/pandas/tests/indexing/common.py @@ -144,9 +144,7 @@ def check_values(self, f, func, values=False): tm.assert_almost_equal(result, expected) - def check_result( - self, method, key, typs=None, axes=None, fails=None, - ): + def check_result(self, method, key, typs=None, axes=None, fails=None): def _eq(axis, obj, key): """ compare equal for these 2 keys """ axified = _axify(obj, key, axis) diff --git a/pandas/tests/indexing/test_callable.py b/pandas/tests/indexing/test_callable.py index 621417eb38d94..bf51c3e5d1695 100644 --- a/pandas/tests/indexing/test_callable.py +++ b/pandas/tests/indexing/test_callable.py @@ -17,15 +17,11 @@ def test_frame_loc_callable(self): res = df.loc[lambda x: x.A > 2] tm.assert_frame_equal(res, df.loc[df.A > 2]) - res = df.loc[ - lambda x: x.A > 2, - ] # noqa: E231 - tm.assert_frame_equal(res, df.loc[df.A > 2,]) # noqa: E231 + res = df.loc[lambda x: x.A > 2] # noqa: E231 + tm.assert_frame_equal(res, df.loc[df.A > 2]) # noqa: E231 - res = df.loc[ - lambda x: x.A > 2, - ] # noqa: E231 - tm.assert_frame_equal(res, df.loc[df.A > 2,]) # noqa: E231 + res = df.loc[lambda x: x.A > 2] # noqa: E231 + tm.assert_frame_equal(res, df.loc[df.A > 2]) # noqa: E231 res = df.loc[lambda x: x.B == "b", :] tm.assert_frame_equal(res, df.loc[df.B == "b", :]) @@ -94,10 +90,8 @@ def test_frame_loc_callable_labels(self): res = df.loc[lambda x: ["A", "C"]] tm.assert_frame_equal(res, df.loc[["A", "C"]]) - res = df.loc[ - lambda x: ["A", "C"], - ] # noqa: E231 - tm.assert_frame_equal(res, df.loc[["A", "C"],]) # noqa: E231 + res = df.loc[lambda x: ["A", "C"]] # noqa: E231 + tm.assert_frame_equal(res, df.loc[["A", "C"]]) # noqa: E231 res = df.loc[lambda x: ["A", "C"], :] tm.assert_frame_equal(res, df.loc[["A", "C"], :]) diff --git a/pandas/tests/indexing/test_check_indexer.py b/pandas/tests/indexing/test_check_indexer.py index 69d4065234d93..865ecb129cdfa 100644 --- a/pandas/tests/indexing/test_check_indexer.py +++ b/pandas/tests/indexing/test_check_indexer.py @@ -32,7 +32,7 @@ def test_valid_input(indexer, expected): @pytest.mark.parametrize( - "indexer", [[True, False, None], pd.array([True, False, None], dtype="boolean")], + "indexer", [[True, False, None], pd.array([True, False, None], dtype="boolean")] ) def test_boolean_na_returns_indexer(indexer): # https://github.com/pandas-dev/pandas/issues/31503 @@ -61,7 +61,7 @@ def test_bool_raise_length(indexer): @pytest.mark.parametrize( - "indexer", [[0, 1, None], pd.array([0, 1, pd.NA], dtype="Int64")], + "indexer", [[0, 1, None], pd.array([0, 1, pd.NA], dtype="Int64")] ) def test_int_raise_missing_values(indexer): array = np.array([1, 2, 3]) @@ -89,9 +89,7 @@ def test_raise_invalid_array_dtypes(indexer): check_array_indexer(array, indexer) -@pytest.mark.parametrize( - "indexer", [None, Ellipsis, slice(0, 3), (None,)], -) +@pytest.mark.parametrize("indexer", [None, Ellipsis, slice(0, 3), (None,)]) def test_pass_through_non_array_likes(indexer): array = np.array([1, 2, 3]) diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 1c5f00ff754a4..752ecd47fe089 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -87,7 +87,7 @@ def _assert_setitem_series_conversion( # tm.assert_series_equal(temp, expected_series) @pytest.mark.parametrize( - "val,exp_dtype", [(1, object), (1.1, object), (1 + 1j, object), (True, object)], + "val,exp_dtype", [(1, object), (1.1, object), (1 + 1j, object), (True, object)] ) def test_setitem_series_object(self, val, exp_dtype): obj = pd.Series(list("abcd")) diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 18b9898e7d800..c48e0a129e161 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -181,9 +181,7 @@ def test_scalar_with_mixed(self): expected = 3 assert result == expected - @pytest.mark.parametrize( - "index_func", [tm.makeIntIndex, tm.makeRangeIndex], - ) + @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) @pytest.mark.parametrize("klass", [Series, DataFrame]) def test_scalar_integer(self, index_func, klass): @@ -405,7 +403,7 @@ def test_slice_integer(self): @pytest.mark.parametrize("l", [slice(2, 4.0), slice(2.0, 4), slice(2.0, 4.0)]) def test_integer_positional_indexing(self, l): - """ make sure that we are raising on positional indexing + """make sure that we are raising on positional indexing w.r.t. an integer index """ s = Series(range(2, 6), index=range(2, 6)) @@ -425,9 +423,7 @@ def test_integer_positional_indexing(self, l): with pytest.raises(TypeError, match=msg): s.iloc[l] - @pytest.mark.parametrize( - "index_func", [tm.makeIntIndex, tm.makeRangeIndex], - ) + @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) def test_slice_integer_frame_getitem(self, index_func): # similar to above, but on the getitem dim (of a DataFrame) @@ -486,9 +482,7 @@ def test_slice_integer_frame_getitem(self, index_func): s[l] @pytest.mark.parametrize("l", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) - @pytest.mark.parametrize( - "index_func", [tm.makeIntIndex, tm.makeRangeIndex], - ) + @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) def test_float_slice_getitem_with_integer_index_raises(self, l, index_func): # similar to above, but on the getitem dim (of a DataFrame)
- [x] pandas/tests/indexes/datetimes/test_datetime.py - [x] pandas/tests/indexes/datetimes/test_timezones.py - [x] pandas/tests/indexes/multi/test_constructors.py - [x] pandas/tests/indexes/multi/test_isin.py - [x] pandas/tests/indexes/test_base.py - [x] pandas/tests/indexes/timedeltas/test_scalar_compat.py - [x] pandas/tests/indexes/timedeltas/test_searchsorted.py - [x] pandas/tests/indexing/common.py - [x] pandas/tests/indexing/test_callable.py - [x] pandas/tests/indexing/test_check_indexer.py - [x] pandas/tests/indexing/test_coercion.py - [x] pandas/tests/indexing/test_floats.py
https://api.github.com/repos/pandas-dev/pandas/pulls/36082
2020-09-03T02:02:22Z
2020-09-05T03:10:50Z
2020-09-05T03:10:50Z
2020-09-05T03:10:54Z
BUG: add py39 compat check for ast.slice #32766
diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index df71b4fe415f8..3865c42993312 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -10,6 +10,8 @@ import numpy as np +from pandas.compat import PY39 + import pandas.core.common as com from pandas.core.computation.ops import ( _LOCAL_TAG, @@ -186,7 +188,6 @@ def _filter_nodes(superclass, all_nodes=_all_nodes): _stmt_nodes = _filter_nodes(ast.stmt) _expr_nodes = _filter_nodes(ast.expr) _expr_context_nodes = _filter_nodes(ast.expr_context) -_slice_nodes = _filter_nodes(ast.slice) _boolop_nodes = _filter_nodes(ast.boolop) _operator_nodes = _filter_nodes(ast.operator) _unary_op_nodes = _filter_nodes(ast.unaryop) @@ -197,6 +198,9 @@ def _filter_nodes(superclass, all_nodes=_all_nodes): _keyword_nodes = _filter_nodes(ast.keyword) _alias_nodes = _filter_nodes(ast.alias) +if not PY39: + _slice_nodes = _filter_nodes(ast.slice) + # nodes that we don't support directly but are needed for parsing _hacked_nodes = frozenset(["Assign", "Module", "Expr"])
- [x] closes #32766 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/36080
2020-09-02T23:19:47Z
2020-09-15T02:06:08Z
2020-09-15T02:06:07Z
2020-09-15T15:13:49Z
DOC: Fix typo of `=!` to `!=` in docstring
diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py index 99c2fefc97ae7..e3a68ad328d55 100644 --- a/pandas/core/ops/docstrings.py +++ b/pandas/core/ops/docstrings.py @@ -611,7 +611,7 @@ def _make_flex_doc(op_name, typ): Among flexible wrappers (`eq`, `ne`, `le`, `lt`, `ge`, `gt`) to comparison operators. -Equivalent to `==`, `=!`, `<=`, `<`, `>=`, `>` with support to choose axis +Equivalent to `==`, `!=`, `<=`, `<`, `>=`, `>` with support to choose axis (rows or columns) and level for comparison. Parameters
This fixes GH36075. - [x] closes #36075 I'm marking the following list items as not-applicable because I'm simply swapping two characters in a docstring that had been in the incorrect order. - [NA] tests added / passed - [NA] passes `black pandas` - [NA] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [NA] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/36077
2020-09-02T18:00:48Z
2020-09-02T19:09:23Z
2020-09-02T19:09:23Z
2021-04-07T01:26:05Z
CLN clearing unnecessary trailing commas
diff --git a/pandas/tests/scalar/test_na_scalar.py b/pandas/tests/scalar/test_na_scalar.py index dc5eb15348c1b..0a7dfbee4e672 100644 --- a/pandas/tests/scalar/test_na_scalar.py +++ b/pandas/tests/scalar/test_na_scalar.py @@ -111,7 +111,7 @@ def test_pow_special(value, asarray): @pytest.mark.parametrize( - "value", [1, 1.0, True, np.bool_(True), np.int_(1), np.float_(1)], + "value", [1, 1.0, True, np.bool_(True), np.int_(1), np.float_(1)] ) @pytest.mark.parametrize("asarray", [True, False]) def test_rpow_special(value, asarray): @@ -128,9 +128,7 @@ def test_rpow_special(value, asarray): assert result == value -@pytest.mark.parametrize( - "value", [-1, -1.0, np.int_(-1), np.float_(-1)], -) +@pytest.mark.parametrize("value", [-1, -1.0, np.int_(-1), np.float_(-1)]) @pytest.mark.parametrize("asarray", [True, False]) def test_rpow_minus_one(value, asarray): if asarray: @@ -193,9 +191,7 @@ def test_logical_not(): assert ~NA is NA -@pytest.mark.parametrize( - "shape", [(3,), (3, 3), (1, 2, 3)], -) +@pytest.mark.parametrize("shape", [(3,), (3, 3), (1, 2, 3)]) def test_arithmetic_ndarray(shape, all_arithmetic_functions): op = all_arithmetic_functions a = np.zeros(shape) diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index 954301b979074..1e980b6e4559c 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -213,7 +213,7 @@ def test_add_int_with_freq(self, ts, other): with pytest.raises(TypeError, match=msg): other - ts - @pytest.mark.parametrize("shape", [(6,), (2, 3,)]) + @pytest.mark.parametrize("shape", [(6,), (2, 3)]) def test_addsub_m8ndarray(self, shape): # GH#33296 ts = Timestamp("2020-04-04 15:45") @@ -237,7 +237,7 @@ def test_addsub_m8ndarray(self, shape): with pytest.raises(TypeError, match=msg): other - ts - @pytest.mark.parametrize("shape", [(6,), (2, 3,)]) + @pytest.mark.parametrize("shape", [(6,), (2, 3)]) def test_addsub_m8ndarray_tzaware(self, shape): # GH#33296 ts = Timestamp("2020-04-04 15:45", tz="US/Pacific") diff --git a/pandas/tests/series/methods/test_argsort.py b/pandas/tests/series/methods/test_argsort.py index 4353eb4c8cd64..ec9ba468c996c 100644 --- a/pandas/tests/series/methods/test_argsort.py +++ b/pandas/tests/series/methods/test_argsort.py @@ -9,7 +9,7 @@ class TestSeriesArgsort: def _check_accum_op(self, name, ser, check_dtype=True): func = getattr(np, name) tm.assert_numpy_array_equal( - func(ser).values, func(np.array(ser)), check_dtype=check_dtype, + func(ser).values, func(np.array(ser)), check_dtype=check_dtype ) # with missing values diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py index dd4bf642e68e8..8a915324a72c1 100644 --- a/pandas/tests/series/methods/test_convert_dtypes.py +++ b/pandas/tests/series/methods/test_convert_dtypes.py @@ -219,10 +219,10 @@ class TestSeriesConvertDtypes: pd.to_datetime(["2020-01-14 10:00", "2020-01-15 11:11"]), object, { - ((True,), (True, False), (True, False), (True, False),): np.dtype( + ((True,), (True, False), (True, False), (True, False)): np.dtype( "datetime64[ns]" ), - ((False,), (True, False), (True, False), (True, False),): np.dtype( + ((False,), (True, False), (True, False), (True, False)): np.dtype( "O" ), }, diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py index 40651c4342e8a..6eb0e09f12658 100644 --- a/pandas/tests/series/methods/test_drop_duplicates.py +++ b/pandas/tests/series/methods/test_drop_duplicates.py @@ -141,7 +141,7 @@ def test_drop_duplicates_categorical_non_bool(self, dtype, ordered): def test_drop_duplicates_categorical_bool(self, ordered): tc = Series( Categorical( - [True, False, True, False], categories=[True, False], ordered=ordered, + [True, False, True, False], categories=[True, False], ordered=ordered ) ) diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index c4b10e0ccdc3e..cba9443005f2f 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -30,7 +30,7 @@ ] ) def nontemporal_method(request): - """ Fixture that returns an (method name, required kwargs) pair. + """Fixture that returns an (method name, required kwargs) pair. This fixture does not include method 'time' as a parameterization; that method requires a Series with a DatetimeIndex, and is generally tested @@ -60,7 +60,7 @@ def nontemporal_method(request): ] ) def interp_methods_ind(request): - """ Fixture that returns a (method name, required kwargs) pair to + """Fixture that returns a (method name, required kwargs) pair to be tested for various Index types. This fixture does not include methods - 'time', 'index', 'nearest', diff --git a/pandas/tests/series/methods/test_unstack.py b/pandas/tests/series/methods/test_unstack.py index cdf6a16e88ad0..d651315d64561 100644 --- a/pandas/tests/series/methods/test_unstack.py +++ b/pandas/tests/series/methods/test_unstack.py @@ -75,9 +75,7 @@ def test_unstack_tuplename_in_multiindex(): expected = pd.DataFrame( [[1, 1, 1], [1, 1, 1], [1, 1, 1]], - columns=pd.MultiIndex.from_tuples( - [("a",), ("b",), ("c",)], names=[("A", "a")], - ), + columns=pd.MultiIndex.from_tuples([("a",), ("b",), ("c",)], names=[("A", "a")]), index=pd.Index([1, 2, 3], name=("B", "b")), ) tm.assert_frame_equal(result, expected) @@ -115,7 +113,7 @@ def test_unstack_mixed_type_name_in_multiindex( result = ser.unstack(unstack_idx) expected = pd.DataFrame( - expected_values, columns=expected_columns, index=expected_index, + expected_values, columns=expected_columns, index=expected_index ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/test_cumulative.py b/pandas/tests/series/test_cumulative.py index 0b4c5f091106a..e070b86717503 100644 --- a/pandas/tests/series/test_cumulative.py +++ b/pandas/tests/series/test_cumulative.py @@ -17,7 +17,7 @@ def _check_accum_op(name, series, check_dtype=True): func = getattr(np, name) tm.assert_numpy_array_equal( - func(series).values, func(np.array(series)), check_dtype=check_dtype, + func(series).values, func(np.array(series)), check_dtype=check_dtype ) # with missing values diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 67a2dc2303550..4e94051305f49 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -970,7 +970,7 @@ def test_isin_int_df_string_search(self): @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 """ + -> should not match values because np.nan is not equal str NaN""" df = pd.DataFrame({"values": [np.nan, 2]}) result = df.isin(["NaN"]) expected_false = pd.DataFrame({"values": [False, False]})
This PR is related to issue #35925, black 19.10b0 and upgraded version both passes these changes.
https://api.github.com/repos/pandas-dev/pandas/pulls/36073
2020-09-02T16:51:04Z
2020-09-02T19:21:30Z
2020-09-02T19:21:30Z
2020-09-02T19:21:45Z
Backport PR #36051 on branch 1.1.x (BUG: frame._item_cache not cleared when Series is altered)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 9be5b5f0ad2dc..927b3290ac606 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -31,6 +31,7 @@ Bug fixes - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) - Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should bw ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) +- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`36051`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 8bd1dbea4696f..67e5759b39808 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3233,6 +3233,10 @@ def _maybe_update_cacher( if len(self) == len(ref): # otherwise, either self or ref has swapped in new arrays ref._maybe_cache_changed(cacher[0], self) + else: + # GH#33675 we have swapped in a new array, so parent + # reference to self is now invalid + ref._item_cache.pop(cacher[0], None) if verify_is_copy: self._check_setitem_copy(stacklevel=5, t="referant") diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 9bf5d24085697..b4f91590e09d1 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -135,13 +135,20 @@ def test_drop_and_dropna_caching(self): df2 = df.copy() df["A"].dropna() tm.assert_series_equal(df["A"], original) - return_value = df["A"].dropna(inplace=True) - tm.assert_series_equal(df["A"], expected) + + ser = df["A"] + return_value = ser.dropna(inplace=True) + tm.assert_series_equal(ser, expected) + tm.assert_series_equal(df["A"], original) assert return_value is None + df2["A"].drop([1]) tm.assert_series_equal(df2["A"], original) - return_value = df2["A"].drop([1], inplace=True) - tm.assert_series_equal(df2["A"], original.drop([1])) + + ser = df2["A"] + return_value = ser.drop([1], inplace=True) + tm.assert_series_equal(ser, original.drop([1])) + tm.assert_series_equal(df2["A"], original) assert return_value is None def test_dropna_corner(self, float_frame): diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index fa5fe5ba5c384..9910ef1b04b1a 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -81,6 +81,21 @@ def test_setitem_cache_updating(self): tm.assert_frame_equal(out, expected) tm.assert_series_equal(out["A"], expected["A"]) + def test_altering_series_clears_parent_cache(self): + # GH #33675 + df = pd.DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"]) + ser = df["A"] + + assert "A" in df._item_cache + + # Adding a new entry to ser swaps in a new array, so "A" needs to + # be removed from df._item_cache + ser["c"] = 5 + assert len(ser) == 3 + assert "A" not in df._item_cache + assert df["A"] is not ser + assert len(df["A"]) == 2 + class TestChaining: def test_setitem_chained_setfault(self):
Backport PR #36051: BUG: frame._item_cache not cleared when Series is altered
https://api.github.com/repos/pandas-dev/pandas/pulls/36072
2020-09-02T16:02:19Z
2020-09-02T17:09:18Z
2020-09-02T17:09:18Z
2020-09-02T17:09:18Z
Backport PR #35852 on branch 1.1.x (API: replace dropna=False option with na_sentinel=None in factorize)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 9be5b5f0ad2dc..dc7adf6d9d00e 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -34,6 +34,14 @@ Bug fixes .. --------------------------------------------------------------------------- +.. _whatsnew_112.other: + +Other +~~~~~ +- :meth:`factorize` now supports ``na_sentinel=None`` to include NaN in the uniques of the values and remove ``dropna`` keyword which was unintentionally exposed to public facing API in 1.1 version from :meth:`factorize`(:issue:`35667`) + +.. --------------------------------------------------------------------------- + .. _whatsnew_112.contributors: Contributors diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 9e3ca4cc53363..856b4ead3f3cc 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -525,9 +525,8 @@ def _factorize_array( def factorize( values, sort: bool = False, - na_sentinel: int = -1, + na_sentinel: Optional[int] = -1, size_hint: Optional[int] = None, - dropna: bool = True, ) -> Tuple[np.ndarray, Union[np.ndarray, ABCIndex]]: """ Encode the object as an enumerated type or categorical variable. @@ -540,8 +539,11 @@ def factorize( Parameters ---------- {values}{sort} - na_sentinel : int, default -1 - Value to mark "not found". + na_sentinel : int or None, default -1 + Value to mark "not found". If None, will not drop the NaN + from the uniques of the values. + + .. versionchanged:: 1.1.2 {size_hint}\ Returns @@ -619,6 +621,22 @@ def factorize( array([0, 0, 1]...) >>> uniques Index(['a', 'c'], dtype='object') + + If NaN is in the values, and we want to include NaN in the uniques of the + values, it can be achieved by setting ``na_sentinel=None``. + + >>> values = np.array([1, 2, 1, np.nan]) + >>> codes, uniques = pd.factorize(values) # default: na_sentinel=-1 + >>> codes + array([ 0, 1, 0, -1]) + >>> uniques + array([1., 2.]) + + >>> codes, uniques = pd.factorize(values, na_sentinel=None) + >>> codes + array([0, 1, 0, 2]) + >>> uniques + array([ 1., 2., nan]) """ # Implementation notes: This method is responsible for 3 things # 1.) coercing data to array-like (ndarray, Index, extension array) @@ -632,6 +650,13 @@ def factorize( values = _ensure_arraylike(values) original = values + # GH35667, if na_sentinel=None, we will not dropna NaNs from the uniques + # of values, assign na_sentinel=-1 to replace code value for NaN. + dropna = True + if na_sentinel is None: + na_sentinel = -1 + dropna = False + if is_extension_array_dtype(values.dtype): values = extract_array(values) codes, uniques = values.factorize(na_sentinel=na_sentinel) diff --git a/pandas/core/base.py b/pandas/core/base.py index b62ef668df5e1..1926803d8f04b 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1398,7 +1398,7 @@ def memory_usage(self, deep=False): """ ), ) - def factorize(self, sort=False, na_sentinel=-1): + def factorize(self, sort: bool = False, na_sentinel: Optional[int] = -1): return algorithms.factorize(self, sort=sort, na_sentinel=na_sentinel) _shared_docs[ diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 8239a792c65dd..272afe7335c6a 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -585,8 +585,13 @@ def _make_codes(self) -> None: codes = self.grouper.codes_info uniques = self.grouper.result_index else: + # GH35667, replace dropna=False with na_sentinel=None + if not self.dropna: + na_sentinel = None + else: + na_sentinel = -1 codes, uniques = algorithms.factorize( - self.grouper, sort=self.sort, dropna=self.dropna + self.grouper, sort=self.sort, na_sentinel=na_sentinel ) uniques = Index(uniques, name=self.name) self._codes = codes diff --git a/pandas/tests/base/test_factorize.py b/pandas/tests/base/test_factorize.py index 415a8b7e4362f..9fad9856d53cc 100644 --- a/pandas/tests/base/test_factorize.py +++ b/pandas/tests/base/test_factorize.py @@ -26,3 +26,16 @@ def test_factorize(index_or_series_obj, sort): tm.assert_numpy_array_equal(result_codes, expected_codes) tm.assert_index_equal(result_uniques, expected_uniques) + + +def test_series_factorize_na_sentinel_none(): + # GH35667 + values = np.array([1, 2, 1, np.nan]) + ser = pd.Series(values) + codes, uniques = ser.factorize(na_sentinel=None) + + expected_codes = np.array([0, 1, 0, 2], dtype="int64") + expected_uniques = pd.Index([1.0, 2.0, np.nan]) + + tm.assert_numpy_array_equal(codes, expected_codes) + tm.assert_index_equal(uniques, expected_uniques) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index a080bf0feaebc..326c926238f89 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -326,73 +326,47 @@ def test_factorize_na_sentinel(self, sort, na_sentinel, data, uniques): tm.assert_extension_array_equal(uniques, expected_uniques) @pytest.mark.parametrize( - "data, dropna, expected_codes, expected_uniques", + "data, expected_codes, expected_uniques", [ ( ["a", None, "b", "a"], - True, - np.array([0, -1, 1, 0], dtype=np.dtype("intp")), - np.array(["a", "b"], dtype=object), - ), - ( - ["a", np.nan, "b", "a"], - True, - np.array([0, -1, 1, 0], dtype=np.dtype("intp")), - np.array(["a", "b"], dtype=object), - ), - ( - ["a", None, "b", "a"], - False, np.array([0, 2, 1, 0], dtype=np.dtype("intp")), np.array(["a", "b", np.nan], dtype=object), ), ( ["a", np.nan, "b", "a"], - False, np.array([0, 2, 1, 0], dtype=np.dtype("intp")), np.array(["a", "b", np.nan], dtype=object), ), ], ) - def test_object_factorize_dropna( - self, data, dropna, expected_codes, expected_uniques + def test_object_factorize_na_sentinel_none( + self, data, expected_codes, expected_uniques ): - codes, uniques = algos.factorize(data, dropna=dropna) + codes, uniques = algos.factorize(data, na_sentinel=None) tm.assert_numpy_array_equal(uniques, expected_uniques) tm.assert_numpy_array_equal(codes, expected_codes) @pytest.mark.parametrize( - "data, dropna, expected_codes, expected_uniques", + "data, expected_codes, expected_uniques", [ ( [1, None, 1, 2], - True, - np.array([0, -1, 0, 1], dtype=np.dtype("intp")), - np.array([1, 2], dtype="O"), - ), - ( - [1, np.nan, 1, 2], - True, - np.array([0, -1, 0, 1], dtype=np.dtype("intp")), - np.array([1, 2], dtype=np.float64), - ), - ( - [1, None, 1, 2], - False, np.array([0, 2, 0, 1], dtype=np.dtype("intp")), np.array([1, 2, np.nan], dtype="O"), ), ( [1, np.nan, 1, 2], - False, np.array([0, 2, 0, 1], dtype=np.dtype("intp")), np.array([1, 2, np.nan], dtype=np.float64), ), ], ) - def test_int_factorize_dropna(self, data, dropna, expected_codes, expected_uniques): - codes, uniques = algos.factorize(data, dropna=dropna) + def test_int_factorize_na_sentinel_none( + self, data, expected_codes, expected_uniques + ): + codes, uniques = algos.factorize(data, na_sentinel=None) tm.assert_numpy_array_equal(uniques, expected_uniques) tm.assert_numpy_array_equal(codes, expected_codes)
Backport PR #35852: API: replace dropna=False option with na_sentinel=None in factorize
https://api.github.com/repos/pandas-dev/pandas/pulls/36071
2020-09-02T15:05:47Z
2020-09-02T16:37:26Z
2020-09-02T16:37:25Z
2020-09-02T16:37:26Z
TYP: statically define attributes in plotting._matplotlib.core
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 93ba9bd26630b..5270c7362d29f 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -66,16 +66,6 @@ def _kind(self): _layout_type = "vertical" _default_rot = 0 orientation: Optional[str] = None - _pop_attributes = [ - "label", - "style", - "mark_right", - "stacked", - ] - _attr_defaults = { - "mark_right": True, - "stacked": False, - } def __init__( self, @@ -165,9 +155,10 @@ def __init__( self.logx = kwds.pop("logx", False) self.logy = kwds.pop("logy", False) self.loglog = kwds.pop("loglog", False) - for attr in self._pop_attributes: - value = kwds.pop(attr, self._attr_defaults.get(attr, None)) - setattr(self, attr, value) + self.label = kwds.pop("label", None) + self.style = kwds.pop("style", None) + self.mark_right = kwds.pop("mark_right", True) + self.stacked = kwds.pop("stacked", False) self.ax = ax self.fig = fig
continuation of changes in #36016 pandas\plotting\_matplotlib\core.py:231: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:232: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:233: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:235: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:385: error: "MPLPlot" has no attribute "label"; maybe "ylabel" or "xlabel"? [attr-defined] pandas\plotting\_matplotlib\core.py:553: error: "MPLPlot" has no attribute "mark_right" [attr-defined] pandas\plotting\_matplotlib\core.py:732: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:733: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:735: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:738: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:739: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:741: error: "MPLPlot" has no attribute "style" [attr-defined] pandas\plotting\_matplotlib\core.py:1008: error: "ScatterPlot" has no attribute "label" [attr-defined] pandas\plotting\_matplotlib\core.py:1075: error: "LinePlot" has no attribute "stacked" [attr-defined] pandas\plotting\_matplotlib\core.py:1180: error: "LinePlot" has no attribute "stacked" [attr-defined] pandas\plotting\_matplotlib\core.py:1269: error: "AreaPlot" has no attribute "stacked" [attr-defined] pandas\plotting\_matplotlib\core.py:1351: error: "BarPlot" has no attribute "stacked" [attr-defined] pandas\plotting\_matplotlib\core.py:1427: error: "BarPlot" has no attribute "stacked" [attr-defined]
https://api.github.com/repos/pandas-dev/pandas/pulls/36068
2020-09-02T13:15:11Z
2020-09-02T15:42:30Z
2020-09-02T15:42:30Z
2020-09-02T15:49:20Z
TYP: update setup.cfg
diff --git a/setup.cfg b/setup.cfg index 2d1c8037636de..29c731848de8e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -321,9 +321,6 @@ check_untyped_defs=False [mypy-pandas.plotting._matplotlib.core] check_untyped_defs=False -[mypy-pandas.plotting._matplotlib.misc] -check_untyped_defs=False - [mypy-pandas.plotting._misc] check_untyped_defs=False
fixes in #36017 merged between generating config in #36012 and merging #36012
https://api.github.com/repos/pandas-dev/pandas/pulls/36067
2020-09-02T13:12:50Z
2020-09-02T15:41:40Z
2020-09-02T15:41:40Z
2020-09-02T15:47:31Z
BUG: groupby and agg on read-only array gives ValueError: buffer source array is read-only
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 9b1ad658d4666..be58aea5783bb 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -18,7 +18,7 @@ Fixed regressions - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) -- +- Fixed regression in :meth:`DataFrameGroupBy.agg` where a ``ValueError: buffer source array is read-only`` would be raised when the underlying array is read-only (:issue:`36014`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 38cb973d6dde9..a83634aad3ce2 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -229,7 +229,7 @@ def group_cumprod_float64(float64_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_cumsum(numeric[:, :] out, - numeric[:, :] values, + ndarray[numeric, ndim=2] values, const int64_t[:] labels, int ngroups, is_datetimelike, @@ -472,7 +472,7 @@ ctypedef fused complexfloating_t: @cython.boundscheck(False) def _group_add(complexfloating_t[:, :] out, int64_t[:] counts, - complexfloating_t[:, :] values, + ndarray[complexfloating_t, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=0): """ @@ -483,8 +483,9 @@ def _group_add(complexfloating_t[:, :] out, complexfloating_t val, count complexfloating_t[:, :] sumx int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) - if len(values) != len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -530,7 +531,7 @@ group_add_complex128 = _group_add['double complex'] @cython.boundscheck(False) def _group_prod(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=0): """ @@ -541,8 +542,9 @@ def _group_prod(floating[:, :] out, floating val, count floating[:, :] prodx int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) - if not len(values) == len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -582,7 +584,7 @@ group_prod_float64 = _group_prod['double'] @cython.cdivision(True) def _group_var(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=-1, int64_t ddof=1): @@ -591,10 +593,11 @@ def _group_var(floating[:, :] out, floating val, ct, oldmean floating[:, :] mean int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) assert min_count == -1, "'min_count' only used in add and prod" - if not len(values) == len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -639,7 +642,7 @@ group_var_float64 = _group_var['double'] @cython.boundscheck(False) def _group_mean(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=-1): cdef: @@ -647,10 +650,11 @@ def _group_mean(floating[:, :] out, floating val, count floating[:, :] sumx int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) assert min_count == -1, "'min_count' only used in add and prod" - if not len(values) == len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -689,7 +693,7 @@ group_mean_float64 = _group_mean['double'] @cython.boundscheck(False) def _group_ohlc(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=-1): """ @@ -740,7 +744,7 @@ group_ohlc_float64 = _group_ohlc['double'] @cython.boundscheck(False) @cython.wraparound(False) def group_quantile(ndarray[float64_t] out, - numeric[:] values, + ndarray[numeric, ndim=1] values, ndarray[int64_t] labels, ndarray[uint8_t] mask, float64_t q, @@ -1072,7 +1076,7 @@ def group_nth(rank_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_rank(float64_t[:, :] out, - rank_t[:, :] values, + ndarray[rank_t, ndim=2] values, const int64_t[:] labels, int ngroups, bint is_datetimelike, object ties_method="average", @@ -1424,7 +1428,7 @@ def group_min(groupby_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_cummin(groupby_t[:, :] out, - groupby_t[:, :] values, + ndarray[groupby_t, ndim=2] values, const int64_t[:] labels, int ngroups, bint is_datetimelike): @@ -1484,7 +1488,7 @@ def group_cummin(groupby_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_cummax(groupby_t[:, :] out, - groupby_t[:, :] values, + ndarray[groupby_t, ndim=2] values, const int64_t[:] labels, int ngroups, bint is_datetimelike): diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index 5ddda264642de..87ebd8b5a27fb 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -236,3 +236,44 @@ def test_cython_with_timestamp_and_nat(op, data): result = df.groupby("a").aggregate(op) tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize( + "agg", + [ + "min", + "max", + "count", + "sum", + "prod", + "var", + "mean", + "median", + "ohlc", + "cumprod", + "cumsum", + "shift", + "any", + "all", + "quantile", + "first", + "last", + "rank", + "cummin", + "cummax", + ], +) +def test_read_only_buffer_source_agg(agg): + # https://github.com/pandas-dev/pandas/issues/36014 + df = DataFrame( + { + "sepal_length": [5.1, 4.9, 4.7, 4.6, 5.0], + "species": ["setosa", "setosa", "setosa", "setosa", "setosa"], + } + ) + df._mgr.blocks[0].values.flags.writeable = False + + result = df.groupby(["species"]).agg({"sepal_length": agg}) + expected = df.copy().groupby(["species"]).agg({"sepal_length": agg}) + + tm.assert_equal(result, expected)
- [x] closes #36014 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry I found multiple aggregate functions that were failing for a read-only array. I applied the change suggested in #36014 to all of them. A couple of questions. 1. I had to add the Py_ssize_t cdefs to suppress the error below for `len(values) != len(labels)`. Let me know if there is another preferred way of doing it. ``` error: comparison of integer expressions of different signedness: ‘Py_ssize_t’ {aka ‘long int’} and ‘size_t’ {aka ‘long unsigned int’} [-Werror=sign-compare] ``` 2. I see some functions don't have the `len(values) != len(labels)` check. Should it be there in all the functions?
https://api.github.com/repos/pandas-dev/pandas/pulls/36061
2020-09-02T07:00:58Z
2020-09-04T14:28:16Z
2020-09-04T14:28:16Z
2020-09-05T08:26:11Z
CLN remove unnecessary trailing commas in groupby tests
diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index 29e65e938f6f9..c4266996748c2 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -57,7 +57,7 @@ def func_numba(values, index): func_numba = numba.jit(func_numba) data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} grouped = data.groupby(0) @@ -90,7 +90,7 @@ def func_2(values, index): func_2 = numba.jit(func_2) data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} grouped = data.groupby(0) @@ -121,7 +121,7 @@ def func_1(values, index): return np.mean(values) - 3.4 data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) grouped = data.groupby(0) expected = grouped.agg(func_1, engine="numba") @@ -142,7 +142,7 @@ def func_1(values, index): ) def test_multifunc_notimplimented(agg_func): data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) grouped = data.groupby(0) with pytest.raises(NotImplementedError, match="Numba engine can"): diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index a1dcb28a32c6c..3183305fe2933 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -946,9 +946,7 @@ def fct(group): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize( - "function", [lambda gr: gr.index, lambda gr: gr.index + 1 - 1], -) +@pytest.mark.parametrize("function", [lambda gr: gr.index, lambda gr: gr.index + 1 - 1]) def test_apply_function_index_return(function): # GH: 22541 df = pd.DataFrame([1, 2, 2, 2, 1, 2, 3, 1, 3, 1], columns=["id"]) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 13a32e285e70a..cbf9e720ecfd0 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -17,7 +17,7 @@ def cartesian_product_for_groupers(result, args, names, fill_value=np.NaN): - """ Reindex to a cartesian production for the groupers, + """Reindex to a cartesian production for the groupers, preserving the nature (Categorical) of each grouper """ diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py index adf62c4723526..d1501111cb22b 100644 --- a/pandas/tests/groupby/test_groupby_dropna.py +++ b/pandas/tests/groupby/test_groupby_dropna.py @@ -246,9 +246,7 @@ def test_groupby_dropna_multi_index_dataframe_agg(dropna, tuples, outputs): (pd.Period("2020-01-01"), pd.Period("2020-02-01")), ], ) -@pytest.mark.parametrize( - "dropna, values", [(True, [12, 3]), (False, [12, 3, 6],)], -) +@pytest.mark.parametrize("dropna, values", [(True, [12, 3]), (False, [12, 3, 6])]) def test_groupby_dropna_datetime_like_data( dropna, values, datetime1, datetime2, unique_nulls_fixture, unique_nulls_fixture2 ): diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py index 7271911c5f80f..cc7a79e976513 100644 --- a/pandas/tests/groupby/test_groupby_subclass.py +++ b/pandas/tests/groupby/test_groupby_subclass.py @@ -51,9 +51,7 @@ def test_groupby_preserves_subclass(obj, groupby_func): tm.assert_series_equal(result1, result2) -@pytest.mark.parametrize( - "obj", [DataFrame, tm.SubclassedDataFrame], -) +@pytest.mark.parametrize("obj", [DataFrame, tm.SubclassedDataFrame]) def test_groupby_resample_preserves_subclass(obj): # GH28330 -- preserve subclass through groupby.resample() diff --git a/pandas/tests/groupby/test_size.py b/pandas/tests/groupby/test_size.py index 9cff8b966dad0..ba27e5a24ba00 100644 --- a/pandas/tests/groupby/test_size.py +++ b/pandas/tests/groupby/test_size.py @@ -53,7 +53,7 @@ def test_size_on_categorical(as_index): result = df.groupby(["A", "B"], as_index=as_index).size() expected = DataFrame( - [[1, 1, 1], [1, 2, 0], [2, 1, 0], [2, 2, 1]], columns=["A", "B", "size"], + [[1, 1, 1], [1, 2, 0], [2, 1, 0], [2, 2, 1]], columns=["A", "B", "size"] ) expected["A"] = expected["A"].astype("category") if as_index: diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 84fd7a1bdfb05..4ccbc6a65fd88 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -780,6 +780,6 @@ def test_grouper_period_index(self): result = period_series.groupby(period_series.index.month).sum() expected = pd.Series( - range(0, periods), index=Index(range(1, periods + 1), name=index.name), + range(0, periods), index=Index(range(1, periods + 1), name=index.name) ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_numba.py b/pandas/tests/groupby/transform/test_numba.py index ee482571e644d..87723cd7c8f50 100644 --- a/pandas/tests/groupby/transform/test_numba.py +++ b/pandas/tests/groupby/transform/test_numba.py @@ -56,7 +56,7 @@ def func(values, index): func = numba.jit(func) data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} grouped = data.groupby(0) @@ -89,7 +89,7 @@ def func_2(values, index): func_2 = numba.jit(func_2) data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} grouped = data.groupby(0) @@ -120,7 +120,7 @@ def func_1(values, index): return values + 1 data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) grouped = data.groupby(0) expected = grouped.transform(func_1, engine="numba")
xref #35925
https://api.github.com/repos/pandas-dev/pandas/pulls/36059
2020-09-02T01:32:16Z
2020-09-02T16:19:49Z
2020-09-02T16:19:49Z
2020-09-02T16:20:00Z
Comma cleanup for #35925
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 52a1e3aae9058..b0ba0d991c9b0 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -86,11 +86,7 @@ def wrapper(x): result0 = f(axis=0, skipna=False) result1 = f(axis=1, skipna=False) tm.assert_series_equal( - result0, - frame.apply(wrapper), - check_dtype=check_dtype, - rtol=rtol, - atol=atol, + result0, frame.apply(wrapper), check_dtype=check_dtype, rtol=rtol, atol=atol ) # HACK: win32 tm.assert_series_equal( @@ -116,7 +112,7 @@ def wrapper(x): if opname in ["sum", "prod"]: expected = frame.apply(skipna_wrapper, axis=1) tm.assert_series_equal( - result1, expected, check_dtype=False, rtol=rtol, atol=atol, + result1, expected, check_dtype=False, rtol=rtol, atol=atol ) # check dtypes diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index c8f5b2b0f6364..0d1004809f7f1 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -932,7 +932,7 @@ def test_constructor_mrecarray(self): # from GH3479 assert_fr_equal = functools.partial( - tm.assert_frame_equal, check_index_type=True, check_column_type=True, + tm.assert_frame_equal, check_index_type=True, check_column_type=True ) arrays = [ ("float", np.array([1.5, 2.0])), diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 6a8f1e7c1aca2..d80ebaa09b6a8 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -417,7 +417,7 @@ def test_unstack_mixed_type_name_in_multiindex( result = df.unstack(unstack_idx) expected = pd.DataFrame( - expected_values, columns=expected_columns, index=expected_index, + expected_values, columns=expected_columns, index=expected_index ) tm.assert_frame_equal(result, expected) @@ -807,7 +807,7 @@ def test_unstack_multi_level_cols(self): [["B", "C"], ["B", "D"]], names=["c1", "c2"] ), index=pd.MultiIndex.from_tuples( - [[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"], + [[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"] ), ) assert df.unstack(["i2", "i1"]).columns.names[-2:] == ["i2", "i1"] diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 4d0f1a326225d..8898619e374ab 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -123,7 +123,7 @@ (pd.DataFrame, frame_data, operator.methodcaller("sort_index")), (pd.DataFrame, frame_data, operator.methodcaller("nlargest", 1, "A")), (pd.DataFrame, frame_data, operator.methodcaller("nsmallest", 1, "A")), - (pd.DataFrame, frame_mi_data, operator.methodcaller("swaplevel"),), + (pd.DataFrame, frame_mi_data, operator.methodcaller("swaplevel")), pytest.param( ( pd.DataFrame, @@ -178,7 +178,7 @@ marks=not_implemented_mark, ), pytest.param( - (pd.DataFrame, frame_mi_data, operator.methodcaller("unstack"),), + (pd.DataFrame, frame_mi_data, operator.methodcaller("unstack")), marks=not_implemented_mark, ), pytest.param( @@ -317,7 +317,7 @@ marks=not_implemented_mark, ), pytest.param( - (pd.Series, ([1, 2],), operator.methodcaller("squeeze")), + (pd.Series, ([1, 2],), operator.methodcaller("squeeze")) # marks=not_implemented_mark, ), (pd.Series, ([1, 2],), operator.methodcaller("rename_axis", index="a")), @@ -733,9 +733,7 @@ def test_timedelta_property(attr): assert result.attrs == {"a": 1} -@pytest.mark.parametrize( - "method", [operator.methodcaller("total_seconds")], -) +@pytest.mark.parametrize("method", [operator.methodcaller("total_seconds")]) @not_implemented_mark def test_timedelta_methods(method): s = pd.Series(pd.timedelta_range("2000", periods=4)) diff --git a/pandas/tests/generic/test_to_xarray.py b/pandas/tests/generic/test_to_xarray.py index ab56a752f7e90..a85d7ddc1ea53 100644 --- a/pandas/tests/generic/test_to_xarray.py +++ b/pandas/tests/generic/test_to_xarray.py @@ -47,9 +47,7 @@ def test_to_xarray_index_types(self, index): expected = df.copy() expected["f"] = expected["f"].astype(object) expected.columns.name = None - tm.assert_frame_equal( - result.to_dataframe(), expected, - ) + tm.assert_frame_equal(result.to_dataframe(), expected) @td.skip_if_no("xarray", min_version="0.7.0") def test_to_xarray(self): diff --git a/pandas/tests/groupby/aggregate/test_numba.py b/pandas/tests/groupby/aggregate/test_numba.py index 29e65e938f6f9..c4266996748c2 100644 --- a/pandas/tests/groupby/aggregate/test_numba.py +++ b/pandas/tests/groupby/aggregate/test_numba.py @@ -57,7 +57,7 @@ def func_numba(values, index): func_numba = numba.jit(func_numba) data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} grouped = data.groupby(0) @@ -90,7 +90,7 @@ def func_2(values, index): func_2 = numba.jit(func_2) data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} grouped = data.groupby(0) @@ -121,7 +121,7 @@ def func_1(values, index): return np.mean(values) - 3.4 data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) grouped = data.groupby(0) expected = grouped.agg(func_1, engine="numba") @@ -142,7 +142,7 @@ def func_1(values, index): ) def test_multifunc_notimplimented(agg_func): data = DataFrame( - {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1], + {0: ["a", "a", "b", "b", "a"], 1: [1.0, 2.0, 3.0, 4.0, 5.0]}, columns=[0, 1] ) grouped = data.groupby(0) with pytest.raises(NotImplementedError, match="Numba engine can"): diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index a1dcb28a32c6c..3183305fe2933 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -946,9 +946,7 @@ def fct(group): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize( - "function", [lambda gr: gr.index, lambda gr: gr.index + 1 - 1], -) +@pytest.mark.parametrize("function", [lambda gr: gr.index, lambda gr: gr.index + 1 - 1]) def test_apply_function_index_return(function): # GH: 22541 df = pd.DataFrame([1, 2, 2, 2, 1, 2, 3, 1, 3, 1], columns=["id"]) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 13a32e285e70a..711daf7fe415d 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -17,7 +17,7 @@ def cartesian_product_for_groupers(result, args, names, fill_value=np.NaN): - """ Reindex to a cartesian production for the groupers, + """Reindex to a cartesian production for the groupers, preserving the nature (Categorical) of each grouper """ @@ -1449,7 +1449,7 @@ def test_groupby_agg_categorical_columns(func, expected_values): result = df.groupby("groups").agg(func) expected = pd.DataFrame( - {"value": expected_values}, index=pd.Index([0, 1, 2], name="groups"), + {"value": expected_values}, index=pd.Index([0, 1, 2], name="groups") ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 8c51ebf89f5c0..bd7609551a6bc 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -676,7 +676,7 @@ def test_ops_not_as_index(reduction_func): if reduction_func in ("corrwith",): pytest.skip("Test not applicable") - if reduction_func in ("nth", "ngroup",): + if reduction_func in ("nth", "ngroup"): pytest.skip("Skip until behavior is determined (GH #5755)") df = DataFrame(np.random.randint(0, 5, size=(100, 2)), columns=["a", "b"]) diff --git a/pandas/tests/groupby/test_groupby_dropna.py b/pandas/tests/groupby/test_groupby_dropna.py index adf62c4723526..d1501111cb22b 100644 --- a/pandas/tests/groupby/test_groupby_dropna.py +++ b/pandas/tests/groupby/test_groupby_dropna.py @@ -246,9 +246,7 @@ def test_groupby_dropna_multi_index_dataframe_agg(dropna, tuples, outputs): (pd.Period("2020-01-01"), pd.Period("2020-02-01")), ], ) -@pytest.mark.parametrize( - "dropna, values", [(True, [12, 3]), (False, [12, 3, 6],)], -) +@pytest.mark.parametrize("dropna, values", [(True, [12, 3]), (False, [12, 3, 6])]) def test_groupby_dropna_datetime_like_data( dropna, values, datetime1, datetime2, unique_nulls_fixture, unique_nulls_fixture2 ): diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py index 7271911c5f80f..cc7a79e976513 100644 --- a/pandas/tests/groupby/test_groupby_subclass.py +++ b/pandas/tests/groupby/test_groupby_subclass.py @@ -51,9 +51,7 @@ def test_groupby_preserves_subclass(obj, groupby_func): tm.assert_series_equal(result1, result2) -@pytest.mark.parametrize( - "obj", [DataFrame, tm.SubclassedDataFrame], -) +@pytest.mark.parametrize("obj", [DataFrame, tm.SubclassedDataFrame]) def test_groupby_resample_preserves_subclass(obj): # GH28330 -- preserve subclass through groupby.resample() diff --git a/pandas/tests/groupby/test_size.py b/pandas/tests/groupby/test_size.py index 9cff8b966dad0..ba27e5a24ba00 100644 --- a/pandas/tests/groupby/test_size.py +++ b/pandas/tests/groupby/test_size.py @@ -53,7 +53,7 @@ def test_size_on_categorical(as_index): result = df.groupby(["A", "B"], as_index=as_index).size() expected = DataFrame( - [[1, 1, 1], [1, 2, 0], [2, 1, 0], [2, 2, 1]], columns=["A", "B", "size"], + [[1, 1, 1], [1, 2, 0], [2, 1, 0], [2, 2, 1]], columns=["A", "B", "size"] ) expected["A"] = expected["A"].astype("category") if as_index:
- [x] pandas/tests/generic/test_finalize.py - [x] pandas/tests/generic/test_to_xarray.py - [x] pandas/tests/groupby/aggregate/test_numba.py - [x] pandas/tests/groupby/test_apply.py - [x] pandas/tests/groupby/test_categorical.py - [x] pandas/tests/groupby/test_groupby.py - [x] pandas/tests/groupby/test_groupby_dropna.py - [x] pandas/tests/groupby/test_groupby_subclass.py
https://api.github.com/repos/pandas-dev/pandas/pulls/36058
2020-09-02T01:29:17Z
2020-09-02T13:28:45Z
2020-09-02T13:28:45Z
2020-09-02T13:28:56Z
CLN remove unnecessary trailing commas
diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py index 50b5fe8e6f6b9..72ef7ea6bf8ca 100644 --- a/pandas/tests/arithmetic/test_interval.py +++ b/pandas/tests/arithmetic/test_interval.py @@ -156,9 +156,7 @@ def test_compare_scalar_other(self, op, array, other): expected = self.elementwise_comparison(op, array, other) tm.assert_numpy_array_equal(result, expected) - def test_compare_list_like_interval( - self, op, array, interval_constructor, - ): + def test_compare_list_like_interval(self, op, array, interval_constructor): # same endpoints other = interval_constructor(array.left, array.right) result = op(array, other) diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 484f83deb0f55..ecac08ffe3ba2 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -99,7 +99,7 @@ class TestNumericArraylikeArithmeticWithDatetimeLike: # TODO: also check name retentention @pytest.mark.parametrize("box_cls", [np.array, pd.Index, pd.Series]) @pytest.mark.parametrize( - "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype), + "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype) ) def test_mul_td64arr(self, left, box_cls): # GH#22390 @@ -119,7 +119,7 @@ def test_mul_td64arr(self, left, box_cls): # TODO: also check name retentention @pytest.mark.parametrize("box_cls", [np.array, pd.Index, pd.Series]) @pytest.mark.parametrize( - "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype), + "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype) ) def test_div_td64arr(self, left, box_cls): # GH#22390 diff --git a/pandas/tests/arrays/boolean/test_logical.py b/pandas/tests/arrays/boolean/test_logical.py index e79262e1b7934..8ed1c27087b02 100644 --- a/pandas/tests/arrays/boolean/test_logical.py +++ b/pandas/tests/arrays/boolean/test_logical.py @@ -205,9 +205,7 @@ def test_kleene_xor_scalar(self, other, expected): a, pd.array([True, False, None], dtype="boolean") ) - @pytest.mark.parametrize( - "other", [True, False, pd.NA, [True, False, None] * 3], - ) + @pytest.mark.parametrize("other", [True, False, pd.NA, [True, False, None] * 3]) def test_no_masked_assumptions(self, other, all_logical_operators): # The logical operations should not assume that masked values are False! a = pd.arrays.BooleanArray(
#35925 - pandas/tests/arithmetic/test_interval.py - pandas/tests/arithmetic/test_numeric.py - pandas/tests/arrays/boolean/test_logical.py I am not including "pandas/io/sas/sas_xport.py" and "pandas/io/stata.py" as there is a PR already open for those.
https://api.github.com/repos/pandas-dev/pandas/pulls/36057
2020-09-01T23:19:03Z
2020-09-02T16:14:01Z
2020-09-02T16:14:01Z
2020-09-02T16:14:07Z
STY/WIP: check for private imports/lookups
diff --git a/Makefile b/Makefile index 4a9a48992f92f..b915d8840cd8d 100644 --- a/Makefile +++ b/Makefile @@ -32,3 +32,9 @@ check: --included-file-extensions="py" \ --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored \ pandas/ + + python3 scripts/validate_unwanted_patterns.py \ + --validation-type="private_import_across_module" \ + --included-file-extensions="py" \ + --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored,doc/ + pandas/ diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 875f1dbb83ce3..54aa830379c07 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -116,11 +116,19 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then fi RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Check for use of private module attribute access' ; echo $MSG + MSG='Check for import of private attributes across modules' ; echo $MSG if [[ "$GITHUB_ACTIONS" == "true" ]]; then - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored --format="##[error]{source_path}:{line_number}:{msg}" pandas/ + $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_import_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored --format="##[error]{source_path}:{line_number}:{msg}" pandas/ else - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored pandas/ + $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_import_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored pandas/ + fi + RET=$(($RET + $?)) ; echo $MSG "DONE" + + MSG='Check for use of private functions across modules' ; echo $MSG + if [[ "$GITHUB_ACTIONS" == "true" ]]; then + $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored,doc/ --format="##[error]{source_path}:{line_number}:{msg}" pandas/ + else + $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored,doc/ pandas/ fi RET=$(($RET + $?)) ; echo $MSG "DONE" diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 6302b48cb1978..b013246e724de 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -54,7 +54,7 @@ from pandas.core import missing, nanops, ops from pandas.core.algorithms import checked_add_with_arr, unique1d, value_counts -from pandas.core.arrays._mixins import _T, NDArrayBackedExtensionArray +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.arrays.base import ExtensionOpsMixin import pandas.core.common as com from pandas.core.construction import array, extract_array @@ -472,11 +472,11 @@ class DatetimeLikeArrayMixin( def _ndarray(self) -> np.ndarray: return self._data - def _from_backing_data(self: _T, arr: np.ndarray) -> _T: + def _from_backing_data( + self: DatetimeLikeArrayT, arr: np.ndarray + ) -> DatetimeLikeArrayT: # Note: we do not retain `freq` - return type(self)._simple_new( # type: ignore[attr-defined] - arr, dtype=self.dtype - ) + return type(self)._simple_new(arr, dtype=self.dtype) # ------------------------------------------------------------------ diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index d83ff91a1315f..dc08e018397bc 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -106,7 +106,7 @@ def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: [t.numpy_dtype if isinstance(t, BaseMaskedDtype) else t for t in dtypes], [] ) if np.issubdtype(np_dtype, np.integer): - return _dtypes[str(np_dtype)] + return STR_TO_DTYPE[str(np_dtype)] return None def __from_arrow__( @@ -214,7 +214,7 @@ def coerce_to_array( if not issubclass(type(dtype), _IntegerDtype): try: - dtype = _dtypes[str(np.dtype(dtype))] + dtype = STR_TO_DTYPE[str(np.dtype(dtype))] except KeyError as err: raise ValueError(f"invalid dtype specified {dtype}") from err @@ -354,7 +354,7 @@ class IntegerArray(BaseMaskedArray): @cache_readonly def dtype(self) -> _IntegerDtype: - return _dtypes[str(self._data.dtype)] + return STR_TO_DTYPE[str(self._data.dtype)] def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): if not (isinstance(values, np.ndarray) and values.dtype.kind in ["i", "u"]): @@ -735,7 +735,7 @@ class UInt64Dtype(_IntegerDtype): __doc__ = _dtype_docstring.format(dtype="uint64") -_dtypes: Dict[str, _IntegerDtype] = { +STR_TO_DTYPE: Dict[str, _IntegerDtype] = { "int8": Int8Dtype(), "int16": Int16Dtype(), "int32": Int32Dtype(), diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index ba1b0b075936d..64ccc0be0a25d 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1151,9 +1151,11 @@ def convert_dtypes( target_int_dtype = "Int64" if is_integer_dtype(input_array.dtype): - from pandas.core.arrays.integer import _dtypes + from pandas.core.arrays.integer import STR_TO_DTYPE - inferred_dtype = _dtypes.get(input_array.dtype.name, target_int_dtype) + inferred_dtype = STR_TO_DTYPE.get( + input_array.dtype.name, target_int_dtype + ) if not is_integer_dtype(input_array.dtype) and is_numeric_dtype( input_array.dtype ): diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 1e3e56f4ff09f..8a55d438cf8d4 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -459,7 +459,7 @@ def f(self): @contextmanager -def group_selection_context(groupby: "_GroupBy"): +def group_selection_context(groupby: "BaseGroupBy"): """ Set / reset the group_selection_context. """ @@ -479,7 +479,7 @@ def group_selection_context(groupby: "_GroupBy"): ] -class _GroupBy(PandasObject, SelectionMixin, Generic[FrameOrSeries]): +class BaseGroupBy(PandasObject, SelectionMixin, Generic[FrameOrSeries]): _group_selection = None _apply_allowlist: FrozenSet[str] = frozenset() @@ -1212,7 +1212,7 @@ def _apply_filter(self, indices, dropna): OutputFrameOrSeries = TypeVar("OutputFrameOrSeries", bound=NDFrame) -class GroupBy(_GroupBy[FrameOrSeries]): +class GroupBy(BaseGroupBy[FrameOrSeries]): """ Class for grouping and aggregating relational data. diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index f0b80c2852bd5..f269495f6011a 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -312,9 +312,9 @@ def _is_dates_only(self) -> bool: ------- bool """ - from pandas.io.formats.format import _is_dates_only + from pandas.io.formats.format import is_dates_only - return self.tz is None and _is_dates_only(self._values) + return self.tz is None and is_dates_only(self._values) def __reduce__(self): diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 7b5154756e613..44848e4d43909 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -26,7 +26,12 @@ from pandas.core.generic import NDFrame, _shared_docs from pandas.core.groupby.base import GroupByMixin from pandas.core.groupby.generic import SeriesGroupBy -from pandas.core.groupby.groupby import GroupBy, _GroupBy, _pipe_template, get_groupby +from pandas.core.groupby.groupby import ( + BaseGroupBy, + GroupBy, + _pipe_template, + get_groupby, +) from pandas.core.groupby.grouper import Grouper from pandas.core.groupby.ops import BinGrouper from pandas.core.indexes.api import Index @@ -40,7 +45,7 @@ _shared_docs_kwargs: Dict[str, str] = dict() -class Resampler(_GroupBy, ShallowMixin): +class Resampler(BaseGroupBy, ShallowMixin): """ Class for resampling datetimelike data, a groupby-like operation. See aggregate, transform, and apply functions on this object. diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 2bd36d8bff155..4282cb41c4e91 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -15,7 +15,7 @@ import pandas.core.common as common from pandas.core.window.common import _doc_template, _shared_docs, zsqrt -from pandas.core.window.rolling import _Rolling, flex_binary_moment +from pandas.core.window.rolling import RollingMixin, flex_binary_moment _bias_template = """ Parameters @@ -60,7 +60,7 @@ def get_center_of_mass( return float(comass) -class ExponentialMovingWindow(_Rolling): +class ExponentialMovingWindow(RollingMixin): r""" Provide exponential weighted (EW) functions. diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index ce4ab2f98c23d..46e002324ec75 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -5,10 +5,10 @@ from pandas.util._decorators import Appender, Substitution, doc from pandas.core.window.common import WindowGroupByMixin, _doc_template, _shared_docs -from pandas.core.window.rolling import _Rolling_and_Expanding +from pandas.core.window.rolling import RollingAndExpandingMixin -class Expanding(_Rolling_and_Expanding): +class Expanding(RollingAndExpandingMixin): """ Provide expanding transformations. diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 5a7482076903c..648ab4d25be83 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1214,13 +1214,13 @@ def std(self, ddof=1, *args, **kwargs): return zsqrt(self.var(ddof=ddof, name="std", **kwargs)) -class _Rolling(_Window): +class RollingMixin(_Window): @property def _constructor(self): return Rolling -class _Rolling_and_Expanding(_Rolling): +class RollingAndExpandingMixin(RollingMixin): _shared_docs["count"] = dedent( r""" @@ -1917,7 +1917,7 @@ def _get_corr(a, b): ) -class Rolling(_Rolling_and_Expanding): +class Rolling(RollingAndExpandingMixin): @cache_readonly def is_datetimelike(self) -> bool: return isinstance( diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6781d98ded41d..77f2a53fc7fab 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1586,7 +1586,7 @@ def format_percentiles( return [i + "%" for i in out] -def _is_dates_only( +def is_dates_only( values: Union[np.ndarray, DatetimeArray, Index, DatetimeIndex] ) -> bool: # return a boolean if we are only dates (and don't have a timezone) @@ -1658,8 +1658,8 @@ def get_format_datetime64_from_values( # only accepts 1D values values = values.ravel() - is_dates_only = _is_dates_only(values) - if is_dates_only: + ido = is_dates_only(values) + if ido: return date_format or "%Y-%m-%d" return date_format @@ -1668,9 +1668,9 @@ class Datetime64TZFormatter(Datetime64Formatter): def _format_strings(self) -> List[str]: """ we by definition have a TZ """ values = self.values.astype(object) - is_dates_only = _is_dates_only(values) + ido = is_dates_only(values) formatter = self.formatter or get_format_datetime64( - is_dates_only, date_format=self.date_format + ido, date_format=self.date_format ) fmt_values = [formatter(x) for x in values] diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py index 2add2b8c62a4e..4a0e859535215 100755 --- a/scripts/validate_unwanted_patterns.py +++ b/scripts/validate_unwanted_patterns.py @@ -18,6 +18,39 @@ import tokenize from typing import IO, Callable, FrozenSet, Iterable, List, Set, Tuple +PRIVATE_IMPORTS_TO_IGNORE: Set[str] = { + "_extension_array_shared_docs", + "_index_shared_docs", + "_interval_shared_docs", + "_merge_doc", + "_shared_docs", + "_apply_docs", + "_new_Index", + "_new_PeriodIndex", + "_doc_template", + "_agg_template", + "_pipe_template", + "_get_version", + "__main__", + "_transform_template", + "_arith_doc_FRAME", + "_flex_comp_doc_FRAME", + "_make_flex_doc", + "_op_descriptions", + "_IntegerDtype", + "_use_inf_as_na", + "_get_plot_backend", + "_matplotlib", + "_arrow_utils", + "_registry", + "_get_offset", # TODO: remove after get_offset deprecation enforced + "_test_parse_iso8601", + "_json_normalize", # TODO: remove after deprecation is enforced + "_testing", + "_test_decorators", + "__version__", # check np.__version__ in compat.numpy.function +} + def _get_literal_string_prefix_len(token_string: str) -> int: """ @@ -164,6 +197,36 @@ def private_function_across_module(file_obj: IO[str]) -> Iterable[Tuple[int, str yield (node.lineno, f"Private function '{module_name}.{function_name}'") +def private_import_across_module(file_obj: IO[str]) -> Iterable[Tuple[int, str]]: + """ + Checking that a private function is not imported across modules. + Parameters + ---------- + file_obj : IO + File-like object containing the Python code to validate. + Yields + ------ + line_number : int + Line number of import statement, that imports the private function. + msg : str + Explenation of the error. + """ + contents = file_obj.read() + tree = ast.parse(contents) + + for node in ast.walk(tree): + if not (isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom)): + continue + + for module in node.names: + module_name = module.name.split(".")[-1] + if module_name in PRIVATE_IMPORTS_TO_IGNORE: + continue + + if module_name.startswith("_"): + yield (node.lineno, f"Import of internal function {repr(module_name)}") + + def strings_to_concatenate(file_obj: IO[str]) -> Iterable[Tuple[int, str]]: """ This test case is necessary after 'Black' (https://github.com/psf/black), @@ -419,6 +482,7 @@ def main( available_validation_types: List[str] = [ "bare_pytest_raises", "private_function_across_module", + "private_import_across_module", "strings_to_concatenate", "strings_with_wrong_placed_whitespace", ] @@ -449,7 +513,7 @@ def main( parser.add_argument( "--excluded-file-paths", default="asv_bench/env", - help="Comma separated file extensions to check.", + help="Comma separated file paths to exclude.", ) args = parser.parse_args()
Mostly this is an amalgam of #33479, #33394, and #33393.
https://api.github.com/repos/pandas-dev/pandas/pulls/36055
2020-09-01T22:20:34Z
2020-09-12T21:30:33Z
2020-09-12T21:30:33Z
2020-09-12T21:34:28Z
BUG: Don't raise when constructing Series from ordered set
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index c6cfcc6730112..b8f6d0e52d058 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -35,6 +35,7 @@ Bug fixes - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) - Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should be ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) +- Bug in :class:`Series` constructor incorrectly raising a ``TypeError`` when passed an ordered set (:issue:`36044`) - Bug in :meth:`Series.dt.isocalendar` and :meth:`DatetimeIndex.isocalendar` that returned incorrect year for certain dates (:issue:`36032`) - Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) - Bug in :meth:`DataFrame.corr` causing subsequent indexing lookups to be incorrect (:issue:`35882`) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 9d6c2789af25b..3812c306b8eb4 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -438,7 +438,12 @@ def sanitize_array( subarr = subarr.copy() return subarr - elif isinstance(data, (list, tuple)) and len(data) > 0: + elif isinstance(data, (list, tuple, abc.Set, abc.ValuesView)) and len(data) > 0: + if isinstance(data, set): + # Raise only for unordered sets, e.g., not for dict_keys + raise TypeError("Set type is unordered") + data = list(data) + if dtype is not None: subarr = _try_cast(data, dtype, copy, raise_cast_failure) else: @@ -450,8 +455,6 @@ def sanitize_array( # GH#16804 arr = np.arange(data.start, data.stop, data.step, dtype="int64") subarr = _try_cast(arr, dtype, copy, raise_cast_failure) - elif isinstance(data, abc.Set): - raise TypeError("Set type is unordered") elif lib.is_scalar(data) and index is not None and dtype is not None: data = maybe_cast_to_datetime(data, dtype) if not lib.is_scalar(data): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index bcf7039ec9039..ce078059479b4 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1464,3 +1464,13 @@ def test_constructor_sparse_datetime64(self, values): arr = pd.arrays.SparseArray(values, dtype=dtype) expected = pd.Series(arr) tm.assert_series_equal(result, expected) + + def test_construction_from_ordered_collection(self): + # https://github.com/pandas-dev/pandas/issues/36044 + result = Series({"a": 1, "b": 2}.keys()) + expected = Series(["a", "b"]) + tm.assert_series_equal(result, expected) + + result = Series({"a": 1, "b": 2}.values()) + expected = Series([1, 2]) + tm.assert_series_equal(result, expected)
- [x] closes #36044 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This may or may not be a regression, since before the change that caused the error to be raised the output was still wrong (same bug that motivated the initial patch): ```python In [2]: keys = {'a': 1, 'b': 2}.keys() In [3]: pd.Series(keys) Out[3]: 0 (a, b) 1 (a, b) dtype: object ```
https://api.github.com/repos/pandas-dev/pandas/pulls/36054
2020-09-01T22:14:11Z
2020-09-05T23:13:46Z
2020-09-05T23:13:45Z
2020-09-06T12:58:55Z
CLN: _wrap_applied_output
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 7b45a114e548b..a92e3af0764a7 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1206,7 +1206,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): key_index = self.grouper.result_index if self.as_index else None if isinstance(first_not_none, Series): - # this is to silence a DeprecationWarning # TODO: Remove when default dtype of empty Series is object kwargs = first_not_none._construct_axes_dict() @@ -1218,16 +1217,26 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): v = values[0] - if isinstance(v, (np.ndarray, Index, Series)) or not self.as_index: + if not isinstance(v, (np.ndarray, Index, Series)) and self.as_index: + # values are not series or array-like but scalars + # self._selection_name not passed through to Series as the + # result should not take the name of original selection + # of columns + return self.obj._constructor_sliced(values, index=key_index) + + else: if isinstance(v, Series): - applied_index = self._selected_obj._get_axis(self.axis) all_indexed_same = all_indexes_same((x.index for x in values)) - singular_series = len(values) == 1 and applied_index.nlevels == 1 # GH3596 # provide a reduction (Frame -> Series) if groups are # unique if self.squeeze: + applied_index = self._selected_obj._get_axis(self.axis) + singular_series = ( + len(values) == 1 and applied_index.nlevels == 1 + ) + # assign the name to this series if singular_series: values[0].name = keys[0] @@ -1253,18 +1262,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): # GH 8467 return self._concat_objects(keys, values, not_indexed_same=True) - # GH6124 if the list of Series have a consistent name, - # then propagate that name to the result. - index = v.index.copy() - if index.name is None: - # Only propagate the series name to the result - # if all series have a consistent name. If the - # series do not have a consistent name, do - # nothing. - names = {v.name for v in values} - if len(names) == 1: - index.name = list(names)[0] - # Combine values # vstack+constructor is faster than concat and handles MI-columns stacked_values = np.vstack([np.asarray(v) for v in values]) @@ -1313,13 +1310,6 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False): return self._reindex_output(result) - # values are not series or array-like but scalars - else: - # self._selection_name not passed through to Series as the - # result should not take the name of original selection - # of columns - return self.obj._constructor_sliced(values, index=key_index) - def _transform_general( self, func, *args, engine="cython", engine_kwargs=None, **kwargs ):
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry 2nd step toward #35412. In this, the order of the largest if-else is switched with the condition negated. We can then drop the else entirely, resulting in much of the function having one less level of nesting.
https://api.github.com/repos/pandas-dev/pandas/pulls/36053
2020-09-01T22:05:45Z
2020-09-01T23:17:23Z
2020-09-01T23:17:23Z
2020-09-01T23:56:26Z
CLN remove unnecessary trailing commas in pandas/io
diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index e4d9324ce5130..1a4ba544f5d59 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -244,7 +244,7 @@ class XportReader(ReaderBase, abc.Iterator): __doc__ = _xport_reader_doc def __init__( - self, filepath_or_buffer, index=None, encoding="ISO-8859-1", chunksize=None, + self, filepath_or_buffer, index=None, encoding="ISO-8859-1", chunksize=None ): self._encoding = encoding diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 0074ebc4decb0..34d520004cc65 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1980,7 +1980,7 @@ def _open_file_binary_write( compression_typ = infer_compression(fname, compression_typ) compression = dict(compression_args, method=compression_typ) ioargs = get_filepath_or_buffer( - fname, mode="wb", compression=compression, storage_options=storage_options, + fname, mode="wb", compression=compression, storage_options=storage_options ) f, _ = get_handle( ioargs.filepath_or_buffer,
@MarcoGorelli can you review this PR this is related to issue #35925, if this looks good to you I can open another PR - [x] pandas/io/sas/sas_xport.py - [x] pandas/io/stata.py - [x] passes `black pandas`
https://api.github.com/repos/pandas-dev/pandas/pulls/36052
2020-09-01T21:28:54Z
2020-09-03T16:33:47Z
2020-09-03T16:33:47Z
2020-09-03T20:04:49Z
BUG: frame._item_cache not cleared when Series is altered
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 9b1ad658d4666..c52a956146fc2 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -32,6 +32,7 @@ Bug fixes - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) - Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should bw ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) +- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`36051`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3bad2d6dd18b9..7a5ba69902dfa 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3315,6 +3315,10 @@ def _maybe_update_cacher( if len(self) == len(ref): # otherwise, either self or ref has swapped in new arrays ref._maybe_cache_changed(cacher[0], self) + else: + # GH#33675 we have swapped in a new array, so parent + # reference to self is now invalid + ref._item_cache.pop(cacher[0], None) if verify_is_copy: self._check_setitem_copy(stacklevel=5, t="referant") diff --git a/pandas/tests/frame/test_missing.py b/pandas/tests/frame/test_missing.py index 9bf5d24085697..b4f91590e09d1 100644 --- a/pandas/tests/frame/test_missing.py +++ b/pandas/tests/frame/test_missing.py @@ -135,13 +135,20 @@ def test_drop_and_dropna_caching(self): df2 = df.copy() df["A"].dropna() tm.assert_series_equal(df["A"], original) - return_value = df["A"].dropna(inplace=True) - tm.assert_series_equal(df["A"], expected) + + ser = df["A"] + return_value = ser.dropna(inplace=True) + tm.assert_series_equal(ser, expected) + tm.assert_series_equal(df["A"], original) assert return_value is None + df2["A"].drop([1]) tm.assert_series_equal(df2["A"], original) - return_value = df2["A"].drop([1], inplace=True) - tm.assert_series_equal(df2["A"], original.drop([1])) + + ser = df2["A"] + return_value = ser.drop([1], inplace=True) + tm.assert_series_equal(ser, original.drop([1])) + tm.assert_series_equal(df2["A"], original) assert return_value is None def test_dropna_corner(self, float_frame): diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index fa5fe5ba5c384..9910ef1b04b1a 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -81,6 +81,21 @@ def test_setitem_cache_updating(self): tm.assert_frame_equal(out, expected) tm.assert_series_equal(out["A"], expected["A"]) + def test_altering_series_clears_parent_cache(self): + # GH #33675 + df = pd.DataFrame([[1, 2], [3, 4]], index=["a", "b"], columns=["A", "B"]) + ser = df["A"] + + assert "A" in df._item_cache + + # Adding a new entry to ser swaps in a new array, so "A" needs to + # be removed from df._item_cache + ser["c"] = 5 + assert len(ser) == 3 + assert "A" not in df._item_cache + assert df["A"] is not ser + assert len(df["A"]) == 2 + class TestChaining: def test_setitem_chained_setfault(self):
- [x] closes #33675 - [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/36051
2020-09-01T21:16:16Z
2020-09-02T15:43:17Z
2020-09-02T15:43:17Z
2020-09-02T16:55:54Z
BUG: incorrect year returned in isocalendar for certain dates
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index ac9fe9d2fca26..0c95a1bf22dce 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -32,6 +32,7 @@ Bug fixes - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) - Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should be ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) +- Bug in :meth:`Series.dt.isocalendar` and :meth:`DatetimeIndex.isocalendar` that returned incorrect year for certain dates (:issue:`36032`) - Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index 6cce2f5e1fd95..d8c83daa661a3 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -201,10 +201,10 @@ cpdef iso_calendar_t get_iso_calendar(int year, int month, int day) nogil: iso_week = 1 iso_year = year - if iso_week == 1 and doy > 7: + if iso_week == 1 and month == 12: iso_year += 1 - elif iso_week >= 52 and doy < 7: + elif iso_week >= 52 and month == 1: iso_year -= 1 return iso_year, iso_week, dow + 1 diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index d2ad9c8c398ea..723bd303b1974 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -682,6 +682,9 @@ def test_setitem_with_different_tz(self): [[pd.NaT], [[np.NaN, np.NaN, np.NaN]]], [["2019-12-31", "2019-12-29"], [[2020, 1, 2], [2019, 52, 7]]], [["2010-01-01", pd.NaT], [[2009, 53, 5], [np.NaN, np.NaN, np.NaN]]], + # see GH#36032 + [["2016-01-08", "2016-01-04"], [[2016, 1, 5], [2016, 1, 1]]], + [["2016-01-07", "2016-01-01"], [[2016, 1, 4], [2015, 53, 5]]], ], ) def test_isocalendar(self, input_series, expected_output): diff --git a/pandas/tests/tslibs/test_ccalendar.py b/pandas/tests/tslibs/test_ccalendar.py index aab86d3a2df69..1ff700fdc23a3 100644 --- a/pandas/tests/tslibs/test_ccalendar.py +++ b/pandas/tests/tslibs/test_ccalendar.py @@ -1,10 +1,13 @@ from datetime import date, datetime +from hypothesis import given, strategies as st import numpy as np import pytest from pandas._libs.tslibs import ccalendar +import pandas as pd + @pytest.mark.parametrize( "date_tuple,expected", @@ -48,3 +51,15 @@ def test_dt_correct_iso_8601_year_week_and_day(input_date_tuple, expected_iso_tu expected_from_date_isocalendar = date(*input_date_tuple).isocalendar() assert result == expected_from_date_isocalendar assert result == expected_iso_tuple + + +@given( + st.datetimes( + min_value=pd.Timestamp.min.to_pydatetime(warn=False), + max_value=pd.Timestamp.max.to_pydatetime(warn=False), + ) +) +def test_isocalendar(dt): + expected = dt.isocalendar() + result = ccalendar.get_iso_calendar(dt.year, dt.month, dt.day) + assert result == expected
- [x] closes #36032 - [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/36050
2020-09-01T20:56:01Z
2020-09-04T20:29:26Z
2020-09-04T20:29:25Z
2020-09-07T05:14:36Z
CLN: rename private functions used across modules
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 01fe98a6f5403..8ceba22b1f7a4 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -12,8 +12,8 @@ from pandas.io.formats.printing import pprint_thing from pandas.plotting._matplotlib.core import LinePlot, MPLPlot -from pandas.plotting._matplotlib.style import _get_standard_colors -from pandas.plotting._matplotlib.tools import _flatten, _subplots +from pandas.plotting._matplotlib.style import get_standard_colors +from pandas.plotting._matplotlib.tools import create_subplots, flatten_axes if TYPE_CHECKING: from matplotlib.axes import Axes @@ -84,7 +84,7 @@ def _validate_color_args(self): self.color = None # get standard colors for default - colors = _get_standard_colors(num_colors=3, colormap=self.colormap, color=None) + colors = get_standard_colors(num_colors=3, colormap=self.colormap, color=None) # use 2 colors by default, for box/whisker and median # flier colors isn't needed here # because it can be specified by ``sym`` kw @@ -200,11 +200,11 @@ def _grouped_plot_by_column( by = [by] columns = data._get_numeric_data().columns.difference(by) naxes = len(columns) - fig, axes = _subplots( + fig, axes = create_subplots( naxes=naxes, sharex=True, sharey=True, figsize=figsize, ax=ax, layout=layout ) - _axes = _flatten(axes) + _axes = flatten_axes(axes) ax_values = [] @@ -259,7 +259,7 @@ def _get_colors(): # num_colors=3 is required as method maybe_color_bp takes the colors # in positions 0 and 2. # if colors not provided, use same defaults as DataFrame.plot.box - result = _get_standard_colors(num_colors=3) + result = get_standard_colors(num_colors=3) result = np.take(result, [0, 0, 2]) result = np.append(result, "k") @@ -414,7 +414,7 @@ def boxplot_frame_groupby( ): if subplots is True: naxes = len(grouped) - fig, axes = _subplots( + fig, axes = create_subplots( naxes=naxes, squeeze=False, ax=ax, @@ -423,7 +423,7 @@ def boxplot_frame_groupby( figsize=figsize, layout=layout, ) - axes = _flatten(axes) + axes = flatten_axes(axes) ret = pd.Series(dtype=object) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 93ba9bd26630b..5eae88d07c295 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -32,14 +32,14 @@ from pandas.io.formats.printing import pprint_thing from pandas.plotting._matplotlib.compat import _mpl_ge_3_0_0 from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters -from pandas.plotting._matplotlib.style import _get_standard_colors +from pandas.plotting._matplotlib.style import get_standard_colors from pandas.plotting._matplotlib.tools import ( - _flatten, - _get_all_lines, - _get_xlim, - _handle_shared_axes, - _subplots, + create_subplots, + flatten_axes, format_date_labels, + get_all_lines, + get_xlim, + handle_shared_axes, table, ) @@ -315,7 +315,7 @@ def _maybe_right_yaxis(self, ax: "Axes", axes_num): def _setup_subplots(self): if self.subplots: - fig, axes = _subplots( + fig, axes = create_subplots( naxes=self.nseries, sharex=self.sharex, sharey=self.sharey, @@ -334,7 +334,7 @@ def _setup_subplots(self): fig.set_size_inches(self.figsize) axes = self.ax - axes = _flatten(axes) + axes = flatten_axes(axes) valid_log = {False, True, "sym", None} input_log = {self.logx, self.logy, self.loglog} @@ -466,7 +466,7 @@ def _adorn_subplots(self): if len(self.axes) > 0: all_axes = self._get_subplots() nrows, ncols = self._get_axes_layout() - _handle_shared_axes( + handle_shared_axes( axarr=all_axes, nplots=len(all_axes), naxes=nrows * ncols, @@ -753,7 +753,7 @@ def _get_colors(self, num_colors=None, color_kwds="color"): if num_colors is None: num_colors = self.nseries - return _get_standard_colors( + return get_standard_colors( num_colors=num_colors, colormap=self.colormap, color=self.kwds.get(color_kwds), @@ -1132,8 +1132,8 @@ def _make_plot(self): # reset of xlim should be used for ts data # TODO: GH28021, should find a way to change view limit on xaxis - lines = _get_all_lines(ax) - left, right = _get_xlim(lines) + lines = get_all_lines(ax) + left, right = get_xlim(lines) ax.set_xlim(left, right) @classmethod diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index ffd46d1b191db..89035552d4309 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -8,7 +8,11 @@ from pandas.io.formats.printing import pprint_thing from pandas.plotting._matplotlib.core import LinePlot, MPLPlot -from pandas.plotting._matplotlib.tools import _flatten, _set_ticks_props, _subplots +from pandas.plotting._matplotlib.tools import ( + create_subplots, + flatten_axes, + set_ticks_props, +) if TYPE_CHECKING: from matplotlib.axes import Axes @@ -198,11 +202,11 @@ def _grouped_plot( grouped = grouped[column] naxes = len(grouped) - fig, axes = _subplots( + fig, axes = create_subplots( naxes=naxes, figsize=figsize, sharex=sharex, sharey=sharey, ax=ax, layout=layout ) - _axes = _flatten(axes) + _axes = flatten_axes(axes) for i, (key, group) in enumerate(grouped): ax = _axes[i] @@ -286,7 +290,7 @@ def plot_group(group, ax): rot=rot, ) - _set_ticks_props( + set_ticks_props( axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot ) @@ -337,7 +341,7 @@ def hist_series( ax.grid(grid) axes = np.array([ax]) - _set_ticks_props( + set_ticks_props( axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot ) @@ -419,7 +423,7 @@ def hist_frame( if naxes == 0: raise ValueError("hist method requires numerical columns, nothing to plot.") - fig, axes = _subplots( + fig, axes = create_subplots( naxes=naxes, ax=ax, squeeze=False, @@ -428,7 +432,7 @@ def hist_frame( figsize=figsize, layout=layout, ) - _axes = _flatten(axes) + _axes = flatten_axes(axes) can_set_label = "label" not in kwds @@ -442,7 +446,7 @@ def hist_frame( if legend: ax.legend() - _set_ticks_props( + set_ticks_props( axes, xlabelsize=xlabelsize, xrot=xrot, ylabelsize=ylabelsize, yrot=yrot ) fig.subplots_adjust(wspace=0.3, hspace=0.3) diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index c5e7c55970c3e..a1c62f9fce23c 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -10,8 +10,8 @@ from pandas.core.dtypes.missing import notna from pandas.io.formats.printing import pprint_thing -from pandas.plotting._matplotlib.style import _get_standard_colors -from pandas.plotting._matplotlib.tools import _set_ticks_props, _subplots +from pandas.plotting._matplotlib.style import get_standard_colors +from pandas.plotting._matplotlib.tools import create_subplots, set_ticks_props if TYPE_CHECKING: from matplotlib.axes import Axes @@ -36,7 +36,7 @@ def scatter_matrix( df = frame._get_numeric_data() n = df.columns.size naxes = n * n - fig, axes = _subplots(naxes=naxes, figsize=figsize, ax=ax, squeeze=False) + fig, axes = create_subplots(naxes=naxes, figsize=figsize, ax=ax, squeeze=False) # no gaps between subplots fig.subplots_adjust(wspace=0, hspace=0) @@ -112,7 +112,7 @@ def scatter_matrix( locs = locs.astype(int) axes[0][0].yaxis.set_ticklabels(locs) - _set_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) + set_ticks_props(axes, xlabelsize=8, xrot=90, ylabelsize=8, yrot=0) return axes @@ -147,7 +147,7 @@ def normalize(series): ax = plt.gca(xlim=[-1, 1], ylim=[-1, 1]) to_plot: Dict[Label, List[List]] = {} - colors = _get_standard_colors( + colors = get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color ) @@ -255,7 +255,7 @@ def f(t): t = np.linspace(-np.pi, np.pi, samples) used_legends: Set[str] = set() - color_values = _get_standard_colors( + color_values = get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color ) colors = dict(zip(classes, color_values)) @@ -382,7 +382,7 @@ def parallel_coordinates( if ax is None: ax = plt.gca() - color_values = _get_standard_colors( + color_values = get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color ) diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 5f1105f0e4233..904a760a03e58 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -10,7 +10,7 @@ import pandas.core.common as com -def _get_standard_colors( +def get_standard_colors( num_colors=None, colormap=None, color_type: str = "default", color=None ): import matplotlib.pyplot as plt diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 4d643ffb734e4..98aaab6838fba 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -100,7 +100,7 @@ def _get_layout(nplots: int, layout=None, layout_type: str = "box") -> Tuple[int # copied from matplotlib/pyplot.py and modified for pandas.plotting -def _subplots( +def create_subplots( naxes: int, sharex: bool = False, sharey: bool = False, @@ -194,7 +194,7 @@ def _subplots( fig = plt.figure(**fig_kw) else: if is_list_like(ax): - ax = _flatten(ax) + ax = flatten_axes(ax) if layout is not None: warnings.warn( "When passing multiple axes, layout keyword is ignored", UserWarning @@ -221,7 +221,7 @@ def _subplots( if squeeze: return fig, ax else: - return fig, _flatten(ax) + return fig, flatten_axes(ax) else: warnings.warn( "To output multiple subplots, the figure containing " @@ -264,7 +264,7 @@ def _subplots( for ax in axarr[naxes:]: ax.set_visible(False) - _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey) + handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey) if squeeze: # Reshape the array to have the final desired dimension (nrow,ncol), @@ -297,7 +297,7 @@ def _remove_labels_from_axis(axis: "Axis"): axis.get_label().set_visible(False) -def _handle_shared_axes( +def handle_shared_axes( axarr: Iterable["Axes"], nplots: int, naxes: int, @@ -351,7 +351,7 @@ def _handle_shared_axes( _remove_labels_from_axis(ax.yaxis) -def _flatten(axes: Union["Axes", Sequence["Axes"]]) -> Sequence["Axes"]: +def flatten_axes(axes: Union["Axes", Sequence["Axes"]]) -> Sequence["Axes"]: if not is_list_like(axes): return np.array([axes]) elif isinstance(axes, (np.ndarray, ABCIndexClass)): @@ -359,7 +359,7 @@ def _flatten(axes: Union["Axes", Sequence["Axes"]]) -> Sequence["Axes"]: return np.array(axes) -def _set_ticks_props( +def set_ticks_props( axes: Union["Axes", Sequence["Axes"]], xlabelsize=None, xrot=None, @@ -368,7 +368,7 @@ def _set_ticks_props( ): import matplotlib.pyplot as plt - for ax in _flatten(axes): + for ax in flatten_axes(axes): if xlabelsize is not None: plt.setp(ax.get_xticklabels(), fontsize=xlabelsize) if xrot is not None: @@ -380,7 +380,7 @@ def _set_ticks_props( return axes -def _get_all_lines(ax: "Axes") -> List["Line2D"]: +def get_all_lines(ax: "Axes") -> List["Line2D"]: lines = ax.get_lines() if hasattr(ax, "right_ax"): @@ -392,7 +392,7 @@ def _get_all_lines(ax: "Axes") -> List["Line2D"]: return lines -def _get_xlim(lines: Iterable["Line2D"]) -> Tuple[float, float]: +def get_xlim(lines: Iterable["Line2D"]) -> Tuple[float, float]: left, right = np.inf, -np.inf for l in lines: x = l.get_xdata(orig=False) diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 3b1ff233c5ec1..b753c96af6290 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -13,13 +13,13 @@ from pandas import DataFrame, Series import pandas._testing as tm -""" -This is a common base class used for various plotting tests -""" - @td.skip_if_no_mpl class TestPlotBase: + """ + This is a common base class used for various plotting tests + """ + def setup_method(self, method): import matplotlib as mpl @@ -330,7 +330,7 @@ def _check_axes_shape(self, axes, axes_num=None, layout=None, figsize=None): figsize : tuple expected figsize. default is matplotlib default """ - from pandas.plotting._matplotlib.tools import _flatten + from pandas.plotting._matplotlib.tools import flatten_axes if figsize is None: figsize = self.default_figsize @@ -343,7 +343,7 @@ def _check_axes_shape(self, axes, axes_num=None, layout=None, figsize=None): assert len(ax.get_children()) > 0 if layout is not None: - result = self._get_axes_layout(_flatten(axes)) + result = self._get_axes_layout(flatten_axes(axes)) assert result == layout tm.assert_numpy_array_equal( @@ -370,9 +370,9 @@ def _flatten_visible(self, axes): axes : matplotlib Axes object, or its list-like """ - from pandas.plotting._matplotlib.tools import _flatten + from pandas.plotting._matplotlib.tools import flatten_axes - axes = _flatten(axes) + axes = flatten_axes(axes) axes = [ax for ax in axes if ax.get_visible()] return axes diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index f5c1c58f3f7ed..130acaa8bcd58 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -353,7 +353,7 @@ def test_get_standard_colors_random_seed(self): # GH17525 df = DataFrame(np.zeros((10, 10))) - # Make sure that the random seed isn't reset by _get_standard_colors + # Make sure that the random seed isn't reset by get_standard_colors plotting.parallel_coordinates(df, 0) rand1 = random.random() plotting.parallel_coordinates(df, 0) @@ -361,19 +361,19 @@ def test_get_standard_colors_random_seed(self): assert rand1 != rand2 # Make sure it produces the same colors every time it's called - from pandas.plotting._matplotlib.style import _get_standard_colors + from pandas.plotting._matplotlib.style import get_standard_colors - color1 = _get_standard_colors(1, color_type="random") - color2 = _get_standard_colors(1, color_type="random") + color1 = get_standard_colors(1, color_type="random") + color2 = get_standard_colors(1, color_type="random") assert color1 == color2 def test_get_standard_colors_default_num_colors(self): - from pandas.plotting._matplotlib.style import _get_standard_colors + from pandas.plotting._matplotlib.style import get_standard_colors # Make sure the default color_types returns the specified amount - color1 = _get_standard_colors(1, color_type="default") - color2 = _get_standard_colors(9, color_type="default") - color3 = _get_standard_colors(20, color_type="default") + color1 = get_standard_colors(1, color_type="default") + color2 = get_standard_colors(9, color_type="default") + color3 = get_standard_colors(20, color_type="default") assert len(color1) == 1 assert len(color2) == 9 assert len(color3) == 20 @@ -401,10 +401,10 @@ def test_get_standard_colors_no_appending(self): # correctly. from matplotlib import cm - from pandas.plotting._matplotlib.style import _get_standard_colors + from pandas.plotting._matplotlib.style import get_standard_colors color_before = cm.gnuplot(range(5)) - color_after = _get_standard_colors(1, color=color_before) + color_after = get_standard_colors(1, color=color_before) assert len(color_after) == len(color_before) df = DataFrame(np.random.randn(48, 4), columns=list("ABCD")) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index cc00626e992f3..c296e2a6278c5 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -809,53 +809,53 @@ def test_series_grid_settings(self): @pytest.mark.slow def test_standard_colors(self): - from pandas.plotting._matplotlib.style import _get_standard_colors + from pandas.plotting._matplotlib.style import get_standard_colors for c in ["r", "red", "green", "#FF0000"]: - result = _get_standard_colors(1, color=c) + result = get_standard_colors(1, color=c) assert result == [c] - result = _get_standard_colors(1, color=[c]) + result = get_standard_colors(1, color=[c]) assert result == [c] - result = _get_standard_colors(3, color=c) + result = get_standard_colors(3, color=c) assert result == [c] * 3 - result = _get_standard_colors(3, color=[c]) + result = get_standard_colors(3, color=[c]) assert result == [c] * 3 @pytest.mark.slow def test_standard_colors_all(self): import matplotlib.colors as colors - from pandas.plotting._matplotlib.style import _get_standard_colors + from pandas.plotting._matplotlib.style import get_standard_colors # multiple colors like mediumaquamarine for c in colors.cnames: - result = _get_standard_colors(num_colors=1, color=c) + result = get_standard_colors(num_colors=1, color=c) assert result == [c] - result = _get_standard_colors(num_colors=1, color=[c]) + result = get_standard_colors(num_colors=1, color=[c]) assert result == [c] - result = _get_standard_colors(num_colors=3, color=c) + result = get_standard_colors(num_colors=3, color=c) assert result == [c] * 3 - result = _get_standard_colors(num_colors=3, color=[c]) + result = get_standard_colors(num_colors=3, color=[c]) assert result == [c] * 3 # single letter colors like k for c in colors.ColorConverter.colors: - result = _get_standard_colors(num_colors=1, color=c) + result = get_standard_colors(num_colors=1, color=c) assert result == [c] - result = _get_standard_colors(num_colors=1, color=[c]) + result = get_standard_colors(num_colors=1, color=[c]) assert result == [c] - result = _get_standard_colors(num_colors=3, color=c) + result = get_standard_colors(num_colors=3, color=c) assert result == [c] * 3 - result = _get_standard_colors(num_colors=3, color=[c]) + result = get_standard_colors(num_colors=3, color=[c]) assert result == [c] * 3 def test_series_plot_color_kwargs(self):
https://api.github.com/repos/pandas-dev/pandas/pulls/36049
2020-09-01T19:35:37Z
2020-09-02T17:54:27Z
2020-09-02T17:54:27Z
2020-09-02T18:27:14Z
CI: pin setuptools on 1.1.x
diff --git a/ci/setup_env.sh b/ci/setup_env.sh index aa43d8b7dd00a..065f9e56ea171 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -148,7 +148,7 @@ python setup.py build_ext -q -i -j2 # - py35_compat # - py36_32bit echo "[Updating pip]" -python -m pip install --no-deps -U pip wheel setuptools +python -m pip install --no-deps -U pip wheel "setuptools<50.0.0" echo "[Install pandas]" python -m pip install --no-build-isolation -e .
top answer on stack overflow is to pin https://stackoverflow.com/questions/63663362/django-python3-on-install-i-get-parent-module-setuptools-not-loaded also see https://github.com/MacPython/pandas-wheels/pull/97#issuecomment-684938715 Note: 50.0.1 released a hour ago but still the same. https://dev.azure.com/pandas-dev/pandas/_build/results?buildId=41325&view=logs&j=a67b4c4c-cd2e-5e3c-a361-de73ac9c05f9&t=9a6bfc0f-544f-57f9-291f-bf4b75b05642
https://api.github.com/repos/pandas-dev/pandas/pulls/36048
2020-09-01T18:42:16Z
2020-09-01T23:27:11Z
2020-09-01T23:27:11Z
2020-09-02T09:23:22Z
REF: simplify CSVFormatter
diff --git a/pandas/_typing.py b/pandas/_typing.py index b237013ac7805..7aef5c02e290f 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -15,6 +15,7 @@ List, Mapping, Optional, + Sequence, Type, TypeVar, Union, @@ -82,6 +83,7 @@ Axis = Union[str, int] Label = Optional[Hashable] +IndexLabel = Optional[Union[Label, Sequence[Label]]] Level = Union[Label, int] Ordered = Optional[bool] JSONSerializable = Optional[Union[PythonScalar, List, Dict]] diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 93c945638a174..126692fb8e899 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -40,6 +40,7 @@ CompressionOptions, FilePathOrBuffer, FrameOrSeries, + IndexLabel, JSONSerializable, Label, Level, @@ -3160,7 +3161,7 @@ def to_csv( columns: Optional[Sequence[Label]] = None, header: Union[bool_t, List[str]] = True, index: bool_t = True, - index_label: Optional[Union[bool_t, str, Sequence[Label]]] = None, + index_label: IndexLabel = None, mode: str = "w", encoding: Optional[str] = None, compression: CompressionOptions = "infer", diff --git a/pandas/io/common.py b/pandas/io/common.py index a80b89569f429..007e0dcbbcfe1 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -208,6 +208,21 @@ def get_filepath_or_buffer( # handle compression dict compression_method, compression = get_compression_method(compression) compression_method = infer_compression(filepath_or_buffer, compression_method) + + # GH21227 internal compression is not used for non-binary handles. + if ( + compression_method + and hasattr(filepath_or_buffer, "write") + and mode + and "b" not in mode + ): + warnings.warn( + "compression has no effect when passing a non-binary object as input.", + RuntimeWarning, + stacklevel=2, + ) + compression_method = None + compression = dict(compression, method=compression_method) # bz2 and xz do not write the byte order mark for utf-16 and utf-32 diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 15cd5c026c6b6..90ab6f61f4d74 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -5,13 +5,18 @@ import csv as csvlib from io import StringIO, TextIOWrapper import os -from typing import Hashable, List, Optional, Sequence, Union -import warnings +from typing import Any, Dict, Hashable, Iterator, List, Optional, Sequence, Union import numpy as np from pandas._libs import writers as libwriters -from pandas._typing import CompressionOptions, FilePathOrBuffer, StorageOptions +from pandas._typing import ( + CompressionOptions, + FilePathOrBuffer, + IndexLabel, + Label, + StorageOptions, +) from pandas.core.dtypes.generic import ( ABCDatetimeIndex, @@ -21,6 +26,8 @@ ) from pandas.core.dtypes.missing import notna +from pandas.core.indexes.api import Index + from pandas.io.common import get_filepath_or_buffer, get_handle @@ -32,10 +39,10 @@ def __init__( sep: str = ",", na_rep: str = "", float_format: Optional[str] = None, - cols=None, + cols: Optional[Sequence[Label]] = None, header: Union[bool, Sequence[Hashable]] = True, index: bool = True, - index_label: Optional[Union[bool, Hashable, Sequence[Hashable]]] = None, + index_label: IndexLabel = None, mode: str = "w", encoding: Optional[str] = None, errors: str = "strict", @@ -43,7 +50,7 @@ def __init__( quoting: Optional[int] = None, line_terminator="\n", chunksize: Optional[int] = None, - quotechar='"', + quotechar: Optional[str] = '"', date_format: Optional[str] = None, doublequote: bool = True, escapechar: Optional[str] = None, @@ -52,16 +59,19 @@ def __init__( ): self.obj = obj + self.encoding = encoding or "utf-8" + if path_or_buf is None: path_or_buf = StringIO() ioargs = get_filepath_or_buffer( path_or_buf, - encoding=encoding, + encoding=self.encoding, compression=compression, mode=mode, storage_options=storage_options, ) + self.compression = ioargs.compression.pop("method") self.compression_args = ioargs.compression self.path_or_buf = ioargs.filepath_or_buffer @@ -72,46 +82,79 @@ def __init__( self.na_rep = na_rep self.float_format = float_format self.decimal = decimal - self.header = header self.index = index self.index_label = index_label - if encoding is None: - encoding = "utf-8" - self.encoding = encoding self.errors = errors + self.quoting = quoting or csvlib.QUOTE_MINIMAL + self.quotechar = quotechar + self.doublequote = doublequote + self.escapechar = escapechar + self.line_terminator = line_terminator or os.linesep + self.date_format = date_format + self.cols = cols # type: ignore[assignment] + self.chunksize = chunksize # type: ignore[assignment] + + @property + def index_label(self) -> IndexLabel: + return self._index_label + + @index_label.setter + def index_label(self, index_label: IndexLabel) -> None: + if index_label is not False: + if index_label is None: + index_label = self._get_index_label_from_obj() + elif not isinstance(index_label, (list, tuple, np.ndarray, ABCIndexClass)): + # given a string for a DF with Index + index_label = [index_label] + self._index_label = index_label + + def _get_index_label_from_obj(self) -> List[str]: + if isinstance(self.obj.index, ABCMultiIndex): + return self._get_index_label_multiindex() + else: + return self._get_index_label_flat() + + def _get_index_label_multiindex(self) -> List[str]: + return [name or "" for name in self.obj.index.names] - if quoting is None: - quoting = csvlib.QUOTE_MINIMAL - self.quoting = quoting + def _get_index_label_flat(self) -> List[str]: + index_label = self.obj.index.name + return [""] if index_label is None else [index_label] - if quoting == csvlib.QUOTE_NONE: + @property + def quotechar(self) -> Optional[str]: + if self.quoting != csvlib.QUOTE_NONE: # prevents crash in _csv - quotechar = None - self.quotechar = quotechar + return self._quotechar + return None - self.doublequote = doublequote - self.escapechar = escapechar + @quotechar.setter + def quotechar(self, quotechar: Optional[str]) -> None: + self._quotechar = quotechar - self.line_terminator = line_terminator or os.linesep + @property + def has_mi_columns(self) -> bool: + return bool(isinstance(self.obj.columns, ABCMultiIndex)) - self.date_format = date_format + @property + def cols(self) -> Sequence[Label]: + return self._cols - self.has_mi_columns = isinstance(obj.columns, ABCMultiIndex) + @cols.setter + def cols(self, cols: Optional[Sequence[Label]]) -> None: + self._cols = self._refine_cols(cols) + def _refine_cols(self, cols: Optional[Sequence[Label]]) -> Sequence[Label]: # validate mi options if self.has_mi_columns: if cols is not None: - raise TypeError("cannot specify cols with a MultiIndex on the columns") + msg = "cannot specify cols with a MultiIndex on the columns" + raise TypeError(msg) if cols is not None: if isinstance(cols, ABCIndexClass): - cols = cols.to_native_types( - na_rep=na_rep, - float_format=float_format, - date_format=date_format, - quoting=self.quoting, - ) + cols = cols.to_native_types(**self._number_format) else: cols = list(cols) self.obj = self.obj.loc[:, cols] @@ -120,58 +163,90 @@ def __init__( # and make sure sure cols is just a list of labels cols = self.obj.columns if isinstance(cols, ABCIndexClass): - cols = cols.to_native_types( - na_rep=na_rep, - float_format=float_format, - date_format=date_format, - quoting=self.quoting, - ) + return cols.to_native_types(**self._number_format) else: - cols = list(cols) + assert isinstance(cols, Sequence) + return list(cols) - # save it - self.cols = cols + @property + def _number_format(self) -> Dict[str, Any]: + """Dictionary used for storing number formatting settings.""" + return dict( + na_rep=self.na_rep, + float_format=self.float_format, + date_format=self.date_format, + quoting=self.quoting, + decimal=self.decimal, + ) - # preallocate data 2d list - ncols = self.obj.shape[-1] - self.data = [None] * ncols + @property + def chunksize(self) -> int: + return self._chunksize + @chunksize.setter + def chunksize(self, chunksize: Optional[int]) -> None: if chunksize is None: chunksize = (100000 // (len(self.cols) or 1)) or 1 - self.chunksize = int(chunksize) + assert chunksize is not None + self._chunksize = int(chunksize) - self.data_index = obj.index + @property + def data_index(self) -> Index: + data_index = self.obj.index if ( - isinstance(self.data_index, (ABCDatetimeIndex, ABCPeriodIndex)) - and date_format is not None + isinstance(data_index, (ABCDatetimeIndex, ABCPeriodIndex)) + and self.date_format is not None ): - from pandas import Index - - self.data_index = Index( - [x.strftime(date_format) if notna(x) else "" for x in self.data_index] + data_index = Index( + [x.strftime(self.date_format) if notna(x) else "" for x in data_index] ) + return data_index + + @property + def nlevels(self) -> int: + if self.index: + return getattr(self.data_index, "nlevels", 1) + else: + return 0 + + @property + def _has_aliases(self) -> bool: + return isinstance(self.header, (tuple, list, np.ndarray, ABCIndexClass)) + + @property + def _need_to_save_header(self) -> bool: + return bool(self._has_aliases or self.header) + + @property + def write_cols(self) -> Sequence[Label]: + if self._has_aliases: + assert not isinstance(self.header, bool) + if len(self.header) != len(self.cols): + raise ValueError( + f"Writing {len(self.cols)} cols but got {len(self.header)} aliases" + ) + else: + return self.header + else: + return self.cols + + @property + def encoded_labels(self) -> List[Label]: + encoded_labels: List[Label] = [] + + if self.index and self.index_label: + assert isinstance(self.index_label, Sequence) + encoded_labels = list(self.index_label) - self.nlevels = getattr(self.data_index, "nlevels", 1) - if not index: - self.nlevels = 0 + if not self.has_mi_columns or self._has_aliases: + encoded_labels += list(self.write_cols) + + return encoded_labels def save(self) -> None: """ Create the writer & save. """ - # GH21227 internal compression is not used for non-binary handles. - if ( - self.compression - and hasattr(self.path_or_buf, "write") - and "b" not in self.mode - ): - warnings.warn( - "compression has no effect when passing a non-binary object as input.", - RuntimeWarning, - stacklevel=2, - ) - self.compression = None - # get a handle or wrap an existing handle to take care of 1) compression and # 2) text -> byte conversion f, handles = get_handle( @@ -215,133 +290,63 @@ def save(self) -> None: for _fh in handles: _fh.close() - def _save_header(self): - writer = self.writer - obj = self.obj - index_label = self.index_label - cols = self.cols - has_mi_columns = self.has_mi_columns - header = self.header - encoded_labels: List[str] = [] - - has_aliases = isinstance(header, (tuple, list, np.ndarray, ABCIndexClass)) - if not (has_aliases or self.header): - return - if has_aliases: - if len(header) != len(cols): - raise ValueError( - f"Writing {len(cols)} cols but got {len(header)} aliases" - ) - else: - write_cols = header - else: - write_cols = cols - - if self.index: - # should write something for index label - if index_label is not False: - if index_label is None: - if isinstance(obj.index, ABCMultiIndex): - index_label = [] - for i, name in enumerate(obj.index.names): - if name is None: - name = "" - index_label.append(name) - else: - index_label = obj.index.name - if index_label is None: - index_label = [""] - else: - index_label = [index_label] - elif not isinstance( - index_label, (list, tuple, np.ndarray, ABCIndexClass) - ): - # given a string for a DF with Index - index_label = [index_label] - - encoded_labels = list(index_label) - else: - encoded_labels = [] - - if not has_mi_columns or has_aliases: - encoded_labels += list(write_cols) - writer.writerow(encoded_labels) - else: - # write out the mi - columns = obj.columns - - # write out the names for each level, then ALL of the values for - # each level - for i in range(columns.nlevels): - - # we need at least 1 index column to write our col names - col_line = [] - if self.index: - - # name is the first column - col_line.append(columns.names[i]) - - if isinstance(index_label, list) and len(index_label) > 1: - col_line.extend([""] * (len(index_label) - 1)) - - col_line.extend(columns._get_level_values(i)) - - writer.writerow(col_line) - - # Write out the index line if it's not empty. - # Otherwise, we will print out an extraneous - # blank line between the mi and the data rows. - if encoded_labels and set(encoded_labels) != {""}: - encoded_labels.extend([""] * len(columns)) - writer.writerow(encoded_labels) - def _save(self) -> None: - self._save_header() + if self._need_to_save_header: + self._save_header() + self._save_body() + def _save_header(self) -> None: + if not self.has_mi_columns or self._has_aliases: + self.writer.writerow(self.encoded_labels) + else: + for row in self._generate_multiindex_header_rows(): + self.writer.writerow(row) + + def _generate_multiindex_header_rows(self) -> Iterator[List[Label]]: + columns = self.obj.columns + for i in range(columns.nlevels): + # we need at least 1 index column to write our col names + col_line = [] + if self.index: + # name is the first column + col_line.append(columns.names[i]) + + if isinstance(self.index_label, list) and len(self.index_label) > 1: + col_line.extend([""] * (len(self.index_label) - 1)) + + col_line.extend(columns._get_level_values(i)) + yield col_line + + # Write out the index line if it's not empty. + # Otherwise, we will print out an extraneous + # blank line between the mi and the data rows. + if self.encoded_labels and set(self.encoded_labels) != {""}: + yield self.encoded_labels + [""] * len(columns) + + def _save_body(self) -> None: nrows = len(self.data_index) - - # write in chunksize bites - chunksize = self.chunksize - chunks = int(nrows / chunksize) + 1 - + chunks = int(nrows / self.chunksize) + 1 for i in range(chunks): - start_i = i * chunksize - end_i = min((i + 1) * chunksize, nrows) + start_i = i * self.chunksize + end_i = min(start_i + self.chunksize, nrows) if start_i >= end_i: break - self._save_chunk(start_i, end_i) def _save_chunk(self, start_i: int, end_i: int) -> None: - data_index = self.data_index + ncols = self.obj.shape[-1] + data = [None] * ncols # create the data for a chunk slicer = slice(start_i, end_i) df = self.obj.iloc[slicer] - blocks = df._mgr.blocks - - for i in range(len(blocks)): - b = blocks[i] - d = b.to_native_types( - na_rep=self.na_rep, - float_format=self.float_format, - decimal=self.decimal, - date_format=self.date_format, - quoting=self.quoting, - ) - for col_loc, col in zip(b.mgr_locs, d): - # self.data is a preallocated list - self.data[col_loc] = col + for block in df._mgr.blocks: + d = block.to_native_types(**self._number_format) - ix = data_index.to_native_types( - slicer=slicer, - na_rep=self.na_rep, - float_format=self.float_format, - decimal=self.decimal, - date_format=self.date_format, - quoting=self.quoting, - ) + for col_loc, col in zip(block.mgr_locs, d): + data[col_loc] = col - libwriters.write_csv_rows(self.data, ix, self.nlevels, self.cols, self.writer) + ix = self.data_index.to_native_types(slicer=slicer, **self._number_format) + libwriters.write_csv_rows(data, ix, self.nlevels, self.cols, self.writer)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Refactor CSVFormatter ---------------------- 1. Put data validation in setters 2. Extract helper methods and properties
https://api.github.com/repos/pandas-dev/pandas/pulls/36046
2020-09-01T17:49:29Z
2020-09-09T10:33:11Z
2020-09-09T10:33:11Z
2020-11-06T15:35:00Z
BUG: NDFrame.replace wrong exception type, wrong return when size==0
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 407e8ba029ada..7460043d8c89e 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -281,7 +281,7 @@ ExtensionArray Other ^^^^^ -- +- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly raising ``AssertionError`` instead of ``ValueError`` when invalid parameter combinations are passed (:issue:`36045`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3bad2d6dd18b9..ce2625f3ec15d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6179,8 +6179,8 @@ def replace( self, to_replace=None, value=None, - inplace=False, - limit=None, + inplace: bool_t = False, + limit: Optional[int] = None, regex=False, method="pad", ): @@ -6256,7 +6256,7 @@ def replace( If True, in place. Note: this will modify any other views on this object (e.g. a column from a DataFrame). Returns the caller if this is True. - limit : int, default None + limit : int or None, default None Maximum size gap to forward or backward fill. regex : bool or same types as `to_replace`, default False Whether to interpret `to_replace` and/or `value` as regular @@ -6490,7 +6490,7 @@ def replace( inplace = validate_bool_kwarg(inplace, "inplace") if not is_bool(regex) and to_replace is not None: - raise AssertionError("'to_replace' must be 'None' if 'regex' is not a bool") + raise ValueError("'to_replace' must be 'None' if 'regex' is not a bool") if value is None: # passing a single value that is scalar like @@ -6550,12 +6550,14 @@ def replace( # need a non-zero len on all axes if not self.size: - return self + if inplace: + return + return self.copy() if is_dict_like(to_replace): if is_dict_like(value): # {'A' : NA} -> {'A' : 0} # Note: Checking below for `in foo.keys()` instead of - # `in foo`is needed for when we have a Series and not dict + # `in foo` is needed for when we have a Series and not dict mapping = { col: (to_replace[col], value[col]) for col in to_replace.keys() diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index f78a28c66e946..ccaa005369a1c 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -397,6 +397,29 @@ def test_replace_invalid_to_replace(self): with pytest.raises(TypeError, match=msg): series.replace(lambda x: x.strip()) + @pytest.mark.parametrize("frame", [False, True]) + def test_replace_nonbool_regex(self, frame): + obj = pd.Series(["a", "b", "c "]) + if frame: + obj = obj.to_frame() + + msg = "'to_replace' must be 'None' if 'regex' is not a bool" + with pytest.raises(ValueError, match=msg): + obj.replace(to_replace=["a"], regex="foo") + + @pytest.mark.parametrize("frame", [False, True]) + def test_replace_empty_copy(self, frame): + obj = pd.Series([], dtype=np.float64) + if frame: + obj = obj.to_frame() + + res = obj.replace(4, 5, inplace=True) + assert res is None + + res = obj.replace(4, 5, inplace=False) + tm.assert_equal(res, obj) + assert res is not obj + def test_replace_only_one_dictlike_arg(self): # GH#33340
- [ ] 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/36045
2020-09-01T17:04:47Z
2020-09-02T03:19:27Z
2020-09-02T03:19:27Z
2020-09-02T16:57:21Z
DOC: add semicolons to suppress text repr of matplotlib objects in visualization.rst
diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst index a6c3d9814b03d..9eb6ac4629901 100644 --- a/doc/source/user_guide/visualization.rst +++ b/doc/source/user_guide/visualization.rst @@ -44,7 +44,7 @@ The ``plot`` method on Series and DataFrame is just a simple wrapper around ts = ts.cumsum() @savefig series_plot_basic.png - ts.plot() + ts.plot(); If the index consists of dates, it calls :meth:`gcf().autofmt_xdate() <matplotlib.figure.Figure.autofmt_xdate>` to try to format the x-axis nicely as per above. @@ -82,7 +82,7 @@ You can plot one column versus another using the ``x`` and ``y`` keywords in df3["A"] = pd.Series(list(range(len(df)))) @savefig df_plot_xy.png - df3.plot(x="A", y="B") + df3.plot(x="A", y="B"); .. note:: @@ -162,8 +162,8 @@ For labeled, non-time series data, you may wish to produce a bar plot: plt.figure(); @savefig bar_plot_ex.png - df.iloc[5].plot.bar() - plt.axhline(0, color="k") + df.iloc[5].plot.bar(); + plt.axhline(0, color="k"); Calling a DataFrame's :meth:`plot.bar() <DataFrame.plot.bar>` method produces a multiple bar plot: @@ -229,7 +229,7 @@ Histograms can be drawn by using the :meth:`DataFrame.plot.hist` and :meth:`Seri plt.figure(); @savefig hist_new.png - df4.plot.hist(alpha=0.5) + df4.plot.hist(alpha=0.5); .. ipython:: python @@ -245,7 +245,7 @@ using the ``bins`` keyword. plt.figure(); @savefig hist_new_stacked.png - df4.plot.hist(stacked=True, bins=20) + df4.plot.hist(stacked=True, bins=20); .. ipython:: python :suppress: @@ -261,7 +261,7 @@ horizontal and cumulative histograms can be drawn by plt.figure(); @savefig hist_new_kwargs.png - df4["a"].plot.hist(orientation="horizontal", cumulative=True) + df4["a"].plot.hist(orientation="horizontal", cumulative=True); .. ipython:: python :suppress: @@ -279,7 +279,7 @@ The existing interface ``DataFrame.hist`` to plot histogram still can be used. plt.figure(); @savefig hist_plot_ex.png - df["A"].diff().hist() + df["A"].diff().hist(); .. ipython:: python :suppress: @@ -291,10 +291,10 @@ subplots: .. ipython:: python - plt.figure() + plt.figure(); @savefig frame_hist_ex.png - df.diff().hist(color="k", alpha=0.5, bins=50) + df.diff().hist(color="k", alpha=0.5, bins=50); The ``by`` keyword can be specified to plot grouped histograms: @@ -311,7 +311,7 @@ The ``by`` keyword can be specified to plot grouped histograms: data = pd.Series(np.random.randn(1000)) @savefig grouped_hist.png - data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4)) + data.hist(by=np.random.randint(0, 4, 1000), figsize=(6, 4)); .. _visualization.box: @@ -336,7 +336,7 @@ a uniform random variable on [0,1). df = pd.DataFrame(np.random.rand(10, 5), columns=["A", "B", "C", "D", "E"]) @savefig box_plot_new.png - df.plot.box() + df.plot.box(); Boxplot can be colorized by passing ``color`` keyword. You can pass a ``dict`` whose keys are ``boxes``, ``whiskers``, ``medians`` and ``caps``. @@ -361,7 +361,7 @@ more complicated colorization, you can get each drawn artists by passing } @savefig box_new_colorize.png - df.plot.box(color=color, sym="r+") + df.plot.box(color=color, sym="r+"); .. ipython:: python :suppress: @@ -375,7 +375,7 @@ For example, horizontal and custom-positioned boxplot can be drawn by .. ipython:: python @savefig box_new_kwargs.png - df.plot.box(vert=False, positions=[1, 4, 5, 6, 8]) + df.plot.box(vert=False, positions=[1, 4, 5, 6, 8]); See the :meth:`boxplot <matplotlib.axes.Axes.boxplot>` method and the @@ -622,7 +622,7 @@ too dense to plot each point individually. df["b"] = df["b"] + np.arange(1000) @savefig hexbin_plot.png - df.plot.hexbin(x="a", y="b", gridsize=25) + df.plot.hexbin(x="a", y="b", gridsize=25); A useful keyword argument is ``gridsize``; it controls the number of hexagons @@ -651,7 +651,7 @@ given by column ``z``. The bins are aggregated with NumPy's ``max`` function. df["z"] = np.random.uniform(0, 3, 1000) @savefig hexbin_plot_agg.png - df.plot.hexbin(x="a", y="b", C="z", reduce_C_function=np.max, gridsize=25) + df.plot.hexbin(x="a", y="b", C="z", reduce_C_function=np.max, gridsize=25); .. ipython:: python :suppress: @@ -682,7 +682,7 @@ A ``ValueError`` will be raised if there are any negative values in your data. series = pd.Series(3 * np.random.rand(4), index=["a", "b", "c", "d"], name="series") @savefig series_pie_plot.png - series.plot.pie(figsize=(6, 6)) + series.plot.pie(figsize=(6, 6)); .. ipython:: python :suppress: @@ -713,7 +713,7 @@ drawn in each pie plots by default; specify ``legend=False`` to hide it. ) @savefig df_pie_plot.png - df.plot.pie(subplots=True, figsize=(8, 4)) + df.plot.pie(subplots=True, figsize=(8, 4)); .. ipython:: python :suppress: @@ -746,7 +746,7 @@ Also, other keywords supported by :func:`matplotlib.pyplot.pie` can be used. autopct="%.2f", fontsize=20, figsize=(6, 6), - ) + ); If you pass values whose sum total is less than 1.0, matplotlib draws a semicircle. @@ -762,7 +762,7 @@ If you pass values whose sum total is less than 1.0, matplotlib draws a semicirc series = pd.Series([0.1] * 4, index=["a", "b", "c", "d"], name="series2") @savefig series_pie_plot_semi.png - series.plot.pie(figsize=(6, 6)) + series.plot.pie(figsize=(6, 6)); See the `matplotlib pie documentation <https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.pie>`__ for more. @@ -862,7 +862,7 @@ You can create density plots using the :meth:`Series.plot.kde` and :meth:`DataFr ser = pd.Series(np.random.randn(1000)) @savefig kde_plot.png - ser.plot.kde() + ser.plot.kde(); .. ipython:: python :suppress: @@ -889,10 +889,10 @@ of the same class will usually be closer together and form larger structures. data = pd.read_csv("data/iris.data") - plt.figure() + plt.figure(); @savefig andrews_curves.png - andrews_curves(data, "Name") + andrews_curves(data, "Name"); .. _visualization.parallel_coordinates: @@ -913,10 +913,10 @@ represents one data point. Points that tend to cluster will appear closer togeth data = pd.read_csv("data/iris.data") - plt.figure() + plt.figure(); @savefig parallel_coordinates.png - parallel_coordinates(data, "Name") + parallel_coordinates(data, "Name"); .. ipython:: python :suppress: @@ -943,13 +943,13 @@ be passed, and when ``lag=1`` the plot is essentially ``data[:-1]`` vs. from pandas.plotting import lag_plot - plt.figure() + plt.figure(); spacing = np.linspace(-99 * np.pi, 99 * np.pi, num=1000) data = pd.Series(0.1 * np.random.rand(1000) + 0.9 * np.sin(spacing)) @savefig lag_plot.png - lag_plot(data) + lag_plot(data); .. ipython:: python :suppress: @@ -980,13 +980,13 @@ autocorrelation plots. from pandas.plotting import autocorrelation_plot - plt.figure() + plt.figure(); spacing = np.linspace(-9 * np.pi, 9 * np.pi, num=1000) data = pd.Series(0.7 * np.random.rand(1000) + 0.3 * np.sin(spacing)) @savefig autocorrelation_plot.png - autocorrelation_plot(data) + autocorrelation_plot(data); .. ipython:: python :suppress: @@ -1016,7 +1016,7 @@ are what constitutes the bootstrap plot. data = pd.Series(np.random.rand(1000)) @savefig bootstrap_plot.png - bootstrap_plot(data, size=50, samples=500, color="grey") + bootstrap_plot(data, size=50, samples=500, color="grey"); .. ipython:: python :suppress: @@ -1049,10 +1049,10 @@ for more information. data = pd.read_csv("data/iris.data") - plt.figure() + plt.figure(); @savefig radviz.png - radviz(data, "Name") + radviz(data, "Name"); .. ipython:: python :suppress: @@ -1117,7 +1117,7 @@ shown by default. df = df.cumsum() @savefig frame_plot_basic_noleg.png - df.plot(legend=False) + df.plot(legend=False); .. ipython:: python :suppress: @@ -1137,11 +1137,11 @@ it empty for ylabel. .. ipython:: python :suppress: - plt.figure() + plt.figure(); .. ipython:: python - df.plot() + df.plot(); @savefig plot_xlabel_ylabel.png df.plot(xlabel="new x", ylabel="new y") @@ -1169,7 +1169,7 @@ You may pass ``logy`` to get a log-scale Y axis. ts = np.exp(ts.cumsum()) @savefig series_plot_logy.png - ts.plot(logy=True) + ts.plot(logy=True); .. ipython:: python :suppress: @@ -1190,10 +1190,10 @@ To plot data on a secondary y-axis, use the ``secondary_y`` keyword: .. ipython:: python - df["A"].plot() + df["A"].plot(); @savefig series_plot_secondary_y.png - df["B"].plot(secondary_y=True, style="g") + df["B"].plot(secondary_y=True, style="g"); .. ipython:: python :suppress: @@ -1205,11 +1205,11 @@ keyword: .. ipython:: python - plt.figure() + plt.figure(); ax = df.plot(secondary_y=["A", "B"]) - ax.set_ylabel("CD scale") + ax.set_ylabel("CD scale"); @savefig frame_plot_secondary_y.png - ax.right_ax.set_ylabel("AB scale") + ax.right_ax.set_ylabel("AB scale"); .. ipython:: python :suppress: @@ -1222,10 +1222,10 @@ with "(right)" in the legend. To turn off the automatic marking, use the .. ipython:: python - plt.figure() + plt.figure(); @savefig frame_plot_secondary_y_no_right.png - df.plot(secondary_y=["A", "B"], mark_right=False) + df.plot(secondary_y=["A", "B"], mark_right=False); .. ipython:: python :suppress: @@ -1259,10 +1259,10 @@ Here is the default behavior, notice how the x-axis tick labeling is performed: .. ipython:: python - plt.figure() + plt.figure(); @savefig ser_plot_suppress.png - df["A"].plot() + df["A"].plot(); .. ipython:: python :suppress: @@ -1273,10 +1273,10 @@ Using the ``x_compat`` parameter, you can suppress this behavior: .. ipython:: python - plt.figure() + plt.figure(); @savefig ser_plot_suppress_parm.png - df["A"].plot(x_compat=True) + df["A"].plot(x_compat=True); .. ipython:: python :suppress: @@ -1288,7 +1288,7 @@ in ``pandas.plotting.plot_params`` can be used in a ``with`` statement: .. ipython:: python - plt.figure() + plt.figure(); @savefig ser_plot_suppress_context.png with pd.plotting.plot_params.use("x_compat", True): @@ -1467,7 +1467,7 @@ Here is an example of one way to easily plot group means with standard deviation # Plot fig, ax = plt.subplots() @savefig errorbar_example.png - means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0) + means.plot.bar(yerr=errors, ax=ax, capsize=4, rot=0); .. ipython:: python :suppress: @@ -1493,7 +1493,7 @@ Plotting with matplotlib table is now supported in :meth:`DataFrame.plot` and : ax.xaxis.tick_top() # Display x-axis ticks on top. @savefig line_plot_table_true.png - df.plot(table=True, ax=ax) + df.plot(table=True, ax=ax); .. ipython:: python :suppress: @@ -1511,7 +1511,7 @@ as seen in the example below. ax.xaxis.tick_top() # Display x-axis ticks on top. @savefig line_plot_table_data.png - df.plot(table=np.round(df.T, 2), ax=ax) + df.plot(table=np.round(df.T, 2), ax=ax); .. ipython:: python :suppress: @@ -1529,10 +1529,10 @@ matplotlib `table <https://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes fig, ax = plt.subplots(1, 1) - table(ax, np.round(df.describe(), 2), loc="upper right", colWidths=[0.2, 0.2, 0.2]) + table(ax, np.round(df.describe(), 2), loc="upper right", colWidths=[0.2, 0.2, 0.2]); @savefig line_plot_table_describe.png - df.plot(ax=ax, ylim=(0, 2), legend=None) + df.plot(ax=ax, ylim=(0, 2), legend=None); .. ipython:: python :suppress: @@ -1571,10 +1571,10 @@ To use the cubehelix colormap, we can pass ``colormap='cubehelix'``. df = pd.DataFrame(np.random.randn(1000, 10), index=ts.index) df = df.cumsum() - plt.figure() + plt.figure(); @savefig cubehelix.png - df.plot(colormap="cubehelix") + df.plot(colormap="cubehelix"); .. ipython:: python :suppress: @@ -1587,10 +1587,10 @@ Alternatively, we can pass the colormap itself: from matplotlib import cm - plt.figure() + plt.figure(); @savefig cubehelix_cm.png - df.plot(colormap=cm.cubehelix) + df.plot(colormap=cm.cubehelix); .. ipython:: python :suppress: @@ -1609,10 +1609,10 @@ Colormaps can also be used other plot types, like bar charts: dd = pd.DataFrame(np.random.randn(10, 10)).applymap(abs) dd = dd.cumsum() - plt.figure() + plt.figure(); @savefig greens.png - dd.plot.bar(colormap="Greens") + dd.plot.bar(colormap="Greens"); .. ipython:: python :suppress: @@ -1623,10 +1623,10 @@ Parallel coordinates charts: .. ipython:: python - plt.figure() + plt.figure(); @savefig parallel_gist_rainbow.png - parallel_coordinates(data, "Name", colormap="gist_rainbow") + parallel_coordinates(data, "Name", colormap="gist_rainbow"); .. ipython:: python :suppress: @@ -1637,10 +1637,10 @@ Andrews curves charts: .. ipython:: python - plt.figure() + plt.figure(); @savefig andrews_curve_winter.png - andrews_curves(data, "Name", colormap="winter") + andrews_curves(data, "Name", colormap="winter"); .. ipython:: python :suppress: @@ -1676,12 +1676,12 @@ when plotting a large number of points. ma = price.rolling(20).mean() mstd = price.rolling(20).std() - plt.figure() + plt.figure(); - plt.plot(price.index, price, "k") - plt.plot(ma.index, ma, "b") + plt.plot(price.index, price, "k"); + plt.plot(ma.index, ma, "b"); @savefig bollinger.png - plt.fill_between(mstd.index, ma - 2 * mstd, ma + 2 * mstd, color="b", alpha=0.2) + plt.fill_between(mstd.index, ma - 2 * mstd, ma + 2 * mstd, color="b", alpha=0.2); .. ipython:: python :suppress:
add semicolons (";") after the plotting function to suppress unnecessary debug messages similar to: <matplotlib.axes._subplots.AxesSubplot at 0x7fe278bb5160> - [ ] 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/36043
2020-09-01T15:46:11Z
2020-10-10T17:28:43Z
2020-10-10T17:28:43Z
2022-07-15T23:39:51Z
Backport PR #35999 on branch 1.1.x (BUG: None in Float64Index raising TypeError, should return False)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index b0d375a52f8ac..ad5f647928738 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -29,7 +29,7 @@ Bug fixes - Bug in :class:`Series` constructor raising a ``TypeError`` when constructing sparse datetime64 dtypes (:issue:`35762`) - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) - Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should bw ``""`` (:issue:`35712`) -- +- Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index d6659cc1895b1..569562f5b5037 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -80,7 +80,11 @@ cdef class IndexEngine: values = self._get_index_values() self._check_type(val) - loc = _bin_search(values, val) # .searchsorted(val, side='left') + try: + loc = _bin_search(values, val) # .searchsorted(val, side='left') + except TypeError: + # GH#35788 e.g. val=None with float64 values + raise KeyError(val) if loc >= len(values): raise KeyError(val) if values[loc] != val: diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py index 473e370c76f8b..508bd2f566507 100644 --- a/pandas/tests/indexes/numeric/test_indexing.py +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -228,6 +228,12 @@ def test_take_fill_value_ints(self, klass): class TestContains: + @pytest.mark.parametrize("klass", [Float64Index, Int64Index, UInt64Index]) + def test_contains_none(self, klass): + # GH#35788 should return False, not raise TypeError + index = klass([0, 1, 2, 3, 4]) + assert None not in index + def test_contains_float64_nans(self): index = Float64Index([1.0, 2.0, np.nan]) assert np.nan in index
Backport PR #35999: BUG: None in Float64Index raising TypeError, should return False
https://api.github.com/repos/pandas-dev/pandas/pulls/36041
2020-09-01T15:03:13Z
2020-09-01T16:57:17Z
2020-09-01T16:57:17Z
2020-09-01T16:57:17Z
Backport PR #35938 on branch 1.1.x (REGR: Fix comparison broadcasting over array of Intervals)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index b0d375a52f8ac..c74976b14e814 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -17,6 +17,7 @@ Fixed regressions - Regression in :meth:`DatetimeIndex.intersection` incorrectly raising ``AssertionError`` when intersecting against a list (:issue:`35876`) - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) +- Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 6867e8aba7411..40bd5ad8f5a1f 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -358,6 +358,11 @@ cdef class Interval(IntervalMixin): self_tuple = (self.left, self.right, self.closed) other_tuple = (other.left, other.right, other.closed) return PyObject_RichCompare(self_tuple, other_tuple, op) + elif util.is_array(other): + return np.array( + [PyObject_RichCompare(self, x, op) for x in other], + dtype=bool, + ) return NotImplemented diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index 8603bff0587b6..83dfd42ae2a6e 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1581,3 +1581,10 @@ def test_replace_with_compiled_regex(self): result = df.replace({regex: "z"}, regex=True) expected = pd.DataFrame(["z", "b", "c"]) tm.assert_frame_equal(result, expected) + + def test_replace_intervals(self): + # https://github.com/pandas-dev/pandas/issues/35931 + df = pd.DataFrame({"a": [pd.Interval(0, 1), pd.Interval(0, 1)]}) + result = df.replace({"a": {pd.Interval(0, 1): "x"}}) + expected = pd.DataFrame({"a": ["x", "x"]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/scalar/interval/test_arithmetic.py b/pandas/tests/scalar/interval/test_arithmetic.py index 5252f1a4d5a24..b4c2b448e252a 100644 --- a/pandas/tests/scalar/interval/test_arithmetic.py +++ b/pandas/tests/scalar/interval/test_arithmetic.py @@ -45,3 +45,15 @@ def test_numeric_interval_add_timedelta_raises(interval, delta): with pytest.raises((TypeError, ValueError), match=msg): delta + interval + + +@pytest.mark.parametrize("klass", [timedelta, np.timedelta64, Timedelta]) +def test_timdelta_add_timestamp_interval(klass): + delta = klass(0) + expected = Interval(Timestamp("2020-01-01"), Timestamp("2020-02-01")) + + result = delta + expected + assert result == expected + + result = expected + delta + assert result == expected diff --git a/pandas/tests/scalar/interval/test_interval.py b/pandas/tests/scalar/interval/test_interval.py index a0151bb9ac7bf..8ad9a2c7a9c70 100644 --- a/pandas/tests/scalar/interval/test_interval.py +++ b/pandas/tests/scalar/interval/test_interval.py @@ -2,6 +2,7 @@ import pytest from pandas import Interval, Period, Timedelta, Timestamp +import pandas._testing as tm import pandas.core.common as com @@ -267,3 +268,11 @@ def test_constructor_errors_tz(self, tz_left, tz_right): msg = "left and right must have the same time zone" with pytest.raises(error, match=msg): Interval(left, right) + + def test_equality_comparison_broadcasts_over_array(self): + # https://github.com/pandas-dev/pandas/issues/35931 + interval = Interval(0, 1) + arr = np.array([interval, interval]) + result = interval == arr + expected = np.array([True, True]) + tm.assert_numpy_array_equal(result, expected)
Backport PR #35938: REGR: Fix comparison broadcasting over array of Intervals
https://api.github.com/repos/pandas-dev/pandas/pulls/36039
2020-09-01T14:56:52Z
2020-09-01T18:29:08Z
2020-09-01T18:29:08Z
2020-09-01T18:29:08Z
CI: pin s3fs for Windows py37_np18 on 1.1.x
diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 287d6877b9810..4d134b43760fe 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -29,7 +29,7 @@ dependencies: - pytables - python-dateutil - pytz - - s3fs>=0.4.0 + - s3fs>=0.4.0,<0.5.0 - scipy - sqlalchemy - xlrd
https://api.github.com/repos/pandas-dev/pandas/pulls/36035
2020-09-01T13:52:17Z
2020-09-01T15:26:05Z
2020-09-01T15:26:05Z
2020-09-01T15:26:59Z
TYP: Postponed Evaluation of Annotations (PEP 563)
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 6d6bb21165814..b6603e1a9636b 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -2,6 +2,8 @@ Generic data algorithms. This module is experimental at the moment and not intended for public consumption """ +from __future__ import annotations + import operator from textwrap import dedent from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union @@ -682,7 +684,7 @@ def value_counts( normalize: bool = False, bins=None, dropna: bool = True, -) -> "Series": +) -> Series: """ Compute a histogram of the counts of non-null values. @@ -824,7 +826,7 @@ def duplicated(values, keep="first") -> np.ndarray: return f(values, keep=keep) -def mode(values, dropna: bool = True) -> "Series": +def mode(values, dropna: bool = True) -> Series: """ Returns the mode(s) of an array. @@ -1136,7 +1138,7 @@ class SelectNSeries(SelectN): nordered : Series """ - def compute(self, method: str) -> "Series": + def compute(self, method: str) -> Series: n = self.n dtype = self.obj.dtype @@ -1210,7 +1212,7 @@ def __init__(self, obj, n: int, keep: str, columns): columns = list(columns) self.columns = columns - def compute(self, method: str) -> "DataFrame": + def compute(self, method: str) -> DataFrame: from pandas import Int64Index diff --git a/pandas/core/construction.py b/pandas/core/construction.py index f145e76046bee..02b8ed17244cd 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -4,6 +4,7 @@ These should not depend on core.internals. """ +from __future__ import annotations from collections import abc from typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast @@ -49,16 +50,14 @@ import pandas.core.common as com if TYPE_CHECKING: - from pandas.core.arrays import ExtensionArray # noqa: F401 - from pandas.core.indexes.api import Index # noqa: F401 - from pandas.core.series import Series # noqa: F401 + from pandas import ExtensionArray, Index, Series def array( data: Union[Sequence[object], AnyArrayLike], dtype: Optional[Dtype] = None, copy: bool = True, -) -> "ExtensionArray": +) -> ExtensionArray: """ Create an array. @@ -389,7 +388,7 @@ def extract_array(obj, extract_numpy: bool = False): def sanitize_array( data, - index: Optional["Index"], + index: Optional[Index], dtype: Optional[DtypeObj] = None, copy: bool = False, raise_cast_failure: bool = False, @@ -594,13 +593,13 @@ def is_empty_data(data: Any) -> bool: def create_series_with_explicit_dtype( data: Any = None, - index: Optional[Union[ArrayLike, "Index"]] = None, + index: Optional[Union[ArrayLike, Index]] = None, dtype: Optional[Dtype] = None, name: Optional[str] = None, copy: bool = False, fastpath: bool = False, dtype_if_empty: Dtype = object, -) -> "Series": +) -> Series: """ Helper to pass an explicit dtype when instantiating an empty Series. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 312d449e36022..2d95917049b32 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8,6 +8,7 @@ alignment and a host of useful data manipulation methods having to do with the labeling information """ +from __future__ import annotations import collections from collections import abc @@ -885,7 +886,7 @@ def to_string( # ---------------------------------------------------------------------- @property - def style(self) -> "Styler": + def style(self) -> Styler: """ Returns a Styler object. @@ -6530,7 +6531,7 @@ def groupby( squeeze: bool = no_default, observed: bool = False, dropna: bool = True, - ) -> "DataFrameGroupBy": + ) -> DataFrameGroupBy: from pandas.core.groupby.generic import DataFrameGroupBy if squeeze is not no_default: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3bad2d6dd18b9..42b4f06ee5334 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import collections from datetime import timedelta import functools @@ -110,7 +112,7 @@ from pandas._libs.tslibs import BaseOffset from pandas.core.resample import Resampler - from pandas.core.series import Series # noqa: F401 + from pandas.core.series import Series from pandas.core.window.indexers import BaseIndexer # goal is to be able to define the docs close to function, while still being @@ -391,7 +393,7 @@ def _get_block_manager_axis(cls, axis: Axis) -> int: return m - axis return axis - def _get_axis_resolvers(self, axis: str) -> Dict[str, Union["Series", MultiIndex]]: + def _get_axis_resolvers(self, axis: str) -> Dict[str, Union[Series, MultiIndex]]: # index or columns axis_index = getattr(self, axis) d = dict() @@ -421,10 +423,10 @@ def _get_axis_resolvers(self, axis: str) -> Dict[str, Union["Series", MultiIndex d[axis] = dindex return d - def _get_index_resolvers(self) -> Dict[str, Union["Series", MultiIndex]]: + def _get_index_resolvers(self) -> Dict[str, Union[Series, MultiIndex]]: from pandas.core.computation.parsing import clean_column_name - d: Dict[str, Union["Series", MultiIndex]] = {} + d: Dict[str, Union[Series, MultiIndex]] = {} for axis_name in self._AXIS_ORDERS: d.update(self._get_axis_resolvers(axis_name)) @@ -660,7 +662,7 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: result = self.set_axis(new_labels, axis=axis, inplace=False) return result - def pop(self, item: Label) -> Union["Series", Any]: + def pop(self, item: Label) -> Union[Series, Any]: result = self[item] del self[item] if self.ndim == 2: @@ -7678,7 +7680,7 @@ def resample( level=None, origin: Union[str, TimestampConvertibleTypes] = "start_day", offset: Optional[TimedeltaConvertibleTypes] = None, - ) -> "Resampler": + ) -> Resampler: """ Resample time-series data. @@ -10451,7 +10453,7 @@ def mad(self, axis=None, skipna=None, level=None): @doc(Rolling) def rolling( self, - window: "Union[int, timedelta, BaseOffset, BaseIndexer]", + window: Union[int, timedelta, BaseOffset, BaseIndexer], min_periods: Optional[int] = None, center: bool_t = False, win_type: Optional[str] = None,
a few files as POC/for discussion from https://www.python.org/dev/peps/pep-0563/ > PEP 3107 added support for arbitrary annotations on parts of a function definition. Just like default values, annotations are evaluated at function definition time. This creates a number of issues for the type hinting use case: > - forward references: when a type hint contains names that have not been defined yet, that definition needs to be expressed as a string literal; > - type hints are executed at module import time, which is not computationally free. > Postponing the evaluation of annotations solves both problems.
https://api.github.com/repos/pandas-dev/pandas/pulls/36034
2020-09-01T10:47:32Z
2020-09-02T21:31:48Z
2020-09-02T21:31:48Z
2020-09-03T08:51:04Z
remove trailing commas for #35925
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 7f0eef039a1e8..f2ce2f056ce82 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -128,7 +128,7 @@ def write( self.api.parquet.write_table(table, path, compression=compression, **kwargs) def read( - self, path, columns=None, storage_options: StorageOptions = None, **kwargs, + self, path, columns=None, storage_options: StorageOptions = None, **kwargs ): if is_fsspec_url(path) and "filesystem" not in kwargs: import_optional_dependency("fsspec") @@ -218,7 +218,7 @@ def write( ) def read( - self, path, columns=None, storage_options: StorageOptions = None, **kwargs, + self, path, columns=None, storage_options: StorageOptions = None, **kwargs ): if is_fsspec_url(path): fsspec = import_optional_dependency("fsspec") diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 983aa56324083..9ad527684120e 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1967,10 +1967,6 @@ def _do_date_conversions(self, names, data): class CParserWrapper(ParserBase): - """ - - """ - def __init__(self, src, **kwds): self.kwds = kwds kwds = kwds.copy() diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index f08e0514a68e1..0913627324c48 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2931,7 +2931,7 @@ def read_index_node( # If the index was an empty array write_array_empty() will # have written a sentinel. Here we replace it with the original. if "shape" in node._v_attrs and np.prod(node._v_attrs.shape) == 0: - data = np.empty(node._v_attrs.shape, dtype=node._v_attrs.value_type,) + data = np.empty(node._v_attrs.shape, dtype=node._v_attrs.value_type) kind = _ensure_decoded(node._v_attrs.kind) name = None @@ -4103,7 +4103,7 @@ def create_description( return d def read_coordinates( - self, where=None, start: Optional[int] = None, stop: Optional[int] = None, + self, where=None, start: Optional[int] = None, stop: Optional[int] = None ): """ select coordinates (row numbers) from a table; return the @@ -4374,7 +4374,7 @@ def write_data_chunk( self.table.flush() def delete( - self, where=None, start: Optional[int] = None, stop: Optional[int] = None, + self, where=None, start: Optional[int] = None, stop: Optional[int] = None ): # delete all rows (and return the nrows) @@ -4805,7 +4805,7 @@ def _convert_index(name: str, index: Index, encoding: str, errors: str) -> Index if inferred_type == "date": converted = np.asarray([v.toordinal() for v in values], dtype=np.int32) return IndexCol( - name, converted, "date", _tables().Time32Col(), index_name=index_name, + name, converted, "date", _tables().Time32Col(), index_name=index_name ) elif inferred_type == "string": @@ -4821,13 +4821,13 @@ def _convert_index(name: str, index: Index, encoding: str, errors: str) -> Index elif inferred_type in ["integer", "floating"]: return IndexCol( - name, values=converted, kind=kind, typ=atom, index_name=index_name, + name, values=converted, kind=kind, typ=atom, index_name=index_name ) else: assert isinstance(converted, np.ndarray) and converted.dtype == object assert kind == "object", kind atom = _tables().ObjectAtom() - return IndexCol(name, converted, kind, atom, index_name=index_name,) + return IndexCol(name, converted, kind, atom, index_name=index_name) def _unconvert_index(
- [x] pandas/io/parquet.py - [x] pandas/io/parsers.py - [x] pandas/io/pytables.py
https://api.github.com/repos/pandas-dev/pandas/pulls/36029
2020-09-01T07:15:29Z
2020-09-01T16:36:51Z
2020-09-01T16:36:51Z
2020-09-01T16:46:34Z
DOC: Update documentation for pd.Interval if string endpoints are not allowed anymore
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 40bd5ad8f5a1f..931ad8326c371 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -291,12 +291,6 @@ cdef class Interval(IntervalMixin): True >>> year_2017.length Timedelta('365 days 00:00:00') - - And also you can create string intervals - - >>> volume_1 = pd.Interval('Ant', 'Dog', closed='both') - >>> 'Bee' in volume_1 - True """ _typ = "interval" __array_priority__ = 1000
- [X] closes #36002 - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Removed outdated example in documentation for pd.Interval (string endpoints are not allowed anymore).
https://api.github.com/repos/pandas-dev/pandas/pulls/36026
2020-09-01T05:19:17Z
2020-09-01T16:15:27Z
2020-09-01T16:15:26Z
2020-09-01T16:15:33Z
TYP: add type annotation to `_xlwt.py` #36024
diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py index 78efe77e9fe2d..e1f72eb533c51 100644 --- a/pandas/io/excel/_xlwt.py +++ b/pandas/io/excel/_xlwt.py @@ -1,8 +1,13 @@ +from typing import TYPE_CHECKING, Dict + import pandas._libs.json as json from pandas.io.excel._base import ExcelWriter from pandas.io.excel._util import _validate_freeze_panes +if TYPE_CHECKING: + from xlwt import XFStyle + class _XlwtWriter(ExcelWriter): engine = "xlwt" @@ -29,12 +34,11 @@ def save(self): """ Save workbook to disk. """ - return self.book.save(self.path) + self.book.save(self.path) def write_cells( self, cells, sheet_name=None, startrow=0, startcol=0, freeze_panes=None ): - # Write the frame cells using xlwt. sheet_name = self._get_sheet_name(sheet_name) @@ -49,7 +53,7 @@ def write_cells( wks.set_horz_split_pos(freeze_panes[0]) wks.set_vert_split_pos(freeze_panes[1]) - style_dict = {} + style_dict: Dict[str, XFStyle] = {} for cell in cells: val, fmt = self._value_with_fmt(cell.val) @@ -101,14 +105,14 @@ def _style_to_xlwt( f"{key}: {cls._style_to_xlwt(value, False)}" for key, value in item.items() ] - out = f"{(line_sep).join(it)} " + out = f"{line_sep.join(it)} " return out else: it = [ f"{key} {cls._style_to_xlwt(value, False)}" for key, value in item.items() ] - out = f"{(field_sep).join(it)} " + out = f"{field_sep.join(it)} " return out else: item = f"{item}" diff --git a/setup.cfg b/setup.cfg index c10624d60aaff..2447a91f88f4e 100644 --- a/setup.cfg +++ b/setup.cfg @@ -223,9 +223,6 @@ check_untyped_defs=False [mypy-pandas.io.excel._util] check_untyped_defs=False -[mypy-pandas.io.excel._xlwt] -check_untyped_defs=False - [mypy-pandas.io.formats.console] check_untyped_defs=False
- [x] closes #36024 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` pandas\io\excel\_xlwt.py:52: error: Need type annotation for 'style_dict' (hint: "style_dict: Dict[<type>, <type>] = ...") [var-annotated]
https://api.github.com/repos/pandas-dev/pandas/pulls/36025
2020-09-01T05:01:30Z
2020-09-01T16:06:11Z
2020-09-01T16:06:11Z
2020-09-02T01:06:26Z
Comma cleanup for #35925
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 52a1e3aae9058..b0ba0d991c9b0 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -86,11 +86,7 @@ def wrapper(x): result0 = f(axis=0, skipna=False) result1 = f(axis=1, skipna=False) tm.assert_series_equal( - result0, - frame.apply(wrapper), - check_dtype=check_dtype, - rtol=rtol, - atol=atol, + result0, frame.apply(wrapper), check_dtype=check_dtype, rtol=rtol, atol=atol ) # HACK: win32 tm.assert_series_equal( @@ -116,7 +112,7 @@ def wrapper(x): if opname in ["sum", "prod"]: expected = frame.apply(skipna_wrapper, axis=1) tm.assert_series_equal( - result1, expected, check_dtype=False, rtol=rtol, atol=atol, + result1, expected, check_dtype=False, rtol=rtol, atol=atol ) # check dtypes diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index c8f5b2b0f6364..0d1004809f7f1 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -932,7 +932,7 @@ def test_constructor_mrecarray(self): # from GH3479 assert_fr_equal = functools.partial( - tm.assert_frame_equal, check_index_type=True, check_column_type=True, + tm.assert_frame_equal, check_index_type=True, check_column_type=True ) arrays = [ ("float", np.array([1.5, 2.0])), diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 6a8f1e7c1aca2..d80ebaa09b6a8 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -417,7 +417,7 @@ def test_unstack_mixed_type_name_in_multiindex( result = df.unstack(unstack_idx) expected = pd.DataFrame( - expected_values, columns=expected_columns, index=expected_index, + expected_values, columns=expected_columns, index=expected_index ) tm.assert_frame_equal(result, expected) @@ -807,7 +807,7 @@ def test_unstack_multi_level_cols(self): [["B", "C"], ["B", "D"]], names=["c1", "c2"] ), index=pd.MultiIndex.from_tuples( - [[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"], + [[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"] ), ) assert df.unstack(["i2", "i1"]).columns.names[-2:] == ["i2", "i1"]
Comma cleanup for #35925
https://api.github.com/repos/pandas-dev/pandas/pulls/36023
2020-09-01T03:16:46Z
2020-09-01T12:38:28Z
2020-09-01T12:38:28Z
2020-09-01T18:22:18Z
TYP/CLN: cleanup `_openpyxl.py`, add type annotation #36021
diff --git a/ci/deps/azure-37-locale_slow.yaml b/ci/deps/azure-37-locale_slow.yaml index 8000f3e6b9a9c..fbb1ea671d696 100644 --- a/ci/deps/azure-37-locale_slow.yaml +++ b/ci/deps/azure-37-locale_slow.yaml @@ -18,7 +18,7 @@ dependencies: - lxml - matplotlib=3.0.0 - numpy=1.16.* - - openpyxl=2.5.7 + - openpyxl=2.6.0 - python-dateutil - python-blosc - pytz=2017.3 diff --git a/ci/deps/azure-37-minimum_versions.yaml b/ci/deps/azure-37-minimum_versions.yaml index 05b1957198bc4..31f82f3304db3 100644 --- a/ci/deps/azure-37-minimum_versions.yaml +++ b/ci/deps/azure-37-minimum_versions.yaml @@ -19,7 +19,7 @@ dependencies: - numba=0.46.0 - numexpr=2.6.8 - numpy=1.16.5 - - openpyxl=2.5.7 + - openpyxl=2.6.0 - pytables=3.4.4 - python-dateutil=2.7.3 - pytz=2017.3 diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 4c270117e079e..c9ac1b0d284a3 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -274,7 +274,7 @@ html5lib 1.0.1 HTML parser for read_html (see :ref lxml 4.3.0 HTML parser for read_html (see :ref:`note <optional_html>`) matplotlib 2.2.3 Visualization numba 0.46.0 Alternative execution engine for rolling operations -openpyxl 2.5.7 Reading / writing for xlsx files +openpyxl 2.6.0 Reading / writing for xlsx files pandas-gbq 0.12.0 Google Big Query access psycopg2 2.7 PostgreSQL engine for sqlalchemy pyarrow 0.15.0 Parquet, ORC, and feather reading / writing diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 1617bf66c4f04..76bebd4a9a1cb 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -109,7 +109,7 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+---------+ | numba | 0.46.0 | | +-----------------+-----------------+---------+ -| openpyxl | 2.5.7 | | +| openpyxl | 2.6.0 | X | +-----------------+-----------------+---------+ | pyarrow | 0.15.0 | X | +-----------------+-----------------+---------+ diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index c2730536af8a3..3c67902d41baa 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -1,4 +1,4 @@ -from typing import List +from typing import TYPE_CHECKING, Dict, List, Optional import numpy as np @@ -8,6 +8,9 @@ from pandas.io.excel._base import ExcelWriter, _BaseExcelReader from pandas.io.excel._util import _validate_freeze_panes +if TYPE_CHECKING: + from openpyxl.descriptors.serialisable import Serialisable + class _OpenpyxlWriter(ExcelWriter): engine = "openpyxl" @@ -22,53 +25,22 @@ def __init__(self, path, engine=None, mode="w", **engine_kwargs): if self.mode == "a": # Load from existing workbook from openpyxl import load_workbook - book = load_workbook(self.path) - self.book = book + self.book = load_workbook(self.path) else: # Create workbook object with default optimized_write=True. self.book = Workbook() if self.book.worksheets: - try: - self.book.remove(self.book.worksheets[0]) - except AttributeError: - - # compat - for openpyxl <= 2.4 - self.book.remove_sheet(self.book.worksheets[0]) + self.book.remove(self.book.worksheets[0]) def save(self): """ Save workbook to disk. """ - return self.book.save(self.path) - - @classmethod - def _convert_to_style(cls, style_dict): - """ - Converts a style_dict to an openpyxl style object. - - Parameters - ---------- - style_dict : style dictionary to convert - """ - from openpyxl.style import Style - - xls_style = Style() - for key, value in style_dict.items(): - for nk, nv in value.items(): - if key == "borders": - ( - xls_style.borders.__getattribute__(nk).__setattr__( - "border_style", nv - ) - ) - else: - xls_style.__getattribute__(key).__setattr__(nk, nv) - - return xls_style + self.book.save(self.path) @classmethod - def _convert_to_style_kwargs(cls, style_dict): + def _convert_to_style_kwargs(cls, style_dict: dict) -> Dict[str, "Serialisable"]: """ Convert a style_dict to a set of kwargs suitable for initializing or updating-on-copy an openpyxl v2 style object. @@ -93,7 +65,7 @@ def _convert_to_style_kwargs(cls, style_dict): """ _style_key_map = {"borders": "border"} - style_kwargs = {} + style_kwargs: Dict[str, Serialisable] = {} for k, v in style_dict.items(): if k in _style_key_map: k = _style_key_map[k] @@ -404,7 +376,7 @@ def write_cells( # Write the frame cells using openpyxl. sheet_name = self._get_sheet_name(sheet_name) - _style_cache = {} + _style_cache: Dict[str, Dict[str, Serialisable]] = {} if sheet_name in self.sheets: wks = self.sheets[sheet_name] @@ -426,7 +398,7 @@ def write_cells( if fmt: xcell.number_format = fmt - style_kwargs = {} + style_kwargs: Optional[Dict[str, Serialisable]] = {} if cell.style: key = str(cell.style) style_kwargs = _style_cache.get(key) @@ -515,16 +487,17 @@ def get_sheet_by_index(self, index: int): def _convert_cell(self, cell, convert_float: bool) -> Scalar: - # TODO: replace with openpyxl constants + from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC + if cell.is_date: return cell.value - elif cell.data_type == "e": + elif cell.data_type == TYPE_ERROR: return np.nan - elif cell.data_type == "b": + elif cell.data_type == TYPE_BOOL: return bool(cell.value) elif cell.value is None: return "" # compat with xlrd - elif cell.data_type == "n": + elif cell.data_type == TYPE_NUMERIC: # GH5394 if convert_float: val = int(cell.value) diff --git a/setup.cfg b/setup.cfg index c10624d60aaff..e346a625911c5 100644 --- a/setup.cfg +++ b/setup.cfg @@ -217,9 +217,6 @@ check_untyped_defs=False [mypy-pandas.io.excel._base] check_untyped_defs=False -[mypy-pandas.io.excel._openpyxl] -check_untyped_defs=False - [mypy-pandas.io.excel._util] check_untyped_defs=False
- [x] closes #36021 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/36022
2020-09-01T02:58:11Z
2020-09-01T19:36:21Z
2020-09-01T19:36:21Z
2020-09-02T01:04:42Z
REF: implement Block._replace_list
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 1b42df1b0147c..ad388ef3f53b0 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -788,6 +788,43 @@ def _replace_single(self, *args, **kwargs): """ no-op on a non-ObjectBlock """ return self if kwargs["inplace"] else self.copy() + def _replace_list( + self, + src_list: List[Any], + dest_list: List[Any], + masks: List[np.ndarray], + inplace: bool = False, + regex: bool = False, + ) -> List["Block"]: + """ + See BlockManager._replace_list docstring. + """ + src_len = len(src_list) - 1 + + rb = [self if inplace else self.copy()] + for i, (src, dest) in enumerate(zip(src_list, dest_list)): + new_rb: List["Block"] = [] + for blk in rb: + m = masks[i][blk.mgr_locs.indexer] + convert = i == src_len # only convert once at the end + result = blk._replace_coerce( + mask=m, + to_replace=src, + value=dest, + inplace=inplace, + convert=convert, + regex=regex, + ) + if m.any() or convert: + if isinstance(result, list): + new_rb.extend(result) + else: + new_rb.append(result) + else: + new_rb.append(blk) + rb = new_rb + return rb + def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 00321b76cb6bf..389252e7ef0f2 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -3,6 +3,7 @@ import operator import re from typing import ( + Any, DefaultDict, Dict, List, @@ -600,8 +601,12 @@ def replace(self, value, **kwargs) -> "BlockManager": return self.apply("replace", value=value, **kwargs) def replace_list( - self, src_list, dest_list, inplace: bool = False, regex: bool = False - ) -> "BlockManager": + self: T, + src_list: List[Any], + dest_list: List[Any], + inplace: bool = False, + regex: bool = False, + ) -> T: """ do a list replace """ inplace = validate_bool_kwarg(inplace, "inplace") @@ -625,34 +630,14 @@ def comp(s: Scalar, mask: np.ndarray, regex: bool = False): masks = [comp(s, mask, regex) for s in src_list] - result_blocks = [] - src_len = len(src_list) - 1 - for blk in self.blocks: - - # its possible to get multiple result blocks here - # replace ALWAYS will return a list - rb = [blk if inplace else blk.copy()] - for i, (s, d) in enumerate(zip(src_list, dest_list)): - new_rb: List[Block] = [] - for b in rb: - m = masks[i][b.mgr_locs.indexer] - convert = i == src_len # only convert once at the end - result = b._replace_coerce( - mask=m, - to_replace=s, - value=d, - inplace=inplace, - convert=convert, - regex=regex, - ) - if m.any() or convert: - new_rb = _extend_blocks(result, new_rb) - else: - new_rb.append(b) - rb = new_rb - result_blocks.extend(rb) - - bm = type(self).from_blocks(result_blocks, self.axes) + bm = self.apply( + "_replace_list", + src_list=src_list, + dest_list=dest_list, + masks=masks, + inplace=inplace, + regex=regex, + ) bm._consolidate_inplace() return bm
So we can re-use BlockManager.apply for the block iteration.
https://api.github.com/repos/pandas-dev/pandas/pulls/36020
2020-09-01T01:30:38Z
2020-09-01T23:31:10Z
2020-09-01T23:31:10Z
2020-09-02T00:55:52Z
TYP: annotate plotting._matplotlib.misc
diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index bb6530b0f6412..c5e7c55970c3e 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -1,18 +1,27 @@ import random +from typing import TYPE_CHECKING, Dict, List, Optional, Set import matplotlib.lines as mlines import matplotlib.patches as patches import numpy as np +from pandas._typing import Label + from pandas.core.dtypes.missing import notna from pandas.io.formats.printing import pprint_thing from pandas.plotting._matplotlib.style import _get_standard_colors from pandas.plotting._matplotlib.tools import _set_ticks_props, _subplots +if TYPE_CHECKING: + from matplotlib.axes import Axes + from matplotlib.figure import Figure + + from pandas import DataFrame, Series + def scatter_matrix( - frame, + frame: "DataFrame", alpha=0.5, figsize=None, ax=None, @@ -114,7 +123,14 @@ def _get_marker_compat(marker): return marker -def radviz(frame, class_column, ax=None, color=None, colormap=None, **kwds): +def radviz( + frame: "DataFrame", + class_column, + ax: Optional["Axes"] = None, + color=None, + colormap=None, + **kwds, +) -> "Axes": import matplotlib.pyplot as plt def normalize(series): @@ -130,7 +146,7 @@ def normalize(series): if ax is None: ax = plt.gca(xlim=[-1, 1], ylim=[-1, 1]) - to_plot = {} + to_plot: Dict[Label, List[List]] = {} colors = _get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color ) @@ -197,8 +213,14 @@ def normalize(series): def andrews_curves( - frame, class_column, ax=None, samples=200, color=None, colormap=None, **kwds -): + frame: "DataFrame", + class_column, + ax: Optional["Axes"] = None, + samples: int = 200, + color=None, + colormap=None, + **kwds, +) -> "Axes": import matplotlib.pyplot as plt def function(amplitudes): @@ -231,7 +253,7 @@ def f(t): classes = frame[class_column].drop_duplicates() df = frame.drop(class_column, axis=1) t = np.linspace(-np.pi, np.pi, samples) - used_legends = set() + used_legends: Set[str] = set() color_values = _get_standard_colors( num_colors=len(classes), colormap=colormap, color_type="random", color=color @@ -256,7 +278,13 @@ def f(t): return ax -def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): +def bootstrap_plot( + series: "Series", + fig: Optional["Figure"] = None, + size: int = 50, + samples: int = 500, + **kwds, +) -> "Figure": import matplotlib.pyplot as plt @@ -306,19 +334,19 @@ def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): def parallel_coordinates( - frame, + frame: "DataFrame", class_column, cols=None, - ax=None, + ax: Optional["Axes"] = None, color=None, use_columns=False, xticks=None, colormap=None, - axvlines=True, + axvlines: bool = True, axvlines_kwds=None, - sort_labels=False, + sort_labels: bool = False, **kwds, -): +) -> "Axes": import matplotlib.pyplot as plt if axvlines_kwds is None: @@ -333,7 +361,7 @@ def parallel_coordinates( else: df = frame[cols] - used_legends = set() + used_legends: Set[str] = set() ncols = len(df.columns) @@ -385,7 +413,9 @@ def parallel_coordinates( return ax -def lag_plot(series, lag=1, ax=None, **kwds): +def lag_plot( + series: "Series", lag: int = 1, ax: Optional["Axes"] = None, **kwds +) -> "Axes": # workaround because `c='b'` is hardcoded in matplotlib's scatter method import matplotlib.pyplot as plt @@ -402,7 +432,9 @@ def lag_plot(series, lag=1, ax=None, **kwds): return ax -def autocorrelation_plot(series, ax=None, **kwds): +def autocorrelation_plot( + series: "Series", ax: Optional["Axes"] = None, **kwds +) -> "Axes": import matplotlib.pyplot as plt n = len(series) diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 7990bff4f517c..5f1105f0e4233 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -11,7 +11,7 @@ def _get_standard_colors( - num_colors=None, colormap=None, color_type="default", color=None + num_colors=None, colormap=None, color_type: str = "default", color=None ): import matplotlib.pyplot as plt
https://api.github.com/repos/pandas-dev/pandas/pulls/36017
2020-08-31T22:46:43Z
2020-09-01T16:39:55Z
2020-09-01T16:39:55Z
2020-09-01T16:43:16Z
TYP: Annotate plotting stacker
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index b33daf39de37c..01fe98a6f5403 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -1,4 +1,5 @@ from collections import namedtuple +from typing import TYPE_CHECKING import warnings from matplotlib.artist import setp @@ -14,6 +15,9 @@ from pandas.plotting._matplotlib.style import _get_standard_colors from pandas.plotting._matplotlib.tools import _flatten, _subplots +if TYPE_CHECKING: + from matplotlib.axes import Axes + class BoxPlot(LinePlot): _kind = "box" @@ -150,7 +154,7 @@ def _make_plot(self): labels = [pprint_thing(key) for key in range(len(labels))] self._set_ticklabels(ax, labels) - def _set_ticklabels(self, ax, labels): + def _set_ticklabels(self, ax: "Axes", labels): if self.orientation == "vertical": ax.set_xticklabels(labels) else: @@ -292,7 +296,7 @@ def maybe_color_bp(bp, **kwds): if not kwds.get("capprops"): setp(bp["caps"], color=colors[3], alpha=1) - def plot_group(keys, values, ax): + def plot_group(keys, values, ax: "Axes"): keys = [pprint_thing(x) for x in keys] values = [np.asarray(remove_na_arraylike(v), dtype=object) for v in values] bp = ax.boxplot(values, **kwds) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 4d23a5e5fc249..93ba9bd26630b 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1,5 +1,5 @@ import re -from typing import TYPE_CHECKING, List, Optional +from typing import TYPE_CHECKING, List, Optional, Tuple import warnings from matplotlib.artist import Artist @@ -45,6 +45,7 @@ if TYPE_CHECKING: from matplotlib.axes import Axes + from matplotlib.axis import Axis class MPLPlot: @@ -68,16 +69,10 @@ def _kind(self): _pop_attributes = [ "label", "style", - "logy", - "logx", - "loglog", "mark_right", "stacked", ] _attr_defaults = { - "logy": False, - "logx": False, - "loglog": False, "mark_right": True, "stacked": False, } @@ -167,6 +162,9 @@ def __init__( self.legend_handles: List[Artist] = [] self.legend_labels: List[Label] = [] + self.logx = kwds.pop("logx", False) + self.logy = kwds.pop("logy", False) + self.loglog = kwds.pop("loglog", False) for attr in self._pop_attributes: value = kwds.pop(attr, self._attr_defaults.get(attr, None)) setattr(self, attr, value) @@ -283,11 +281,11 @@ def generate(self): def _args_adjust(self): pass - def _has_plotted_object(self, ax): + def _has_plotted_object(self, ax: "Axes") -> bool: """check whether ax has data""" return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0 - def _maybe_right_yaxis(self, ax, axes_num): + def _maybe_right_yaxis(self, ax: "Axes", axes_num): if not self.on_right(axes_num): # secondary axes may be passed via ax kw return self._get_ax_layer(ax) @@ -523,7 +521,7 @@ def _adorn_subplots(self): raise ValueError(msg) self.axes[0].set_title(self.title) - def _apply_axis_properties(self, axis, rot=None, fontsize=None): + def _apply_axis_properties(self, axis: "Axis", rot=None, fontsize=None): """ Tick creation within matplotlib is reasonably expensive and is internally deferred until accessed as Ticks are created/destroyed @@ -540,7 +538,7 @@ def _apply_axis_properties(self, axis, rot=None, fontsize=None): label.set_fontsize(fontsize) @property - def legend_title(self): + def legend_title(self) -> Optional[str]: if not isinstance(self.data.columns, ABCMultiIndex): name = self.data.columns.name if name is not None: @@ -591,7 +589,7 @@ def _make_legend(self): if ax.get_visible(): ax.legend(loc="best") - def _get_ax_legend_handle(self, ax): + def _get_ax_legend_handle(self, ax: "Axes"): """ Take in axes and return ax, legend and handle under different scenarios """ @@ -616,7 +614,7 @@ def plt(self): _need_to_set_index = False - def _get_xticks(self, convert_period=False): + def _get_xticks(self, convert_period: bool = False): index = self.data.index is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time") @@ -646,7 +644,7 @@ def _get_xticks(self, convert_period=False): @classmethod @register_pandas_matplotlib_converters - def _plot(cls, ax, x, y, style=None, is_errorbar=False, **kwds): + def _plot(cls, ax: "Axes", x, y, style=None, is_errorbar: bool = False, **kwds): mask = isna(y) if mask.any(): y = np.ma.array(y) @@ -667,10 +665,10 @@ def _plot(cls, ax, x, y, style=None, is_errorbar=False, **kwds): if style is not None: args = (x, y, style) else: - args = (x, y) + args = (x, y) # type:ignore[assignment] return ax.plot(*args, **kwds) - def _get_index_name(self): + def _get_index_name(self) -> Optional[str]: if isinstance(self.data.index, ABCMultiIndex): name = self.data.index.names if com.any_not_none(*name): @@ -877,7 +875,7 @@ def _get_subplots(self): ax for ax in self.axes[0].get_figure().get_axes() if isinstance(ax, Subplot) ] - def _get_axes_layout(self): + def _get_axes_layout(self) -> Tuple[int, int]: axes = self._get_subplots() x_set = set() y_set = set() @@ -916,15 +914,15 @@ def __init__(self, data, x, y, **kwargs): self.y = y @property - def nseries(self): + def nseries(self) -> int: return 1 - def _post_plot_logic(self, ax, data): + def _post_plot_logic(self, ax: "Axes", data): x, y = self.x, self.y ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) - def _plot_colorbar(self, ax, **kwds): + def _plot_colorbar(self, ax: "Axes", **kwds): # Addresses issues #10611 and #10678: # When plotting scatterplots and hexbinplots in IPython # inline backend the colorbar axis height tends not to @@ -1080,7 +1078,7 @@ def __init__(self, data, **kwargs): if "x_compat" in self.kwds: self.x_compat = bool(self.kwds.pop("x_compat")) - def _is_ts_plot(self): + def _is_ts_plot(self) -> bool: # this is slightly deceptive return not self.x_compat and self.use_index and self._use_dynamic_x() @@ -1139,7 +1137,9 @@ def _make_plot(self): ax.set_xlim(left, right) @classmethod - def _plot(cls, ax, x, y, style=None, column_num=None, stacking_id=None, **kwds): + def _plot( + cls, ax: "Axes", x, y, style=None, column_num=None, stacking_id=None, **kwds + ): # column_num is used to get the target column from plotf in line and # area plots if column_num == 0: @@ -1183,7 +1183,7 @@ def _get_stacking_id(self): return None @classmethod - def _initialize_stacker(cls, ax, stacking_id, n): + def _initialize_stacker(cls, ax: "Axes", stacking_id, n: int): if stacking_id is None: return if not hasattr(ax, "_stacker_pos_prior"): @@ -1194,7 +1194,7 @@ def _initialize_stacker(cls, ax, stacking_id, n): ax._stacker_neg_prior[stacking_id] = np.zeros(n) @classmethod - def _get_stacked_values(cls, ax, stacking_id, values, label): + def _get_stacked_values(cls, ax: "Axes", stacking_id, values, label): if stacking_id is None: return values if not hasattr(ax, "_stacker_pos_prior"): @@ -1213,7 +1213,7 @@ def _get_stacked_values(cls, ax, stacking_id, values, label): ) @classmethod - def _update_stacker(cls, ax, stacking_id, values): + def _update_stacker(cls, ax: "Axes", stacking_id, values): if stacking_id is None: return if (values >= 0).all(): @@ -1221,7 +1221,7 @@ def _update_stacker(cls, ax, stacking_id, values): elif (values <= 0).all(): ax._stacker_neg_prior[stacking_id] += values - def _post_plot_logic(self, ax, data): + def _post_plot_logic(self, ax: "Axes", data): from matplotlib.ticker import FixedLocator def get_label(i): @@ -1276,7 +1276,7 @@ def __init__(self, data, **kwargs): @classmethod def _plot( cls, - ax, + ax: "Axes", x, y, style=None, @@ -1318,7 +1318,7 @@ def _plot( res = [rect] return res - def _post_plot_logic(self, ax, data): + def _post_plot_logic(self, ax: "Axes", data): LinePlot._post_plot_logic(self, ax, data) if self.ylim is None: @@ -1372,7 +1372,7 @@ def _args_adjust(self): self.left = np.array(self.left) @classmethod - def _plot(cls, ax, x, y, w, start=0, log=False, **kwds): + def _plot(cls, ax: "Axes", x, y, w, start=0, log=False, **kwds): return ax.bar(x, y, w, bottom=start, log=log, **kwds) @property @@ -1454,7 +1454,7 @@ def _make_plot(self): ) self._add_legend_handle(rect, label, index=i) - def _post_plot_logic(self, ax, data): + def _post_plot_logic(self, ax: "Axes", data): if self.use_index: str_index = [pprint_thing(key) for key in data.index] else: @@ -1466,7 +1466,7 @@ def _post_plot_logic(self, ax, data): self._decorate_ticks(ax, name, str_index, s_edge, e_edge) - def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge): + def _decorate_ticks(self, ax: "Axes", name, ticklabels, start_edge, end_edge): ax.set_xlim((start_edge, end_edge)) if self.xticks is not None: @@ -1489,10 +1489,10 @@ def _start_base(self): return self.left @classmethod - def _plot(cls, ax, x, y, w, start=0, log=False, **kwds): + def _plot(cls, ax: "Axes", x, y, w, start=0, log=False, **kwds): return ax.barh(x, y, w, left=start, log=log, **kwds) - def _decorate_ticks(self, ax, name, ticklabels, start_edge, end_edge): + def _decorate_ticks(self, ax: "Axes", name, ticklabels, start_edge, end_edge): # horizontal bars ax.set_ylim((start_edge, end_edge)) ax.set_yticks(self.tick_pos) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index ee41479b3c7c9..ffd46d1b191db 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -1,3 +1,5 @@ +from typing import TYPE_CHECKING + import numpy as np from pandas.core.dtypes.common import is_integer, is_list_like @@ -8,6 +10,9 @@ from pandas.plotting._matplotlib.core import LinePlot, MPLPlot from pandas.plotting._matplotlib.tools import _flatten, _set_ticks_props, _subplots +if TYPE_CHECKING: + from matplotlib.axes import Axes + class HistPlot(LinePlot): _kind = "hist" @@ -90,7 +95,7 @@ def _make_plot_keywords(self, kwds, y): kwds["bins"] = self.bins return kwds - def _post_plot_logic(self, ax, data): + def _post_plot_logic(self, ax: "Axes", data): if self.orientation == "horizontal": ax.set_xlabel("Frequency") else:
In AreaPlot._plot we call `ax.fill_between`, which means `ax` must be an `Axes` object (and in particular, not an `Axis` object). This chases down all the other places we can infer `Axes` from that. Then some edits in an `__init__` to get mypy passing, and revert annotations of `_plot` in a few places because mypy complained about signature mismatch.
https://api.github.com/repos/pandas-dev/pandas/pulls/36016
2020-08-31T22:23:53Z
2020-09-01T17:28:03Z
2020-09-01T17:28:03Z
2020-09-01T17:41:26Z
BUG: PeriodIndex.get_loc incorrectly raising ValueError instead of KeyError
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 1617bf66c4f04..e7f9e8011bef6 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -217,7 +217,7 @@ Interval Indexing ^^^^^^^^ - +- Bug in :meth:`PeriodIndex.get_loc` incorrectly raising ``ValueError`` on non-datelike strings instead of ``KeyError``, causing similar errors in :meth:`Series.__geitem__`, :meth:`Series.__contains__`, and :meth:`Series.loc.__getitem__` (:issue:`34240`) - - diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 18970ea0544e4..3017521c6a065 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -755,9 +755,9 @@ def is_in_obj(gpr) -> bool: return False try: return gpr is obj[gpr.name] - except (KeyError, IndexError, ValueError): - # TODO: ValueError: Given date string not likely a datetime. - # should be KeyError? + except (KeyError, IndexError): + # IndexError reached in e.g. test_skip_group_keys when we pass + # lambda here return False for i, (gpr, level) in enumerate(zip(keys, levels)): diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 11334803d4583..cdb502199c6f1 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -504,7 +504,7 @@ def get_loc(self, key, method=None, tolerance=None): try: asdt, reso = parse_time_string(key, self.freq) - except DateParseError as err: + except (ValueError, DateParseError) as err: # A string with invalid format raise KeyError(f"Cannot interpret '{key}' as period") from err diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index b61d1d903f89a..d2499b85ad181 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -359,6 +359,22 @@ def test_get_loc2(self): ], ) + def test_get_loc_invalid_string_raises_keyerror(self): + # GH#34240 + pi = pd.period_range("2000", periods=3, name="A") + with pytest.raises(KeyError, match="A"): + pi.get_loc("A") + + ser = pd.Series([1, 2, 3], index=pi) + with pytest.raises(KeyError, match="A"): + ser.loc["A"] + + with pytest.raises(KeyError, match="A"): + ser["A"] + + assert "A" not in ser + assert "A" not in pi + class TestGetIndexer: def test_get_indexer(self):
- [x] closes #34240 - [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/36015
2020-08-31T21:51:19Z
2020-09-01T23:32:01Z
2020-09-01T23:32:00Z
2020-09-02T01:02:52Z
Backport PR #36011 on branch 1.1.x (CI: suppress another setuptools warning)
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py index 04e841c05e44a..fe5fc3e21d960 100644 --- a/pandas/tests/util/test_show_versions.py +++ b/pandas/tests/util/test_show_versions.py @@ -25,6 +25,7 @@ # https://github.com/pandas-dev/pandas/issues/35252 "ignore:Distutils:UserWarning" ) +@pytest.mark.filterwarnings("ignore:Setuptools is replacing distutils:UserWarning") def test_show_versions(capsys): # gh-32041 pd.show_versions()
Backport PR #36011: CI: suppress another setuptools warning
https://api.github.com/repos/pandas-dev/pandas/pulls/36013
2020-08-31T16:28:59Z
2020-09-01T14:14:38Z
2020-09-01T14:14:38Z
2020-09-01T14:14:38Z
CI: Unpin MyPy
diff --git a/environment.yml b/environment.yml index 96f2c8d2086c7..4622aac1dc6f8 100644 --- a/environment.yml +++ b/environment.yml @@ -21,7 +21,7 @@ dependencies: - flake8-comprehensions>=3.1.0 # used by flake8, linting of unnecessary comprehensions - flake8-rst>=0.6.0,<=0.7.0 # linting of code blocks in rst files - isort>=5.2.1 # check that imports are in the right order - - mypy=0.730 + - mypy=0.782 - pycodestyle # used by flake8 # documentation diff --git a/pandas/_config/config.py b/pandas/_config/config.py index fb41b37980b2e..0b802f2cc9e69 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -460,9 +460,7 @@ def register_option( path = key.split(".") for k in path: - # NOTE: tokenize.Name is not a public constant - # error: Module has no attribute "Name" [attr-defined] - if not re.match("^" + tokenize.Name + "$", k): # type: ignore[attr-defined] + if not re.match("^" + tokenize.Name + "$", k): raise ValueError(f"{k} is not a valid identifier") if keyword.iskeyword(k): raise ValueError(f"{k} is a python keyword") diff --git a/pandas/core/common.py b/pandas/core/common.py index e7260a9923ee0..6fd4700ab7f3f 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -9,7 +9,7 @@ from datetime import datetime, timedelta from functools import partial import inspect -from typing import Any, Collection, Iterable, Iterator, List, Union +from typing import Any, Collection, Iterable, Iterator, List, Union, cast import warnings import numpy as np @@ -277,6 +277,11 @@ def maybe_iterable_to_list(obj: Union[Iterable[T], T]) -> Union[Collection[T], T """ if isinstance(obj, abc.Iterable) and not isinstance(obj, abc.Sized): return list(obj) + # error: Incompatible return value type (got + # "Union[pandas.core.common.<subclass of "Iterable" and "Sized">, + # pandas.core.common.<subclass of "Iterable" and "Sized">1, T]", expected + # "Union[Collection[T], T]") [return-value] + obj = cast(Collection, obj) return obj diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 125ecb0d88036..df71b4fe415f8 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -364,7 +364,7 @@ class BaseExprVisitor(ast.NodeVisitor): unary_ops = _unary_ops_syms unary_op_nodes = "UAdd", "USub", "Invert", "Not" - unary_op_nodes_map = dict(zip(unary_ops, unary_op_nodes)) + unary_op_nodes_map = {k: v for k, v in zip(unary_ops, unary_op_nodes)} rewrite_map = { ast.Eq: ast.In, diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index 909643d50e9d7..8c4437f2cdeb9 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -103,5 +103,7 @@ def __str__(self) -> str: def __repr__(self) -> str: return f"{type(self).__name__}({str(self)})" - __setitem__ = __setslice__ = __delitem__ = __delslice__ = _disabled - pop = append = extend = remove = sort = insert = _disabled + __setitem__ = __setslice__ = _disabled # type: ignore[assignment] + __delitem__ = __delslice__ = _disabled # type: ignore[assignment] + pop = append = extend = _disabled # type: ignore[assignment] + remove = sort = insert = _disabled # type: ignore[assignment] diff --git a/pandas/core/resample.py b/pandas/core/resample.py index fc54128ae5aa6..7b5154756e613 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -966,8 +966,7 @@ def __init__(self, obj, *args, **kwargs): for attr in self._attributes: setattr(self, attr, kwargs.get(attr, getattr(parent, attr))) - # error: Too many arguments for "__init__" of "object" - super().__init__(None) # type: ignore[call-arg] + super().__init__(None) self._groupby = groupby self._groupby.mutated = True self._groupby.grouper.mutated = True diff --git a/requirements-dev.txt b/requirements-dev.txt index 1fca25c9fecd9..cc3775de3a4ba 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -12,7 +12,7 @@ flake8<3.8.0 flake8-comprehensions>=3.1.0 flake8-rst>=0.6.0,<=0.7.0 isort>=5.2.1 -mypy==0.730 +mypy==0.782 pycodestyle gitpython gitdb diff --git a/setup.cfg b/setup.cfg index c10624d60aaff..2114909256a7a 100644 --- a/setup.cfg +++ b/setup.cfg @@ -127,10 +127,7 @@ show_error_codes = True [mypy-pandas.tests.*] check_untyped_defs=False -[mypy-pandas.conftest] -ignore_errors=True - -[mypy-pandas.tests.tools.test_to_datetime] +[mypy-pandas.conftest,pandas.tests.window.conftest] ignore_errors=True [mypy-pandas._testing] @@ -139,7 +136,22 @@ check_untyped_defs=False [mypy-pandas._version] check_untyped_defs=False -[mypy-pandas.core.arrays.interval] +[mypy-pandas.compat.pickle_compat] +check_untyped_defs=False + +[mypy-pandas.core.apply] +check_untyped_defs=False + +[mypy-pandas.core.arrays.base] +check_untyped_defs=False + +[mypy-pandas.core.arrays.datetimelike] +check_untyped_defs=False + +[mypy-pandas.core.arrays.sparse.array] +check_untyped_defs=False + +[mypy-pandas.core.arrays.string_] check_untyped_defs=False [mypy-pandas.core.base] @@ -151,6 +163,9 @@ check_untyped_defs=False [mypy-pandas.core.computation.expressions] check_untyped_defs=False +[mypy-pandas.core.computation.ops] +check_untyped_defs=False + [mypy-pandas.core.computation.pytables] check_untyped_defs=False @@ -163,6 +178,9 @@ check_untyped_defs=False [mypy-pandas.core.generic] check_untyped_defs=False +[mypy-pandas.core.groupby.base] +check_untyped_defs=False + [mypy-pandas.core.groupby.generic] check_untyped_defs=False @@ -172,15 +190,33 @@ check_untyped_defs=False [mypy-pandas.core.groupby.ops] check_untyped_defs=False +[mypy-pandas.core.indexes.base] +check_untyped_defs=False + +[mypy-pandas.core.indexes.category] +check_untyped_defs=False + +[mypy-pandas.core.indexes.datetimelike] +check_untyped_defs=False + [mypy-pandas.core.indexes.datetimes] check_untyped_defs=False +[mypy-pandas.core.indexes.extension] +check_untyped_defs=False + [mypy-pandas.core.indexes.interval] check_untyped_defs=False [mypy-pandas.core.indexes.multi] check_untyped_defs=False +[mypy-pandas.core.indexes.period] +check_untyped_defs=False + +[mypy-pandas.core.indexes.range] +check_untyped_defs=False + [mypy-pandas.core.internals.blocks] check_untyped_defs=False @@ -190,15 +226,27 @@ check_untyped_defs=False [mypy-pandas.core.internals.managers] check_untyped_defs=False +[mypy-pandas.core.internals.ops] +check_untyped_defs=False + [mypy-pandas.core.missing] check_untyped_defs=False [mypy-pandas.core.ops.docstrings] check_untyped_defs=False +[mypy-pandas.core.resample] +check_untyped_defs=False + +[mypy-pandas.core.reshape.concat] +check_untyped_defs=False + [mypy-pandas.core.reshape.merge] check_untyped_defs=False +[mypy-pandas.core.series] +check_untyped_defs=False + [mypy-pandas.core.strings] check_untyped_defs=False @@ -214,6 +262,9 @@ check_untyped_defs=False [mypy-pandas.io.clipboard] check_untyped_defs=False +[mypy-pandas.io.common] +check_untyped_defs=False + [mypy-pandas.io.excel._base] check_untyped_defs=False @@ -232,6 +283,9 @@ check_untyped_defs=False [mypy-pandas.io.formats.css] check_untyped_defs=False +[mypy-pandas.io.formats.csvs] +check_untyped_defs=False + [mypy-pandas.io.formats.excel] check_untyped_defs=False @@ -270,3 +324,10 @@ check_untyped_defs=False [mypy-pandas.plotting._matplotlib.misc] check_untyped_defs=False + +[mypy-pandas.plotting._misc] +check_untyped_defs=False + +[mypy-pandas.util._decorators] +check_untyped_defs=False +
https://api.github.com/repos/pandas-dev/pandas/pulls/36012
2020-08-31T15:29:23Z
2020-09-01T23:34:16Z
2020-09-01T23:34:16Z
2020-09-02T09:21:03Z
CI: suppress another setuptools warning
diff --git a/pandas/tests/util/test_show_versions.py b/pandas/tests/util/test_show_versions.py index 04e841c05e44a..fe5fc3e21d960 100644 --- a/pandas/tests/util/test_show_versions.py +++ b/pandas/tests/util/test_show_versions.py @@ -25,6 +25,7 @@ # https://github.com/pandas-dev/pandas/issues/35252 "ignore:Distutils:UserWarning" ) +@pytest.mark.filterwarnings("ignore:Setuptools is replacing distutils:UserWarning") def test_show_versions(capsys): # gh-32041 pd.show_versions()
Seeing this on some new PRs. xref #35252
https://api.github.com/repos/pandas-dev/pandas/pulls/36011
2020-08-31T14:53:54Z
2020-08-31T16:27:28Z
2020-08-31T16:27:28Z
2020-08-31T16:57:40Z
POC: ArrayManager -- array-based data manager for columnar store
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e8834bd509bf0..516d37a483ce4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,3 +132,22 @@ jobs: - name: Upload dev docs run: rsync -az --delete doc/build/html/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas/pandas-docs/dev if: github.event_name == 'push' + + data_manager: + name: Test experimental data manager + runs-on: ubuntu-latest + steps: + + - name: Setting conda path + run: echo "${HOME}/miniconda3/bin" >> $GITHUB_PATH + + - name: Checkout + uses: actions/checkout@v1 + + - name: Setup environment and build pandas + run: ci/setup_env.sh + + - name: Run tests + run: | + source activate pandas-dev + pytest pandas/tests/frame/methods --array-manager diff --git a/pandas/_typing.py b/pandas/_typing.py index 91cb01dac76fb..9b957ab4d0686 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -39,6 +39,7 @@ from pandas.core.generic import NDFrame # noqa: F401 from pandas.core.groupby.generic import DataFrameGroupBy, SeriesGroupBy from pandas.core.indexes.base import Index + from pandas.core.internals import ArrayManager, BlockManager from pandas.core.resample import Resampler from pandas.core.series import Series from pandas.core.window.rolling import BaseWindow @@ -159,3 +160,6 @@ ColspaceArgType = Union[ str, int, Sequence[Union[str, int]], Mapping[Hashable, Union[str, int]] ] + +# internals +Manager = Union["ArrayManager", "BlockManager"] diff --git a/pandas/conftest.py b/pandas/conftest.py index e30a55cef3166..45d545a522fc7 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -75,6 +75,19 @@ def pytest_addoption(parser): action="store_true", help="Fail if a test is skipped for missing data file.", ) + parser.addoption( + "--array-manager", + "--am", + action="store_true", + help="Use the experimental ArrayManager as default data manager.", + ) + + +def pytest_sessionstart(session): + # Note: we need to set the option here and not in pytest_runtest_setup below + # to ensure this is run before creating fixture data + if session.config.getoption("--array-manager"): + pd.options.mode.data_manager = "array" def pytest_runtest_setup(item): @@ -1454,3 +1467,11 @@ def indexer_si(request): Parametrize over __setitem__, iloc.__setitem__ """ return request.param + + +@pytest.fixture +def using_array_manager(request): + """ + Fixture to check if the array manager is being used. + """ + return pd.options.mode.data_manager == "array" diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index fba82ae499e90..56ef1ea28ed1b 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -483,6 +483,12 @@ def use_inf_as_na_cb(key): cf.register_option( "use_inf_as_null", False, use_inf_as_null_doc, cb=use_inf_as_na_cb ) + cf.register_option( + "data_manager", + "block", + "Internal data manager type", + validator=is_one_of_factory(["block", "array"]), + ) cf.deprecate_option( "mode.use_inf_as_null", msg=use_inf_as_null_doc, rkey="mode.use_inf_as_na" diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 344e5d6667074..36ccd0b8a2f7d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -62,6 +62,7 @@ IndexKeyFunc, IndexLabel, Level, + Manager, PythonFuncType, Renamer, StorageOptions, @@ -137,13 +138,14 @@ ) from pandas.core.indexes.multi import MultiIndex, maybe_droplevels from pandas.core.indexing import check_bool_indexer, convert_to_index_sliceable -from pandas.core.internals import BlockManager +from pandas.core.internals import ArrayManager, BlockManager from pandas.core.internals.construction import ( arrays_to_mgr, dataclasses_to_dicts, init_dict, init_ndarray, masked_rec_array_to_mgr, + mgr_to_mgr, nested_data_to_arrays, reorder_arrays, sanitize_index, @@ -523,7 +525,7 @@ def __init__( if isinstance(data, DataFrame): data = data._mgr - if isinstance(data, BlockManager): + if isinstance(data, (BlockManager, ArrayManager)): if index is None and columns is None and dtype is None and copy is False: # GH#33357 fastpath NDFrame.__init__(self, data) @@ -601,8 +603,31 @@ def __init__( values, index, columns, dtype=values.dtype, copy=False ) + # ensure correct Manager type according to settings + manager = get_option("mode.data_manager") + mgr = mgr_to_mgr(mgr, typ=manager) + NDFrame.__init__(self, mgr) + def _as_manager(self, typ: str) -> DataFrame: + """ + Private helper function to create a DataFrame with specific manager. + + Parameters + ---------- + typ : {"block", "array"} + + Returns + ------- + DataFrame + New DataFrame using specified manager type. Is not guaranteed + to be a copy or not. + """ + new_mgr: Manager + new_mgr = mgr_to_mgr(self._mgr, typ=typ) + # fastpath of passing a manager doesn't check the option/manager class + return DataFrame(new_mgr) + # ---------------------------------------------------------------------- @property @@ -675,6 +700,8 @@ def _is_homogeneous_type(self) -> bool: ... "B": np.array([1, 2], dtype=np.int64)})._is_homogeneous_type False """ + if isinstance(self._mgr, ArrayManager): + return len({arr.dtype for arr in self._mgr.arrays}) == 1 if self._mgr.any_extension_types: return len({block.dtype for block in self._mgr.blocks}) == 1 else: @@ -685,6 +712,8 @@ def _can_fast_transpose(self) -> bool: """ Can we transpose this DataFrame without creating any new array objects. """ + if isinstance(self._mgr, ArrayManager): + return False if self._mgr.any_extension_types: # TODO(EA2D) special case would be unnecessary with 2D EAs return False @@ -5506,7 +5535,7 @@ def sort_values( # type: ignore[override] ) if ignore_index: - new_data.axes[1] = ibase.default_index(len(indexer)) + new_data.set_axis(1, ibase.default_index(len(indexer))) result = self._constructor(new_data) if inplace: @@ -6051,7 +6080,10 @@ def _dispatch_frame_op(self, right, func, axis: Optional[int] = None): # fails in cases with empty columns reached via # _frame_arith_method_with_reindex - bm = self._mgr.operate_blockwise(right._mgr, array_op) + # TODO operate_blockwise expects a manager of the same type + bm = self._mgr.operate_blockwise( + right._mgr, array_op # type: ignore[arg-type] + ) return type(self)(bm) elif isinstance(right, Series) and axis == 1: @@ -8894,11 +8926,11 @@ def func(values: np.ndarray): # We only use this in the case that operates on self.values return op(values, axis=axis, skipna=skipna, **kwds) - def blk_func(values): + def blk_func(values, axis=1): if isinstance(values, ExtensionArray): return values._reduce(name, skipna=skipna, **kwds) else: - return op(values, axis=1, skipna=skipna, **kwds) + return op(values, axis=axis, skipna=skipna, **kwds) def _get_data() -> DataFrame: if filter_type is None: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0daeed0e393e6..9e3f6f8e36175 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -45,6 +45,7 @@ IndexLabel, JSONSerializable, Level, + Manager, NpDtype, Renamer, StorageOptions, @@ -102,7 +103,7 @@ RangeIndex, ensure_index, ) -from pandas.core.internals import BlockManager +from pandas.core.internals import ArrayManager, BlockManager from pandas.core.missing import find_valid_index from pandas.core.ops import align_method_FRAME from pandas.core.shared_docs import _shared_docs @@ -179,7 +180,7 @@ class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): ) _metadata: List[str] = [] _is_copy = None - _mgr: BlockManager + _mgr: Manager _attrs: Dict[Optional[Hashable], Any] _typ: str @@ -188,7 +189,7 @@ class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): def __init__( self, - data: BlockManager, + data: Manager, copy: bool = False, attrs: Optional[Mapping[Optional[Hashable], Any]] = None, ): @@ -207,7 +208,7 @@ def __init__( @classmethod def _init_mgr( cls, mgr, axes, dtype: Optional[Dtype] = None, copy: bool = False - ) -> BlockManager: + ) -> Manager: """ passed a manager and a axes dict """ for a, axe in axes.items(): if axe is not None: @@ -220,7 +221,13 @@ def _init_mgr( mgr = mgr.copy() if dtype is not None: # avoid further copies if we can - if len(mgr.blocks) > 1 or mgr.blocks[0].values.dtype != dtype: + if ( + isinstance(mgr, BlockManager) + and len(mgr.blocks) == 1 + and mgr.blocks[0].values.dtype == dtype + ): + pass + else: mgr = mgr.astype(dtype=dtype) return mgr @@ -4544,11 +4551,11 @@ def sort_index( new_data = self._mgr.take(indexer, axis=baxis, verify=False) # reconstruct axis if needed - new_data.axes[baxis] = new_data.axes[baxis]._sort_levels_monotonic() + new_data.set_axis(baxis, new_data.axes[baxis]._sort_levels_monotonic()) if ignore_index: axis = 1 if isinstance(self, ABCDataFrame) else 0 - new_data.axes[axis] = ibase.default_index(len(indexer)) + new_data.set_axis(axis, ibase.default_index(len(indexer))) result = self._constructor(new_data) @@ -5521,6 +5528,8 @@ def _protect_consolidate(self, f): Consolidate _mgr -- if the blocks have changed, then clear the cache """ + if isinstance(self._mgr, ArrayManager): + return f() blocks_before = len(self._mgr.blocks) result = f() if len(self._mgr.blocks) != blocks_before: @@ -5710,11 +5719,13 @@ def _to_dict_of_blocks(self, copy: bool_t = True): Return a dict of dtype -> Constructor Types that each is a homogeneous dtype. - Internal ONLY + Internal ONLY - only works for BlockManager """ + mgr = self._mgr + mgr = cast(BlockManager, mgr) return { k: self._constructor(v).__finalize__(self) - for k, v, in self._mgr.to_dict(copy=copy).items() + for k, v, in mgr.to_dict(copy=copy).items() } def astype( diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 174a2f4052b06..c561204c1c125 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1086,10 +1086,12 @@ def py_fallback(bvalues: ArrayLike) -> ArrayLike: # in the operation. We un-split here. result = result._consolidate() assert isinstance(result, (Series, DataFrame)) # for mypy - assert len(result._mgr.blocks) == 1 + mgr = result._mgr + assert isinstance(mgr, BlockManager) + assert len(mgr.blocks) == 1 # unwrap DataFrame to get array - result = result._mgr.blocks[0].values + result = mgr.blocks[0].values return result def blk_func(bvalues: ArrayLike) -> ArrayLike: diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index fbccac1c2af67..e71143224556b 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -1,3 +1,5 @@ +from pandas.core.internals.array_manager import ArrayManager +from pandas.core.internals.base import DataManager from pandas.core.internals.blocks import ( # io.pytables, io.packers Block, BoolBlock, @@ -35,6 +37,8 @@ "TimeDeltaBlock", "safe_reshape", "make_block", + "DataManager", + "ArrayManager", "BlockManager", "SingleBlockManager", "concatenate_block_managers", diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py new file mode 100644 index 0000000000000..134bf59ed7f9c --- /dev/null +++ b/pandas/core/internals/array_manager.py @@ -0,0 +1,892 @@ +""" +Experimental manager based on storing a collection of 1D arrays +""" +from typing import TYPE_CHECKING, Any, Callable, List, Optional, Tuple, TypeVar, Union + +import numpy as np + +from pandas._libs import algos as libalgos, lib +from pandas._typing import ArrayLike, DtypeObj, Hashable +from pandas.util._validators import validate_bool_kwarg + +from pandas.core.dtypes.cast import find_common_type, infer_dtype_from_scalar +from pandas.core.dtypes.common import ( + is_bool_dtype, + is_dtype_equal, + is_extension_array_dtype, + is_numeric_dtype, +) +from pandas.core.dtypes.dtypes import ExtensionDtype +from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries +from pandas.core.dtypes.missing import isna + +import pandas.core.algorithms as algos +from pandas.core.arrays import ExtensionArray, PandasDtype +from pandas.core.arrays.sparse import SparseDtype +from pandas.core.construction import extract_array +from pandas.core.indexers import maybe_convert_indices +from pandas.core.indexes.api import Index, ensure_index +from pandas.core.internals.base import DataManager +from pandas.core.internals.blocks import make_block + +if TYPE_CHECKING: + from pandas.core.internals.managers import SingleBlockManager + + +T = TypeVar("T", bound="ArrayManager") + + +class ArrayManager(DataManager): + """ + Core internal data structure to implement DataFrame and Series. + + Alternative to the BlockManager, storing a list of 1D arrays instead of + Blocks. + + This is *not* a public API class + + Parameters + ---------- + arrays : Sequence of arrays + axes : Sequence of Index + do_integrity_check : bool, default True + + """ + + __slots__ = [ + "_axes", # private attribute, because 'axes' has different order, see below + "arrays", + ] + + arrays: List[Union[np.ndarray, ExtensionArray]] + _axes: List[Index] + + def __init__( + self, + arrays: List[Union[np.ndarray, ExtensionArray]], + axes: List[Index], + do_integrity_check: bool = True, + ): + # Note: we are storing the axes in "_axes" in the (row, columns) order + # which contrasts the order how it is stored in BlockManager + self._axes = axes + self.arrays = arrays + + if do_integrity_check: + self._axes = [ensure_index(ax) for ax in axes] + self._verify_integrity() + + def make_empty(self: T, axes=None) -> T: + """Return an empty ArrayManager with the items axis of len 0 (no columns)""" + if axes is None: + axes = [self.axes[1:], Index([])] + + arrays: List[Union[np.ndarray, ExtensionArray]] = [] + return type(self)(arrays, axes) + + @property + def items(self) -> Index: + return self._axes[1] + + @property + def axes(self) -> List[Index]: # type: ignore[override] + # mypy doesn't work to override attribute with property + # see https://github.com/python/mypy/issues/4125 + """Axes is BlockManager-compatible order (columns, rows)""" + return [self._axes[1], self._axes[0]] + + @property + def shape(self) -> Tuple[int, ...]: + # this still gives the BlockManager-compatible transposed shape + return tuple(len(ax) for ax in self.axes) + + @property + def shape_proper(self) -> Tuple[int, ...]: + # this returns (n_rows, n_columns) + return tuple(len(ax) for ax in self._axes) + + @staticmethod + def _normalize_axis(axis): + # switch axis + axis = 1 if axis == 0 else 0 + return axis + + # TODO can be shared + def set_axis(self, axis: int, new_labels: Index) -> None: + # Caller is responsible for ensuring we have an Index object. + axis = self._normalize_axis(axis) + old_len = len(self._axes[axis]) + new_len = len(new_labels) + + if new_len != old_len: + raise ValueError( + f"Length mismatch: Expected axis has {old_len} elements, new " + f"values have {new_len} elements" + ) + + self._axes[axis] = new_labels + + def consolidate(self) -> "ArrayManager": + return self + + def is_consolidated(self) -> bool: + return True + + def _consolidate_inplace(self) -> None: + pass + + def get_dtypes(self): + return np.array([arr.dtype for arr in self.arrays], dtype="object") + + # TODO setstate getstate + + def __repr__(self) -> str: + output = type(self).__name__ + output += f"\nIndex: {self._axes[0]}" + output += f"\nColumns: {self._axes[1]}" + output += f"\n{len(self.arrays)} arrays:" + for arr in self.arrays: + output += f"\n{arr.dtype}" + return output + + def _verify_integrity(self) -> None: + n_rows, n_columns = self.shape_proper + if not len(self.arrays) == n_columns: + raise ValueError( + "Number of passed arrays must equal the size of the column Index: " + f"{len(self.arrays)} arrays vs {n_columns} columns." + ) + for arr in self.arrays: + if not len(arr) == n_rows: + raise ValueError( + "Passed arrays should have the same length as the rows Index: " + f"{len(arr)} vs {n_rows} rows" + ) + if not isinstance(arr, (np.ndarray, ExtensionArray)): + raise ValueError( + "Passed arrays should be np.ndarray or ExtensionArray instances, " + f"got {type(arr)} instead" + ) + + def reduce( + self: T, func: Callable, ignore_failures: bool = False + ) -> Tuple[T, np.ndarray]: + # TODO this still fails because `func` assumes to work on 2D arrays + # TODO implement ignore_failures + assert self.ndim == 2 + + res_arrays = [] + for arr in self.arrays: + res = func(arr, axis=0) + res_arrays.append(np.array([res])) + + index = Index([None]) # placeholder + new_mgr = type(self)(res_arrays, [index, self.items]) + indexer = np.arange(self.shape[0]) + return new_mgr, indexer + + def operate_blockwise(self, other: "ArrayManager", array_op) -> "ArrayManager": + """ + Apply array_op blockwise with another (aligned) BlockManager. + """ + # TODO what if `other` is BlockManager ? + left_arrays = self.arrays + right_arrays = other.arrays + result_arrays = [ + array_op(left, right) for left, right in zip(left_arrays, right_arrays) + ] + return type(self)(result_arrays, self._axes) + + def apply( + self: T, + f, + align_keys: Optional[List[str]] = None, + ignore_failures: bool = False, + **kwargs, + ) -> T: + """ + Iterate over the arrays, collect and create a new ArrayManager. + + Parameters + ---------- + f : str or callable + Name of the Array method to apply. + align_keys: List[str] or None, default None + ignore_failures: bool, default False + **kwargs + Keywords to pass to `f` + + Returns + ------- + ArrayManager + """ + assert "filter" not in kwargs + + align_keys = align_keys or [] + result_arrays: List[np.ndarray] = [] + result_indices: List[int] = [] + # fillna: Series/DataFrame is responsible for making sure value is aligned + + aligned_args = {k: kwargs[k] for k in align_keys} + + if f == "apply": + f = kwargs.pop("func") + + for i, arr in enumerate(self.arrays): + + if aligned_args: + + for k, obj in aligned_args.items(): + if isinstance(obj, (ABCSeries, ABCDataFrame)): + # The caller is responsible for ensuring that + # obj.axes[-1].equals(self.items) + if obj.ndim == 1: + kwargs[k] = obj.iloc[i] + else: + kwargs[k] = obj.iloc[:, i]._values + else: + # otherwise we have an array-like + kwargs[k] = obj[i] + + try: + if callable(f): + applied = f(arr, **kwargs) + else: + applied = getattr(arr, f)(**kwargs) + except (TypeError, NotImplementedError): + if not ignore_failures: + raise + continue + # if not isinstance(applied, ExtensionArray): + # # TODO not all EA operations return new EAs (eg astype) + # applied = array(applied) + result_arrays.append(applied) + result_indices.append(i) + + new_axes: List[Index] + if ignore_failures: + # TODO copy? + new_axes = [self._axes[0], self._axes[1][result_indices]] + else: + new_axes = self._axes + + if len(result_arrays) == 0: + return self.make_empty(new_axes) + + return type(self)(result_arrays, new_axes) + + def apply_with_block(self: T, f, align_keys=None, **kwargs) -> T: + + align_keys = align_keys or [] + aligned_args = {k: kwargs[k] for k in align_keys} + + result_arrays = [] + + for i, arr in enumerate(self.arrays): + + if aligned_args: + for k, obj in aligned_args.items(): + if isinstance(obj, (ABCSeries, ABCDataFrame)): + # The caller is responsible for ensuring that + # obj.axes[-1].equals(self.items) + if obj.ndim == 1: + kwargs[k] = obj.iloc[[i]] + else: + kwargs[k] = obj.iloc[:, [i]]._values + else: + # otherwise we have an ndarray + kwargs[k] = obj[[i]] + + if hasattr(arr, "tz") and arr.tz is None: # type: ignore[union-attr] + # DatetimeArray needs to be converted to ndarray for DatetimeBlock + arr = arr._data # type: ignore[union-attr] + elif arr.dtype.kind == "m": + # TimedeltaArray needs to be converted to ndarray for TimedeltaBlock + arr = arr._data # type: ignore[union-attr] + if isinstance(arr, np.ndarray): + arr = np.atleast_2d(arr) + block = make_block(arr, placement=slice(0, 1, 1), ndim=2) + applied = getattr(block, f)(**kwargs) + if isinstance(applied, list): + applied = applied[0] + arr = applied.values + if isinstance(arr, np.ndarray): + arr = arr[0, :] + result_arrays.append(arr) + + return type(self)(result_arrays, self._axes) + + # TODO quantile + + def isna(self, func) -> "ArrayManager": + return self.apply("apply", func=func) + + def where(self, other, cond, align: bool, errors: str, axis: int) -> "ArrayManager": + if align: + align_keys = ["other", "cond"] + else: + align_keys = ["cond"] + other = extract_array(other, extract_numpy=True) + + return self.apply_with_block( + "where", + align_keys=align_keys, + other=other, + cond=cond, + errors=errors, + axis=axis, + ) + + # TODO what is this used for? + # def setitem(self, indexer, value) -> "ArrayManager": + # return self.apply_with_block("setitem", indexer=indexer, value=value) + + def putmask(self, mask, new, align: bool = True, axis: int = 0): + + if align: + align_keys = ["new", "mask"] + else: + align_keys = ["mask"] + new = extract_array(new, extract_numpy=True) + + return self.apply_with_block( + "putmask", + align_keys=align_keys, + mask=mask, + new=new, + axis=axis, + ) + + def diff(self, n: int, axis: int) -> "ArrayManager": + return self.apply_with_block("diff", n=n, axis=axis) + + def interpolate(self, **kwargs) -> "ArrayManager": + return self.apply_with_block("interpolate", **kwargs) + + def shift(self, periods: int, axis: int, fill_value) -> "ArrayManager": + if fill_value is lib.no_default: + fill_value = None + + if axis == 0 and self.ndim == 2: + # TODO column-wise shift + raise NotImplementedError + + return self.apply_with_block( + "shift", periods=periods, axis=axis, fill_value=fill_value + ) + + def fillna(self, value, limit, inplace: bool, downcast) -> "ArrayManager": + # TODO implement downcast + inplace = validate_bool_kwarg(inplace, "inplace") + + def array_fillna(array, value, limit, inplace): + + mask = isna(array) + if limit is not None: + limit = libalgos.validate_limit(None, limit=limit) + mask[mask.cumsum() > limit] = False + + # TODO could optimize for arrays that cannot hold NAs + # (like _can_hold_na on Blocks) + if not inplace: + array = array.copy() + + # np.putmask(array, mask, value) + if np.any(mask): + # TODO allow invalid value if there is nothing to fill? + array[mask] = value + return array + + return self.apply(array_fillna, value=value, limit=limit, inplace=inplace) + + def downcast(self) -> "ArrayManager": + return self.apply_with_block("downcast") + + def astype( + self, dtype, copy: bool = False, errors: str = "raise" + ) -> "ArrayManager": + return self.apply("astype", dtype=dtype, copy=copy) # , errors=errors) + + def convert( + self, + copy: bool = True, + datetime: bool = True, + numeric: bool = True, + timedelta: bool = True, + ) -> "ArrayManager": + return self.apply_with_block( + "convert", + copy=copy, + datetime=datetime, + numeric=numeric, + timedelta=timedelta, + ) + + def replace(self, value, **kwargs) -> "ArrayManager": + assert np.ndim(value) == 0, value + # TODO "replace" is right now implemented on the blocks, we should move + # it to general array algos so it can be reused here + return self.apply_with_block("replace", value=value, **kwargs) + + def replace_list( + self: T, + src_list: List[Any], + dest_list: List[Any], + inplace: bool = False, + regex: bool = False, + ) -> T: + """ do a list replace """ + inplace = validate_bool_kwarg(inplace, "inplace") + + return self.apply_with_block( + "_replace_list", + src_list=src_list, + dest_list=dest_list, + inplace=inplace, + regex=regex, + ) + + def to_native_types(self, **kwargs): + return self.apply_with_block("to_native_types", **kwargs) + + @property + def is_mixed_type(self) -> bool: + return True + + @property + def is_numeric_mixed_type(self) -> bool: + return False + + @property + def any_extension_types(self) -> bool: + """Whether any of the blocks in this manager are extension blocks""" + return False # any(block.is_extension for block in self.blocks) + + @property + def is_view(self) -> bool: + """ return a boolean if we are a single block and are a view """ + # TODO what is this used for? + return False + + @property + def is_single_block(self) -> bool: + return False + + def get_bool_data(self, copy: bool = False) -> "ArrayManager": + """ + Parameters + ---------- + copy : bool, default False + Whether to copy the blocks + """ + mask = np.array([is_bool_dtype(t) for t in self.get_dtypes()], dtype="object") + arrays = [self.arrays[i] for i in np.nonzero(mask)[0]] + # TODO copy? + new_axes = [self._axes[0], self._axes[1][mask]] + return type(self)(arrays, new_axes) + + def get_numeric_data(self, copy: bool = False) -> "ArrayManager": + """ + Parameters + ---------- + copy : bool, default False + Whether to copy the blocks + """ + mask = np.array([is_numeric_dtype(t) for t in self.get_dtypes()]) + arrays = [self.arrays[i] for i in np.nonzero(mask)[0]] + # TODO copy? + new_axes = [self._axes[0], self._axes[1][mask]] + return type(self)(arrays, new_axes) + + def copy(self: T, deep=True) -> T: + """ + Make deep or shallow copy of ArrayManager + + Parameters + ---------- + deep : bool or string, default True + If False, return shallow copy (do not copy data) + If 'all', copy data and a deep copy of the index + + Returns + ------- + BlockManager + """ + # this preserves the notion of view copying of axes + if deep: + # hit in e.g. tests.io.json.test_pandas + + def copy_func(ax): + return ax.copy(deep=True) if deep == "all" else ax.view() + + new_axes = [copy_func(ax) for ax in self._axes] + else: + new_axes = list(self._axes) + + if deep: + new_arrays = [arr.copy() for arr in self.arrays] + else: + new_arrays = self.arrays + return type(self)(new_arrays, new_axes) + + def as_array( + self, + transpose: bool = False, + dtype=None, + copy: bool = False, + na_value=lib.no_default, + ) -> np.ndarray: + """ + Convert the blockmanager data into an numpy array. + + Parameters + ---------- + transpose : bool, default False + If True, transpose the return array. + dtype : object, default None + Data type of the return array. + copy : bool, default False + If True then guarantee that a copy is returned. A value of + False does not guarantee that the underlying data is not + copied. + na_value : object, default lib.no_default + Value to be used as the missing value sentinel. + + Returns + ------- + arr : ndarray + """ + if len(self.arrays) == 0: + arr = np.empty(self.shape, dtype=float) + return arr.transpose() if transpose else arr + + # We want to copy when na_value is provided to avoid + # mutating the original object + copy = copy or na_value is not lib.no_default + + if not dtype: + dtype = _interleaved_dtype(self.arrays) + + if isinstance(dtype, SparseDtype): + dtype = dtype.subtype + elif isinstance(dtype, PandasDtype): + dtype = dtype.numpy_dtype + elif is_extension_array_dtype(dtype): + dtype = "object" + elif is_dtype_equal(dtype, str): + dtype = "object" + + result = np.empty(self.shape_proper, dtype=dtype) + + for i, arr in enumerate(self.arrays): + arr = arr.astype(dtype, copy=copy) + result[:, i] = arr + + if na_value is not lib.no_default: + result[isna(result)] = na_value + + return result + # return arr.transpose() if transpose else arr + + def get_slice(self, slobj: slice, axis: int = 0) -> "ArrayManager": + axis = self._normalize_axis(axis) + + if axis == 0: + arrays = [arr[slobj] for arr in self.arrays] + elif axis == 1: + arrays = self.arrays[slobj] + + new_axes = list(self._axes) + new_axes[axis] = new_axes[axis][slobj] + + return type(self)(arrays, new_axes, do_integrity_check=False) + + def fast_xs(self, loc: int) -> ArrayLike: + """ + Return the array corresponding to `frame.iloc[loc]`. + + Parameters + ---------- + loc : int + + Returns + ------- + np.ndarray or ExtensionArray + """ + dtype = _interleaved_dtype(self.arrays) + + if isinstance(dtype, SparseDtype): + temp_dtype = dtype.subtype + elif isinstance(dtype, PandasDtype): + temp_dtype = dtype.numpy_dtype + elif is_extension_array_dtype(dtype): + temp_dtype = "object" + elif is_dtype_equal(dtype, str): + temp_dtype = "object" + else: + temp_dtype = dtype + + result = np.array([arr[loc] for arr in self.arrays], dtype=temp_dtype) + if isinstance(dtype, ExtensionDtype): + result = dtype.construct_array_type()._from_sequence(result, dtype=dtype) + return result + + def iget(self, i: int) -> "SingleBlockManager": + """ + Return the data as a SingleBlockManager. + """ + from pandas.core.internals.managers import SingleBlockManager + + values = self.arrays[i] + block = make_block(values, placement=slice(0, len(values)), ndim=1) + + return SingleBlockManager(block, self._axes[0]) + + def iget_values(self, i: int) -> ArrayLike: + """ + Return the data for column i as the values (ndarray or ExtensionArray). + """ + return self.arrays[i] + + def idelete(self, indexer): + """ + Delete selected locations in-place (new block and array, same BlockManager) + """ + to_keep = np.ones(self.shape[0], dtype=np.bool_) + to_keep[indexer] = False + + self.arrays = [self.arrays[i] for i in np.nonzero(to_keep)[0]] + self._axes = [self._axes[0], self._axes[1][to_keep]] + + def iset(self, loc: Union[int, slice, np.ndarray], value): + """ + Set new item in-place. Does not consolidate. Adds new Block if not + contained in the current set of items + """ + if lib.is_integer(loc): + # TODO normalize array -> this should in theory not be needed? + value = extract_array(value, extract_numpy=True) + if isinstance(value, np.ndarray) and value.ndim == 2: + value = value[0, :] + + assert isinstance(value, (np.ndarray, ExtensionArray)) + # value = np.asarray(value) + # assert isinstance(value, np.ndarray) + assert len(value) == len(self._axes[0]) + self.arrays[loc] = value + return + + # TODO + raise Exception + + def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False): + """ + Insert item at selected position. + + Parameters + ---------- + loc : int + item : hashable + value : array_like + allow_duplicates: bool + If False, trying to insert non-unique item will raise + + """ + if not allow_duplicates and item in self.items: + # Should this be a different kind of error?? + raise ValueError(f"cannot insert {item}, already exists") + + if not isinstance(loc, int): + raise TypeError("loc must be int") + + # insert to the axis; this could possibly raise a TypeError + new_axis = self.items.insert(loc, item) + + value = extract_array(value, extract_numpy=True) + if value.ndim == 2: + value = value[0, :] + # TODO self.arrays can be empty + # assert len(value) == len(self.arrays[0]) + + # TODO is this copy needed? + arrays = self.arrays.copy() + arrays.insert(loc, value) + + self.arrays = arrays + self._axes[1] = new_axis + + def reindex_indexer( + self: T, + new_axis, + indexer, + axis: int, + fill_value=None, + allow_dups: bool = False, + copy: bool = True, + # ignored keywords + consolidate: bool = True, + only_slice: bool = False, + ) -> T: + axis = self._normalize_axis(axis) + return self._reindex_indexer( + new_axis, indexer, axis, fill_value, allow_dups, copy + ) + + def _reindex_indexer( + self: T, + new_axis, + indexer, + axis: int, + fill_value=None, + allow_dups: bool = False, + copy: bool = True, + ) -> T: + """ + Parameters + ---------- + new_axis : Index + indexer : ndarray of int64 or None + axis : int + fill_value : object, default None + allow_dups : bool, default False + copy : bool, default True + + + pandas-indexer with -1's only. + """ + if indexer is None: + if new_axis is self._axes[axis] and not copy: + return self + + result = self.copy(deep=copy) + result._axes = list(self._axes) + result._axes[axis] = new_axis + return result + + # some axes don't allow reindexing with dups + if not allow_dups: + self._axes[axis]._can_reindex(indexer) + + # if axis >= self.ndim: + # raise IndexError("Requested axis not found in manager") + + if axis == 1: + new_arrays = [] + for i in indexer: + if i == -1: + arr = self._make_na_array(fill_value=fill_value) + else: + arr = self.arrays[i] + new_arrays.append(arr) + + else: + new_arrays = [ + algos.take( + arr, + indexer, + allow_fill=True, + fill_value=fill_value, + # if fill_value is not None else blk.fill_value + ) + for arr in self.arrays + ] + + new_axes = list(self._axes) + new_axes[axis] = new_axis + + return type(self)(new_arrays, new_axes) + + def take(self, indexer, axis: int = 1, verify: bool = True, convert: bool = True): + """ + Take items along any axis. + """ + axis = self._normalize_axis(axis) + + indexer = ( + np.arange(indexer.start, indexer.stop, indexer.step, dtype="int64") + if isinstance(indexer, slice) + else np.asanyarray(indexer, dtype="int64") + ) + + n = self.shape_proper[axis] + if convert: + indexer = maybe_convert_indices(indexer, n) + + if verify: + if ((indexer == -1) | (indexer >= n)).any(): + raise Exception("Indices must be nonzero and less than the axis length") + + new_labels = self._axes[axis].take(indexer) + return self._reindex_indexer( + new_axis=new_labels, indexer=indexer, axis=axis, allow_dups=True + ) + + def _make_na_array(self, fill_value=None): + if fill_value is None: + fill_value = np.nan + + dtype, fill_value = infer_dtype_from_scalar(fill_value) + values = np.empty(self.shape_proper[0], dtype=dtype) + values.fill(fill_value) + return values + + def equals(self, other: object) -> bool: + # TODO + raise NotImplementedError + + def unstack(self, unstacker, fill_value) -> "ArrayManager": + """ + Return a BlockManager with all blocks unstacked.. + + Parameters + ---------- + unstacker : reshape._Unstacker + fill_value : Any + fill_value for newly introduced missing values. + + Returns + ------- + unstacked : BlockManager + """ + indexer, _ = unstacker._indexer_and_to_sort + new_indexer = np.full(unstacker.mask.shape, -1) + new_indexer[unstacker.mask] = indexer + new_indexer2D = new_indexer.reshape(*unstacker.full_shape) + + new_arrays = [] + for arr in self.arrays: + for i in range(unstacker.full_shape[1]): + new_arr = algos.take( + arr, new_indexer2D[:, i], allow_fill=True, fill_value=fill_value + ) + new_arrays.append(new_arr) + + new_index = unstacker.new_index + new_columns = unstacker.get_new_columns(self._axes[1]) + new_axes = [new_index, new_columns] + + return type(self)(new_arrays, new_axes, do_integrity_check=False) + + # TODO + # equals + # to_dict + # quantile + + +def _interleaved_dtype(blocks) -> Optional[DtypeObj]: + """ + Find the common dtype for `blocks`. + + Parameters + ---------- + blocks : List[Block] + + Returns + ------- + dtype : np.dtype, ExtensionDtype, or None + None is returned when `blocks` is empty. + """ + if not len(blocks): + return None + + return find_common_type([b.dtype for b in blocks]) diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py new file mode 100644 index 0000000000000..2295e3f2c41b2 --- /dev/null +++ b/pandas/core/internals/base.py @@ -0,0 +1,72 @@ +""" +Base class for the internal managers. Both BlockManager and ArrayManager +inherit from this class. +""" +from typing import List, TypeVar + +from pandas.errors import AbstractMethodError + +from pandas.core.base import PandasObject +from pandas.core.indexes.api import Index, ensure_index + +T = TypeVar("T", bound="DataManager") + + +class DataManager(PandasObject): + + # TODO share more methods/attributes + + axes: List[Index] + + @property + def items(self) -> Index: + raise AbstractMethodError(self) + + def __len__(self) -> int: + return len(self.items) + + @property + def ndim(self) -> int: + return len(self.axes) + + def reindex_indexer( + self: T, + new_axis, + indexer, + axis: int, + fill_value=None, + allow_dups: bool = False, + copy: bool = True, + consolidate: bool = True, + only_slice: bool = False, + ) -> T: + raise AbstractMethodError(self) + + def reindex_axis( + self, + new_index, + axis: int, + method=None, + limit=None, + fill_value=None, + copy: bool = True, + consolidate: bool = True, + only_slice: bool = False, + ): + """ + Conform data manager to new index. + """ + new_index = ensure_index(new_index) + new_index, indexer = self.axes[axis].reindex( + new_index, method=method, limit=limit + ) + + return self.reindex_indexer( + new_index, + indexer, + axis=axis, + fill_value=fill_value, + copy=copy, + consolidate=consolidate, + only_slice=only_slice, + ) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index f97077954f8bf..32b6f9d64dd8d 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -1,11 +1,12 @@ from collections import defaultdict import copy +import itertools from typing import TYPE_CHECKING, Any, Dict, List, Sequence, Tuple, cast import numpy as np from pandas._libs import NaT, internals as libinternals -from pandas._typing import ArrayLike, DtypeObj, Shape +from pandas._typing import ArrayLike, DtypeObj, Manager, Shape from pandas.util._decorators import cache_readonly from pandas.core.dtypes.cast import maybe_promote @@ -25,6 +26,7 @@ import pandas.core.algorithms as algos from pandas.core.arrays import DatetimeArray, ExtensionArray +from pandas.core.internals.array_manager import ArrayManager from pandas.core.internals.blocks import make_block from pandas.core.internals.managers import BlockManager @@ -35,7 +37,7 @@ def concatenate_block_managers( mgrs_indexers, axes: List["Index"], concat_axis: int, copy: bool -) -> BlockManager: +) -> Manager: """ Concatenate block managers into one. @@ -50,6 +52,21 @@ def concatenate_block_managers( ------- BlockManager """ + if isinstance(mgrs_indexers[0][0], ArrayManager): + + if concat_axis == 1: + # TODO for now only fastpath without indexers + mgrs = [t[0] for t in mgrs_indexers] + arrays = [ + concat_compat([mgrs[i].arrays[j] for i in range(len(mgrs))], axis=0) + for j in range(len(mgrs[0].arrays)) + ] + return ArrayManager(arrays, [axes[1], axes[0]]) + elif concat_axis == 0: + mgrs = [t[0] for t in mgrs_indexers] + arrays = list(itertools.chain.from_iterable([mgr.arrays for mgr in mgrs])) + return ArrayManager(arrays, [axes[1], axes[0]]) + concat_plans = [ _get_mgr_concatenation_plan(mgr, indexers) for mgr, indexers in mgrs_indexers ] diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 5161cf7038fe8..57a87e1e283d9 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -19,7 +19,7 @@ import numpy.ma as ma from pandas._libs import lib -from pandas._typing import Axis, DtypeObj, Scalar +from pandas._typing import Axis, DtypeObj, Manager, Scalar from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -149,6 +149,33 @@ def masked_rec_array_to_mgr( return mgr +def mgr_to_mgr(mgr, typ: str): + """ + Convert to specific type of Manager. Does not copy if the type is already + correct. Does not guarantee a copy otherwise. + """ + from pandas.core.internals import ArrayManager, BlockManager + + new_mgr: Manager + + if typ == "block": + if isinstance(mgr, BlockManager): + new_mgr = mgr + else: + new_mgr = arrays_to_mgr( + mgr.arrays, mgr.axes[0], mgr.axes[1], mgr.axes[0], dtype=None + ) + elif typ == "array": + if isinstance(mgr, ArrayManager): + new_mgr = mgr + else: + arrays = [mgr.iget_values(i).copy() for i in range(len(mgr.axes[0]))] + new_mgr = ArrayManager(arrays, [mgr.axes[1], mgr.axes[0]]) + else: + raise ValueError(f"'typ' needs to be one of {{'block', 'array'}}, got '{type}'") + return new_mgr + + # --------------------------------------------------------------------- # DataFrame Constructor Interface diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index fd503280eeafb..cc5576719ff43 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -40,10 +40,10 @@ import pandas.core.algorithms as algos from pandas.core.arrays.sparse import SparseDtype -from pandas.core.base import PandasObject from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.api import Index, ensure_index +from pandas.core.internals.base import DataManager from pandas.core.internals.blocks import ( Block, CategoricalBlock, @@ -62,7 +62,7 @@ T = TypeVar("T", bound="BlockManager") -class BlockManager(PandasObject): +class BlockManager(DataManager): """ Core internal data structure to implement DataFrame, Series, etc. @@ -1229,35 +1229,6 @@ def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False stacklevel=5, ) - def reindex_axis( - self, - new_index, - axis: int, - method=None, - limit=None, - fill_value=None, - copy: bool = True, - consolidate: bool = True, - only_slice: bool = False, - ): - """ - Conform block manager to new index. - """ - new_index = ensure_index(new_index) - new_index, indexer = self.axes[axis].reindex( - new_index, method=method, limit=limit - ) - - return self.reindex_indexer( - new_index, - indexer, - axis=axis, - fill_value=fill_value, - copy=copy, - consolidate=consolidate, - only_slice=only_slice, - ) - def reindex_indexer( self: T, new_axis, diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d1275590306ef..f1d0af60e1c7f 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -21,6 +21,7 @@ Tuple, Type, Union, + cast, ) import warnings @@ -67,6 +68,7 @@ from pandas.core.computation.pytables import PyTablesExpr, maybe_expression from pandas.core.construction import extract_array from pandas.core.indexes.api import ensure_index +from pandas.core.internals import BlockManager from pandas.io.common import stringify_path from pandas.io.formats.printing import adjoin, pprint_thing @@ -3983,19 +3985,21 @@ def _get_blocks_and_items( def get_blk_items(mgr): return [mgr.items.take(blk.mgr_locs) for blk in mgr.blocks] - blocks: List["Block"] = list(frame._mgr.blocks) - blk_items: List[Index] = get_blk_items(frame._mgr) + mgr = frame._mgr + mgr = cast(BlockManager, mgr) + blocks: List["Block"] = list(mgr.blocks) + blk_items: List[Index] = get_blk_items(mgr) if len(data_columns): axis, axis_labels = new_non_index_axes[0] new_labels = Index(axis_labels).difference(Index(data_columns)) mgr = frame.reindex(new_labels, axis=axis)._mgr - blocks = list(mgr.blocks) + blocks = list(mgr.blocks) # type: ignore[union-attr] blk_items = get_blk_items(mgr) for c in data_columns: mgr = frame.reindex([c], axis=axis)._mgr - blocks.extend(mgr.blocks) + blocks.extend(mgr.blocks) # type: ignore[union-attr] blk_items.extend(get_blk_items(mgr)) # reorder the blocks in the same order as the existing table if we can diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py index 356dc800d9662..36c875b8abe6f 100644 --- a/pandas/tests/frame/methods/test_append.py +++ b/pandas/tests/frame/methods/test_append.py @@ -1,10 +1,15 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import DataFrame, Series, Timestamp, date_range, timedelta_range import pandas._testing as tm +# TODO td.skip_array_manager_not_yet_implemented +# appending with reindexing not yet working + class TestDataFrameAppend: def test_append_multiindex(self, multiindex_dataframe_random_data, frame_or_series): @@ -32,6 +37,7 @@ def test_append_empty_list(self): tm.assert_frame_equal(result, expected) assert result is not df # .append() should return a new object + @td.skip_array_manager_not_yet_implemented def test_append_series_dict(self): df = DataFrame(np.random.randn(5, 4), columns=["foo", "bar", "baz", "qux"]) @@ -72,6 +78,7 @@ def test_append_series_dict(self): expected = df.append(df[-1:], ignore_index=True) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented def test_append_list_of_series_dicts(self): df = DataFrame(np.random.randn(5, 4), columns=["foo", "bar", "baz", "qux"]) @@ -90,6 +97,7 @@ def test_append_list_of_series_dicts(self): expected = df.append(DataFrame(dicts), ignore_index=True, sort=True) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented def test_append_missing_cols(self): # GH22252 # exercise the conditional branch in append method where the data @@ -134,6 +142,7 @@ def test_append_empty_dataframe(self): expected = df1.copy() tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented def test_append_dtypes(self): # GH 5754 @@ -193,6 +202,7 @@ def test_append_timestamps_aware_or_naive(self, tz_naive_fixture, timestamp): expected = Series(Timestamp(timestamp, tz=tz), name=0) tm.assert_series_equal(result, expected) + @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize( "data, dtype", [ diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 3c65551aafd0f..a4da77548b920 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -3,6 +3,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import ( Categorical, @@ -90,6 +92,7 @@ def test_astype_mixed_type(self, mixed_type_frame): casted = mn.astype("O") _check_cast(casted, "object") + @td.skip_array_manager_not_yet_implemented def test_astype_with_exclude_string(self, float_frame): df = float_frame.copy() expected = float_frame.astype(int) @@ -124,6 +127,7 @@ def test_astype_with_view_mixed_float(self, mixed_float_frame): casted = tf.astype(np.int64) casted = tf.astype(np.float32) # noqa + @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize("dtype", [np.int32, np.int64]) @pytest.mark.parametrize("val", [np.nan, np.inf]) def test_astype_cast_nan_inf_int(self, val, dtype): @@ -382,6 +386,7 @@ def test_astype_to_datetimelike_unit(self, arr_dtype, dtype, unit): tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) def test_astype_to_datetime_unit(self, unit): # tests all units from datetime origination @@ -406,6 +411,7 @@ def test_astype_to_timedelta_unit_ns(self, unit): tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize("unit", ["us", "ms", "s", "h", "m", "D"]) def test_astype_to_timedelta_unit(self, unit): # coerce to float @@ -429,6 +435,7 @@ def test_astype_to_incorrect_datetimelike(self, unit): msg = ( fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to " fr"\[timedelta64\[{unit}\]\]" + fr"|(Cannot cast DatetimeArray to dtype timedelta64\[{unit}\])" ) with pytest.raises(TypeError, match=msg): df.astype(other) @@ -436,11 +443,13 @@ def test_astype_to_incorrect_datetimelike(self, unit): msg = ( fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to " fr"\[datetime64\[{unit}\]\]" + fr"|(Cannot cast TimedeltaArray to dtype datetime64\[{unit}\])" ) df = DataFrame(np.array([[1, 2, 3]], dtype=other)) with pytest.raises(TypeError, match=msg): df.astype(dtype) + @td.skip_array_manager_not_yet_implemented def test_astype_arg_for_errors(self): # GH#14878 @@ -567,6 +576,7 @@ def test_astype_empty_dtype_dict(self): tm.assert_frame_equal(result, df) assert result is not df + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) ignore keyword @pytest.mark.parametrize( "df", [ diff --git a/pandas/tests/frame/methods/test_count.py b/pandas/tests/frame/methods/test_count.py index d738c7139093c..1727a76c191ee 100644 --- a/pandas/tests/frame/methods/test_count.py +++ b/pandas/tests/frame/methods/test_count.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import DataFrame, Index, Series import pandas._testing as tm @@ -103,6 +105,7 @@ def test_count_index_with_nan(self): ) tm.assert_frame_equal(res, expected) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_count_level( self, multiindex_year_month_day_dataframe_random_data, diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 6cea5abcac6d0..f8d729a215ba8 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -191,14 +191,15 @@ def test_corr_nullable_integer(self, nullable_column, other_column, method): expected = DataFrame(np.ones((2, 2)), columns=["a", "b"], index=["a", "b"]) tm.assert_frame_equal(result, expected) - def test_corr_item_cache(self): + def test_corr_item_cache(self, using_array_manager): # Check that corr does not lead to incorrect entries in item_cache df = DataFrame({"A": range(10)}) df["B"] = range(10)[::-1] ser = df["A"] # populate item_cache - assert len(df._mgr.blocks) == 2 + if not using_array_manager: + assert len(df._mgr.blocks) == 2 _ = df.corr() diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index 148263bad0eb0..1de270fc72fb2 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -1,10 +1,15 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import Categorical, DataFrame, Series, Timestamp, date_range import pandas._testing as tm +# TODO(ArrayManager) quantile is needed for describe() +pytestmark = td.skip_array_manager_not_yet_implemented + class TestDataFrameDescribe: def test_describe_bool_in_mixed_frame(self): diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 58e1bd146191f..bc2b7a4655b8e 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -5,6 +5,7 @@ from pandas.compat import is_numpy_dev from pandas.errors import PerformanceWarning +import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, Timestamp @@ -156,6 +157,7 @@ def test_drop(self): assert return_value is None tm.assert_frame_equal(df, expected) + @td.skip_array_manager_not_yet_implemented def test_drop_multiindex_not_lexsorted(self): # GH#11640 diff --git a/pandas/tests/frame/methods/test_equals.py b/pandas/tests/frame/methods/test_equals.py index de2509ed91be2..dc45c9eb97ae4 100644 --- a/pandas/tests/frame/methods/test_equals.py +++ b/pandas/tests/frame/methods/test_equals.py @@ -1,8 +1,13 @@ import numpy as np +import pandas.util._test_decorators as td + from pandas import DataFrame, date_range import pandas._testing as tm +# TODO(ArrayManager) implement equals +pytestmark = td.skip_array_manager_not_yet_implemented + class TestEquals: def test_dataframe_not_equal(self): diff --git a/pandas/tests/frame/methods/test_explode.py b/pandas/tests/frame/methods/test_explode.py index bd0901387eeed..be80dd49ff1fb 100644 --- a/pandas/tests/frame/methods/test_explode.py +++ b/pandas/tests/frame/methods/test_explode.py @@ -1,9 +1,14 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd import pandas._testing as tm +# TODO(ArrayManager) concat with reindexing +pytestmark = td.skip_array_manager_not_yet_implemented + def test_error(): df = pd.DataFrame( diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index b427611099be3..58016be82c405 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import ( Categorical, DataFrame, @@ -230,6 +232,7 @@ def test_fillna_categorical_nan(self): df = DataFrame({"a": Categorical(idx)}) tm.assert_frame_equal(df.fillna(value=NaT), df) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) implement downcast def test_fillna_downcast(self): # GH#15277 # infer int64 from float64 @@ -244,6 +247,7 @@ def test_fillna_downcast(self): expected = DataFrame({"a": [1, 0]}) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) object upcasting def test_fillna_dtype_conversion(self): # make sure that fillna on an empty frame works df = DataFrame(index=["A", "B", "C"], columns=[1, 2, 3, 4, 5]) @@ -268,6 +272,7 @@ def test_fillna_dtype_conversion(self): result = df.fillna(v) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_invalid_test def test_fillna_datetime_columns(self): # GH#7095 df = DataFrame( @@ -335,13 +340,13 @@ def test_frame_pad_backfill_limit(self): result = df[:2].reindex(index, method="pad", limit=5) expected = df[:2].reindex(index).fillna(method="pad") - expected.values[-3:] = np.nan + expected.iloc[-3:] = np.nan tm.assert_frame_equal(result, expected) result = df[-2:].reindex(index, method="backfill", limit=5) expected = df[-2:].reindex(index).fillna(method="backfill") - expected.values[:3] = np.nan + expected.iloc[:3] = np.nan tm.assert_frame_equal(result, expected) def test_frame_fillna_limit(self): @@ -352,14 +357,14 @@ def test_frame_fillna_limit(self): result = result.fillna(method="pad", limit=5) expected = df[:2].reindex(index).fillna(method="pad") - expected.values[-3:] = np.nan + expected.iloc[-3:] = np.nan tm.assert_frame_equal(result, expected) result = df[-2:].reindex(index) result = result.fillna(method="backfill", limit=5) expected = df[-2:].reindex(index).fillna(method="backfill") - expected.values[:3] = np.nan + expected.iloc[:3] = np.nan tm.assert_frame_equal(result, expected) def test_fillna_skip_certain_blocks(self): diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index 6b86a13fcf1b9..2477ad79d8a2c 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -324,6 +324,7 @@ def test_interp_string_axis(self, axis_name, axis_number): expected = df.interpolate(method="linear", axis=axis_number) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) support axis=1 @pytest.mark.parametrize("method", ["ffill", "bfill", "pad"]) def test_interp_fillna_methods(self, axis, method): # GH 12918 diff --git a/pandas/tests/frame/methods/test_is_homogeneous_dtype.py b/pandas/tests/frame/methods/test_is_homogeneous_dtype.py index 0fca4e988b775..126c78a657c58 100644 --- a/pandas/tests/frame/methods/test_is_homogeneous_dtype.py +++ b/pandas/tests/frame/methods/test_is_homogeneous_dtype.py @@ -1,8 +1,13 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import Categorical, DataFrame +# _is_homogeneous_type always returns True for ArrayManager +pytestmark = td.skip_array_manager_invalid_test + @pytest.mark.parametrize( "data, expected", diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py index eba92cc71a6d0..42694dc3ff37c 100644 --- a/pandas/tests/frame/methods/test_join.py +++ b/pandas/tests/frame/methods/test_join.py @@ -3,10 +3,15 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import DataFrame, Index, MultiIndex, date_range, period_range import pandas._testing as tm +# TODO(ArrayManager) concat with reindexing +pytestmark = td.skip_array_manager_not_yet_implemented + @pytest.fixture def frame_with_period_index(): diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 6ddba8b5e7064..3f7f2e51add96 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -1,10 +1,14 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import DataFrame, Series, Timestamp import pandas._testing as tm +pytestmark = td.skip_array_manager_not_yet_implemented + class TestDataFrameQuantile: @pytest.mark.parametrize( diff --git a/pandas/tests/frame/methods/test_rank.py b/pandas/tests/frame/methods/test_rank.py index 4255c1cb5e65f..5b66f58b8f069 100644 --- a/pandas/tests/frame/methods/test_rank.py +++ b/pandas/tests/frame/methods/test_rank.py @@ -238,6 +238,7 @@ def test_rank_methods_frame(self): expected = DataFrame(sprank, columns=cols).astype("float64") tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented @pytest.mark.parametrize("dtype", ["O", "f8", "i8"]) def test_rank_descending(self, method, dtype): diff --git a/pandas/tests/frame/methods/test_reorder_levels.py b/pandas/tests/frame/methods/test_reorder_levels.py index 6bfbf089a6108..451fc9a5cf717 100644 --- a/pandas/tests/frame/methods/test_reorder_levels.py +++ b/pandas/tests/frame/methods/test_reorder_levels.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import DataFrame, MultiIndex import pandas._testing as tm @@ -47,6 +49,7 @@ def test_reorder_levels(self, frame_or_series): result = obj.reorder_levels(["L0", "L0", "L0"]) tm.assert_equal(result, expected) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_reorder_levels_swaplevel_equivalence( self, multiindex_year_month_day_dataframe_random_data ): diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 00d4a4277a42f..e43eb3fb47b7e 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -4,6 +4,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype import pandas as pd @@ -518,6 +520,7 @@ def test_reset_index_delevel_infer_dtype(self): assert is_integer_dtype(deleveled["prm1"]) assert is_float_dtype(deleveled["prm2"]) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_reset_index_with_drop( self, multiindex_year_month_day_dataframe_random_data ): @@ -616,6 +619,7 @@ def test_reset_index_empty_frame_with_datetime64_multiindex(): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_reset_index_empty_frame_with_datetime64_multiindex_from_groupby(): # https://github.com/pandas-dev/pandas/issues/35657 df = DataFrame({"c1": [10.0], "c2": ["a"], "c3": pd.to_datetime("2020-01-01")}) diff --git a/pandas/tests/frame/methods/test_select_dtypes.py b/pandas/tests/frame/methods/test_select_dtypes.py index f2dbe4a799a17..434df5ccccaf7 100644 --- a/pandas/tests/frame/methods/test_select_dtypes.py +++ b/pandas/tests/frame/methods/test_select_dtypes.py @@ -42,6 +42,9 @@ def __len__(self) -> int: def __getitem__(self, item): pass + def copy(self): + return self + class TestSelectDtypes: def test_select_dtypes_include_using_list_like(self): diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 40b3f1e89c015..aefc407d0c432 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import CategoricalIndex, DataFrame, Index, Series, date_range, offsets import pandas._testing as tm @@ -145,12 +147,13 @@ def test_shift_duplicate_columns(self): tm.assert_frame_equal(shifted[0], shifted[1]) tm.assert_frame_equal(shifted[0], shifted[2]) - def test_shift_axis1_multiple_blocks(self): + def test_shift_axis1_multiple_blocks(self, using_array_manager): # GH#35488 df1 = DataFrame(np.random.randint(1000, size=(5, 3))) df2 = DataFrame(np.random.randint(1000, size=(5, 2))) df3 = pd.concat([df1, df2], axis=1) - assert len(df3._mgr.blocks) == 2 + if not using_array_manager: + assert len(df3._mgr.blocks) == 2 result = df3.shift(2, axis=1) @@ -163,7 +166,8 @@ def test_shift_axis1_multiple_blocks(self): # Case with periods < 0 # rebuild df3 because `take` call above consolidated df3 = pd.concat([df1, df2], axis=1) - assert len(df3._mgr.blocks) == 2 + if not using_array_manager: + assert len(df3._mgr.blocks) == 2 result = df3.shift(-2, axis=1) expected = df3.take([2, 3, 4, -1, -1], axis=1) @@ -272,6 +276,7 @@ def test_datetime_frame_shift_with_freq_error(self, datetime_frame): with pytest.raises(ValueError, match=msg): no_freq.shift(freq="infer") + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) axis=1 support def test_shift_dt64values_int_fill_deprecated(self): # GH#31971 ser = Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 3be6a8453420e..221296bfd6d76 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import ( CategoricalDtype, @@ -371,6 +373,7 @@ def test_sort_index_multiindex(self, level): result = df.sort_index(level=level, sort_remaining=False) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_sort_index_intervalindex(self): # this is a de-facto sort via unstack # confirming that we sort in the order of the bins diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 987848ec697d1..cd3286fa38056 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -566,12 +566,13 @@ def test_sort_values_nat_na_position_default(self): result = expected.sort_values(["A", "date"]) tm.assert_frame_equal(result, expected) - def test_sort_values_item_cache(self): + def test_sort_values_item_cache(self, using_array_manager): # previous behavior incorrect retained an invalid _item_cache entry df = DataFrame(np.random.randn(4, 3), columns=["A", "B", "C"]) df["D"] = df["A"] * 2 ser = df["A"] - assert len(df._mgr.blocks) == 2 + if not using_array_manager: + assert len(df._mgr.blocks) == 2 df.sort_values(by="A") ser.values[0] = 99 diff --git a/pandas/tests/frame/methods/test_to_dict_of_blocks.py b/pandas/tests/frame/methods/test_to_dict_of_blocks.py index 0257a5d43170f..8de47cb17d7d3 100644 --- a/pandas/tests/frame/methods/test_to_dict_of_blocks.py +++ b/pandas/tests/frame/methods/test_to_dict_of_blocks.py @@ -1,9 +1,13 @@ import numpy as np +import pandas.util._test_decorators as td + from pandas import DataFrame, MultiIndex import pandas._testing as tm from pandas.core.arrays import PandasArray +pytestmark = td.skip_array_manager_invalid_test + class TestToDictOfBlocks: def test_copy_blocks(self, float_frame): diff --git a/pandas/tests/frame/methods/test_to_numpy.py b/pandas/tests/frame/methods/test_to_numpy.py index 3d69c004db6bb..0682989294457 100644 --- a/pandas/tests/frame/methods/test_to_numpy.py +++ b/pandas/tests/frame/methods/test_to_numpy.py @@ -1,5 +1,7 @@ import numpy as np +import pandas.util._test_decorators as td + from pandas import DataFrame, Timestamp import pandas._testing as tm @@ -17,6 +19,7 @@ def test_to_numpy_dtype(self): result = df.to_numpy(dtype="int64") tm.assert_numpy_array_equal(result, expected) + @td.skip_array_manager_invalid_test def test_to_numpy_copy(self): arr = np.random.randn(4, 3) df = DataFrame(arr) diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index 8635168f1eb03..548842e653a63 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import DataFrame, date_range import pandas._testing as tm @@ -79,6 +81,7 @@ def test_transpose_float(self, float_frame): for col, s in mixed_T.items(): assert s.dtype == np.object_ + @td.skip_array_manager_invalid_test def test_transpose_get_view(self, float_frame): dft = float_frame.T dft.values[:, 5:10] = 5 diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py index fb0c5d31f692b..5426e4368722e 100644 --- a/pandas/tests/frame/methods/test_values.py +++ b/pandas/tests/frame/methods/test_values.py @@ -1,11 +1,14 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import DataFrame, NaT, Series, Timestamp, date_range, period_range import pandas._testing as tm class TestDataFrameValues: + @td.skip_array_manager_invalid_test def test_values(self, float_frame): float_frame.values[:, 0] = 5.0 assert (float_frame.values[:, 0] == 5).all() diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 22eb642ed8512..afc25c48beb5f 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -972,7 +972,7 @@ def test_align_frame(self): result = ts + ts[::2] expected = ts + ts - expected.values[1::2] = np.nan + expected.iloc[1::2] = np.nan tm.assert_frame_equal(result, expected) half = ts[::2] diff --git a/pandas/tests/internals/test_managers.py b/pandas/tests/internals/test_managers.py new file mode 100644 index 0000000000000..333455875904a --- /dev/null +++ b/pandas/tests/internals/test_managers.py @@ -0,0 +1,40 @@ +""" +Testing interaction between the different managers (BlockManager, ArrayManager) +""" +from pandas.core.dtypes.missing import array_equivalent + +import pandas as pd +import pandas._testing as tm +from pandas.core.internals import ArrayManager, BlockManager + + +def test_dataframe_creation(): + + with pd.option_context("mode.data_manager", "block"): + df_block = pd.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}) + assert isinstance(df_block._mgr, BlockManager) + + with pd.option_context("mode.data_manager", "array"): + df_array = pd.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}) + assert isinstance(df_array._mgr, ArrayManager) + + # also ensure both are seen as equal + tm.assert_frame_equal(df_block, df_array) + + # conversion from one manager to the other + result = df_block._as_manager("block") + assert isinstance(result._mgr, BlockManager) + result = df_block._as_manager("array") + assert isinstance(result._mgr, ArrayManager) + tm.assert_frame_equal(result, df_block) + assert all( + array_equivalent(left, right) + for left, right in zip(result._mgr.arrays, df_array._mgr.arrays) + ) + + result = df_array._as_manager("array") + assert isinstance(result._mgr, ArrayManager) + result = df_array._as_manager("block") + assert isinstance(result._mgr, BlockManager) + tm.assert_frame_equal(result, df_array) + assert len(result._mgr.blocks) == 2 diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index f0d5ef19c4468..2339e21288bb5 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -3,6 +3,8 @@ import pandas._config.config as cf +import pandas.util._test_decorators as td + import pandas as pd import pandas.io.formats.format as fmt @@ -119,6 +121,7 @@ def test_ambiguous_width(self): assert adjoined == expected +@td.skip_array_manager_not_yet_implemented class TestTableSchemaRepr: @classmethod def setup_class(cls): diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index 5faca6bd89dad..6ead81db1fab0 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -5,6 +5,8 @@ import pandas as pd import pandas._testing as tm +pytestmark = td.skip_array_manager_not_yet_implemented + def test_compression_roundtrip(compression): df = pd.DataFrame( diff --git a/pandas/tests/io/json/test_deprecated_kwargs.py b/pandas/tests/io/json/test_deprecated_kwargs.py index 79245bc9d34a8..7367aaefb1c1e 100644 --- a/pandas/tests/io/json/test_deprecated_kwargs.py +++ b/pandas/tests/io/json/test_deprecated_kwargs.py @@ -2,11 +2,15 @@ Tests for the deprecated keyword arguments for `read_json`. """ +import pandas.util._test_decorators as td + import pandas as pd import pandas._testing as tm from pandas.io.json import read_json +pytestmark = td.skip_array_manager_not_yet_implemented + def test_deprecated_kwargs(): df = pd.DataFrame({"A": [2, 4, 6], "B": [3, 6, 9]}, index=[0, 1, 2]) diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 215d663e68d8f..e25964f556e4e 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -6,6 +6,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas.core.dtypes.dtypes import CategoricalDtype, DatetimeTZDtype, PeriodDtype import pandas as pd @@ -20,6 +22,8 @@ set_default_names, ) +pytestmark = td.skip_array_manager_not_yet_implemented + class TestBuildSchema: def setup_method(self, method): diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index b232c827f5ece..d7fc1257d8396 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -3,11 +3,15 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import DataFrame, Index, Series, json_normalize import pandas._testing as tm from pandas.io.json._normalize import nested_to_record +pytestmark = td.skip_array_manager_not_yet_implemented + @pytest.fixture def deep_nested(): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index dba3cb4db3ab8..c3ada52eba5aa 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -15,6 +15,9 @@ from pandas import DataFrame, DatetimeIndex, Series, Timestamp, compat, read_json import pandas._testing as tm +pytestmark = td.skip_array_manager_not_yet_implemented + + _seriesd = tm.getSeriesData() _frame = DataFrame(_seriesd) diff --git a/pandas/tests/io/json/test_readlines.py b/pandas/tests/io/json/test_readlines.py index 099d99507e136..2484c12f42600 100644 --- a/pandas/tests/io/json/test_readlines.py +++ b/pandas/tests/io/json/test_readlines.py @@ -3,12 +3,16 @@ import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import DataFrame, read_json import pandas._testing as tm from pandas.io.json._json import JsonReader +pytestmark = td.skip_array_manager_not_yet_implemented + @pytest.fixture def lines_json_df(): diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 74adb397d91f4..dff506809ee4f 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -16,10 +16,13 @@ import pandas._libs.json as ujson from pandas._libs.tslib import Timestamp from pandas.compat import IS64, is_platform_windows +import pandas.util._test_decorators as td from pandas import DataFrame, DatetimeIndex, Index, NaT, Series, Timedelta, date_range import pandas._testing as tm +pytestmark = td.skip_array_manager_not_yet_implemented + def _clean_dict(d): """ diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py index 71bb6584889aa..72e8b4aea5ede 100644 --- a/pandas/tests/io/pytables/test_complex.py +++ b/pandas/tests/io/pytables/test_complex.py @@ -3,6 +3,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm @@ -10,6 +12,9 @@ from pandas.io.pytables import read_hdf +# TODO(ArrayManager) HDFStore relies on accessing the blocks +pytestmark = td.skip_array_manager_not_yet_implemented + def test_complex_fixed(setup_path): df = DataFrame( diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 3f0fd6e7483f8..131711a32d114 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -55,6 +55,10 @@ from pandas.io.pytables import TableIterator # isort:skip +# TODO(ArrayManager) HDFStore relies on accessing the blocks +pytestmark = td.skip_array_manager_not_yet_implemented + + _default_compressor = "blosc" ignore_natural_naming_warning = pytest.mark.filterwarnings( "ignore:object name:tables.exceptions.NaturalNameWarning" diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 9ee44b58d6ced..a106a579d7e52 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -14,6 +14,9 @@ ensure_clean_store, ) +# TODO(ArrayManager) HDFStore relies on accessing the blocks +pytestmark = td.skip_array_manager_not_yet_implemented + def _compare_with_tz(a, b): tm.assert_frame_equal(a, b) diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 725c14f410357..d31bee9aca135 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -272,7 +272,9 @@ def test_read_fspath_all(self, reader, module, path, datapath): ("to_excel", {"engine": "xlwt"}, "xlwt"), ("to_feather", {}, "pyarrow"), ("to_html", {}, "os"), - ("to_json", {}, "os"), + pytest.param( + "to_json", {}, "os", marks=td.skip_array_manager_not_yet_implemented + ), ("to_latex", {}, "os"), ("to_pickle", {}, "os"), ("to_stata", {"time_stamp": pd.to_datetime("2019-01-01 00:00")}, "os"), diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index 158504082e657..76bc188afdd1f 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -8,11 +8,15 @@ import pytest +import pandas.util._test_decorators as td + import pandas as pd import pandas._testing as tm import pandas.io.common as icom +pytestmark = td.skip_array_manager_not_yet_implemented + @pytest.mark.parametrize( "obj", diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index b1038b6d28083..d9575a6ad81e5 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -247,6 +247,7 @@ def test_pickle_options(fsspectest): tm.assert_frame_equal(df, out) +@td.skip_array_manager_not_yet_implemented def test_json_options(fsspectest): df = DataFrame({"a": [0]}) df.to_json("testmem://afile", storage_options={"test": "json_write"}) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 24944281419c3..035460185fa81 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -12,6 +12,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas.core.dtypes.common import is_categorical_dtype import pandas as pd @@ -29,6 +31,9 @@ read_stata, ) +# TODO(ArrayManager) the stata code relies on BlockManager internals (eg blknos) +pytestmark = td.skip_array_manager_not_yet_implemented + @pytest.fixture() def mixed_frame(): diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py index 32399c7de7a68..fd3ca3919d416 100644 --- a/pandas/tests/io/test_user_agent.py +++ b/pandas/tests/io/test_user_agent.py @@ -8,6 +8,8 @@ import pytest +import pandas.util._test_decorators as td + import pandas as pd import pandas._testing as tm @@ -180,13 +182,25 @@ def do_GET(self): "responder, read_method, port, parquet_engine", [ (CSVUserAgentResponder, pd.read_csv, 34259, None), - (JSONUserAgentResponder, pd.read_json, 34260, None), + pytest.param( + JSONUserAgentResponder, + pd.read_json, + 34260, + None, + marks=td.skip_array_manager_not_yet_implemented, + ), (ParquetPyArrowUserAgentResponder, pd.read_parquet, 34268, "pyarrow"), (ParquetFastParquetUserAgentResponder, pd.read_parquet, 34273, "fastparquet"), (PickleUserAgentResponder, pd.read_pickle, 34271, None), (StataUserAgentResponder, pd.read_stata, 34272, None), (GzippedCSVUserAgentResponder, pd.read_csv, 34261, None), - (GzippedJSONUserAgentResponder, pd.read_json, 34262, None), + pytest.param( + GzippedJSONUserAgentResponder, + pd.read_json, + 34262, + None, + marks=td.skip_array_manager_not_yet_implemented, + ), ], ) def test_server_and_default_headers(responder, read_method, port, parquet_engine): @@ -212,13 +226,25 @@ def test_server_and_default_headers(responder, read_method, port, parquet_engine "responder, read_method, port, parquet_engine", [ (CSVUserAgentResponder, pd.read_csv, 34263, None), - (JSONUserAgentResponder, pd.read_json, 34264, None), + pytest.param( + JSONUserAgentResponder, + pd.read_json, + 34264, + None, + marks=td.skip_array_manager_not_yet_implemented, + ), (ParquetPyArrowUserAgentResponder, pd.read_parquet, 34270, "pyarrow"), (ParquetFastParquetUserAgentResponder, pd.read_parquet, 34275, "fastparquet"), (PickleUserAgentResponder, pd.read_pickle, 34273, None), (StataUserAgentResponder, pd.read_stata, 34274, None), (GzippedCSVUserAgentResponder, pd.read_csv, 34265, None), - (GzippedJSONUserAgentResponder, pd.read_json, 34266, None), + pytest.param( + GzippedJSONUserAgentResponder, + pd.read_json, + 34266, + None, + marks=td.skip_array_manager_not_yet_implemented, + ), ], ) def test_server_and_custom_headers(responder, read_method, port, parquet_engine): diff --git a/pandas/tests/series/methods/test_describe.py b/pandas/tests/series/methods/test_describe.py index a15dc0751aa7d..e479e5c1416db 100644 --- a/pandas/tests/series/methods/test_describe.py +++ b/pandas/tests/series/methods/test_describe.py @@ -1,8 +1,13 @@ import numpy as np +import pandas.util._test_decorators as td + from pandas import Period, Series, Timedelta, Timestamp, date_range import pandas._testing as tm +# TODO(ArrayManager) quantile is needed for describe() +pytestmark = td.skip_array_manager_not_yet_implemented + class TestSeriesDescribe: def test_describe(self): diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py index 1d3e91d07afe3..5771d8e2b8a47 100644 --- a/pandas/tests/series/methods/test_quantile.py +++ b/pandas/tests/series/methods/test_quantile.py @@ -1,6 +1,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas.core.dtypes.common import is_integer import pandas as pd @@ -8,6 +10,8 @@ import pandas._testing as tm from pandas.core.indexes.datetimes import Timestamp +pytestmark = td.skip_array_manager_not_yet_implemented + class TestSeriesQuantile: def test_quantile(self, datetime_series): diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index 209a4233fc3b7..95ef2f6c00fe8 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -274,3 +274,18 @@ def async_mark(): async_mark = pytest.mark.skip(reason="Missing dependency pytest-asyncio") return async_mark + + +# Note: we are using a string as condition (and not for example +# `get_option("mode.data_manager") == "array"`) because this needs to be +# evaluated at test time (otherwise this boolean condition gets evaluated +# at import time, when the pd.options.mode.data_manager has not yet been set) + +skip_array_manager_not_yet_implemented = pytest.mark.skipif( + "config.getvalue('--array-manager')", reason="JSON C code relies on Blocks" +) + +skip_array_manager_invalid_test = pytest.mark.skipif( + "config.getvalue('--array-manager')", + reason="Test that relies on BlockManager internals or specific behaviour", +)
Related to the discussion in https://github.com/pandas-dev/pandas/issues/10556, and following up on the mailing list discussion *"A case for a simplified (non-consolidating) BlockManager with 1D blocks"* ([archive](https://mail.python.org/pipermail/pandas-dev/2020-May/001219.html)). This branch experiments with an *"array manager"*, storing a list of 1D arrays instead of blocks. The idea is that this `ArrayManager` could optionally be used instead of `BlockManager`. If we ensure the "DataManager" has a clear interface for the rest of pandas (and thus parts outside of the internals don't rely on details like block layout, xref https://github.com/pandas-dev/pandas/issues/34669), this should be possible without much changes outside of /core/internals. Some notes on this experiment: - This is not a complete POC, not every aspect and behaviour of the BlockManager has already been replicated, and there are still places in pandas that rely on the blocks being present, so lots of tests are still failing (although changes in behaviour are also desired). That said, a *lot* of the basic operations do work. Two illustrations of this: - An updated version of the notebook I showed in the mailing list discussion as well: with a certain setup, comparing a set of operations between block vs array manager: https://nbviewer.jupyter.org/gist/jorisvandenbossche/f917d4301d21069e2be2e3b7c7aa4d07 - I ran the arithmetic.py benchmark file, comparing against master, see below for the results. - For now, I focused on an ArrayManager storing a list of *numpy arrays*. Of course we need to expand that to support ExtensionArrays as well (or ExtensionArrays only?), but the reason I limited to numpy arrays for now: besides making it a bit simpler to experiment with, this also gives a fairer comparison with the consolidated BlockManager (because it focuses on the numpy array being 1D vs 2D, and doesn't mix in performance/implementation differences of numpy array vs ExtensionArray). - Personally, I think this looks promising. Many of the methods are a *lot* simpler than the BlockManager equivalent (although not every aspect is implemented yet, that's correct). And for the case I showed in the notebook, performance looks also good. For the benchmark suite I ran, there are obviously slowdowns for the "wide dataframe" benchmarks. There is still a lot of work needed to make this fully working with the rest of pandas, though ;) - Given the early proof of concept stage, detailed code feedback is not yet needed, but I would find it very useful to discuss the following aspects: - High-level feedback on the approach: does the approach of the two subclasses look interesting? The approach of the ArrayManager itself storing a list of arrays? ... - What to do with Series, which now is a SingleBlockManager inheriting from BlockManager (should we also have a "SingleArrayManager"?) - *If* we find this interesting, how can we go from here? How do we decide on this? (what aspects already need to work, how fast does it need to be?) I don't think getting a fully complete implementation passing all tests is is possible in a single PR. Are we fine with merging something partial in master and continue from there? Or a shared feature branch in upstream? ... <details> <summary>Benchmark results for asv_bench/arithmetic.py</summary> As an example, I ran `asv continuous -f 1.1 upstream/master HEAD -b arithmetic`. The benchmarks with a slowdown bigger than a factor 2 can basically be brought back to two cases: - Benchmarks for "wide" dataframes (eg `FrameWithFrameWide` using a case with n_cols > n_rows) - Benchmarks from the `IntFrameWithScalar` class: from a quick profile, it seems that the usage of numexpr is the cause, and disabling this seems to reduce the slowdown to a factor 2. The numexpr code (and checking if it should be used etc) apparently has a high overhead per call, which I assume is something that can be solved (moving those checks a level higher up, so we don't need to repeat it for each column) ``` before after ratio [b45327f5] [047f9091] <master> ! 40.6±6ms failed n/a arithmetic.Ops.time_frame_multi_and(False, 'default') ! 32.7±2ms failed n/a arithmetic.Ops.time_frame_multi_and(False, 1) ! 26.5±1ms failed n/a arithmetic.Ops.time_frame_multi_and(True, 'default') ! 37.7±2ms failed n/a arithmetic.Ops.time_frame_multi_and(True, 1) + 1.06±0.3ms 93.5±7ms 88.57 arithmetic.FrameWithFrameWide.time_op_same_blocks(<built-in function gt>) + 1.51±0.2ms 80.6±3ms 53.34 arithmetic.FrameWithFrameWide.time_op_same_blocks(<built-in function add>) + 1.22±0.08ms 55.1±5ms 45.19 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('le') + 1.30±0.07ms 55.6±20ms 42.83 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('ne') + 2.12±0.4ms 90.1±4ms 42.47 arithmetic.FrameWithFrameWide.time_op_different_blocks(<built-in function gt>) + 1.17±0.04ms 49.4±4ms 42.38 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('gt') + 1.28±0.07ms 52.9±3ms 41.28 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('lt') + 1.29±0.2ms 52.5±0.6ms 40.63 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('ge') + 1.44±0.02ms 56.8±7ms 39.56 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('eq') + 2.08±0.3ms 78.9±10ms 37.90 arithmetic.Ops2.time_frame_float_mod + 2.34±0.1ms 78.3±4ms 33.51 arithmetic.FrameWithFrameWide.time_op_different_blocks(<built-in function add>) + 1.66±0.2ms 46.6±1ms 28.00 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('mul') + 1.78±0.2ms 48.2±5ms 27.02 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('truediv') + 1.14±0.04ms 26.8±4ms 23.49 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function le>) + 1.83±0.2ms 42.9±1ms 23.39 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('add') + 1.94±0.3ms 45.1±4ms 23.29 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('sub') + 1.23±0.07ms 23.0±3ms 18.65 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function ge>) + 1.33±0.08ms 22.8±1ms 17.14 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function eq>) + 1.03±0.05ms 17.6±2ms 17.13 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function ge>) + 1.65±0.5ms 28.1±7ms 17.00 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function eq>) + 1.21±0.05ms 20.1±3ms 16.67 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function gt>) + 1.18±0.03ms 19.4±0.9ms 16.54 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function eq>) + 1.08±0.07ms 17.8±1ms 16.53 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function lt>) + 1.22±0.05ms 20.0±2ms 16.41 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function gt>) + 1.30±0.06ms 21.2±3ms 16.28 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function ne>) + 1.15±0.06ms 18.6±3ms 16.18 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function lt>) + 1.42±0.1ms 22.6±1ms 15.96 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function lt>) + 1.11±0.01ms 17.6±0.4ms 15.85 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function ne>) + 5.30±0.8ms 81.7±20ms 15.40 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('lt') + 1.37±0.2ms 20.7±3ms 15.09 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function gt>) + 1.22±0.05ms 18.0±6ms 14.72 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function ge>) + 1.28±0.1ms 18.6±3ms 14.55 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function gt>) + 1.17±0.08ms 17.0±3ms 14.54 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function gt>) + 1.22±0.1ms 17.6±0.8ms 14.44 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function eq>) + 1.35±0.1ms 19.4±2ms 14.35 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function le>) + 1.35±0.1ms 19.2±4ms 14.21 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function ge>) + 4.36±0.3ms 61.8±8ms 14.17 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('le') + 1.31±0.1ms 18.5±2ms 14.09 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function lt>) + 4.48±0.5ms 62.9±5ms 14.06 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('ge') + 1.15±0.1ms 16.1±1ms 14.01 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function ne>) + 1.33±0.1ms 18.6±2ms 14.00 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function ge>) + 4.37±0.4ms 58.9±2ms 13.48 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('ne') + 1.22±0.2ms 16.2±3ms 13.25 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function le>) + 1.25±0.1ms 16.5±1ms 13.13 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function le>) + 1.44±0.2ms 18.6±4ms 12.90 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function ge>) + 1.75±0.3ms 22.3±2ms 12.74 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function eq>) + 1.42±0.3ms 18.0±7ms 12.68 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function gt>) + 1.36±0.1ms 17.2±1ms 12.67 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function ne>) + 440±30μs 5.57±0.1ms 12.65 arithmetic.Ops2.time_frame_series_dot + 1.63±0.2ms 20.6±2ms 12.65 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function lt>) + 1.35±0.07ms 17.0±3ms 12.58 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function le>) + 1.34±0.2ms 16.7±1ms 12.46 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function eq>) + 1.50±0.1ms 18.6±5ms 12.43 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function ge>) + 1.35±0.07ms 16.8±1ms 12.42 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function ge>) + 1.35±0.1ms 16.7±2ms 12.37 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function le>) + 1.55±0.3ms 18.9±2ms 12.20 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function le>) + 1.67±0.3ms 20.3±5ms 12.17 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function ne>) + 1.55±0.2ms 18.5±0.7ms 11.94 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function le>) + 5.05±0.5ms 59.1±3ms 11.70 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('gt') + 1.51±0.2ms 17.6±2ms 11.66 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function lt>) + 1.33±0.08ms 15.3±1ms 11.50 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function ne>) + 4.47±0.1ms 51.2±1ms 11.45 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('eq') + 1.35±0.1ms 15.4±2ms 11.45 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function lt>) + 1.76±0.5ms 19.8±2ms 11.28 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function lt>) + 1.55±0.09ms 16.8±0.3ms 10.86 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function ne>) + 1.71±0.1ms 18.2±2ms 10.58 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function eq>) + 1.51±0.2ms 15.9±3ms 10.54 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function eq>) + 1.53±0.2ms 15.6±0.3ms 10.19 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function ne>) + 1.95±0.2ms 19.7±5ms 10.08 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function gt>) + 2.22±0.08ms 21.6±4ms 9.73 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function add>) + 1.77±0.08ms 16.7±1ms 9.48 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function gt>) + 2.19±0.1ms 19.9±2ms 9.08 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function mul>) + 1.91±0.04ms 17.0±2ms 8.88 arithmetic.Ops.time_frame_comparison(True, 'default') + 2.18±0.1ms 19.0±1ms 8.73 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function add>) + 2.23±0.08ms 19.1±1ms 8.59 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function sub>) + 2.24±0.07ms 19.0±3ms 8.47 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function mul>) + 2.34±0.06ms 19.5±2ms 8.31 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function truediv>) + 2.52±0.2ms 20.3±6ms 8.06 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function truediv>) + 2.39±0.2ms 19.2±2ms 8.05 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function truediv>) + 3.07±0.4ms 24.4±5ms 7.94 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function mod>) + 2.24±0.1ms 17.5±2ms 7.85 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function add>) + 2.24±0.2ms 17.4±0.7ms 7.79 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function sub>) + 2.33±0.1ms 18.0±2ms 7.73 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function mul>) + 2.15±0.1ms 16.4±4ms 7.60 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function sub>) + 2.10±0.05ms 15.9±2ms 7.57 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function add>) + 2.27±0.1ms 16.8±1ms 7.39 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function add>) + 3.59±0.1ms 26.1±5ms 7.27 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function mod>) + 2.32±0.1ms 16.8±3ms 7.25 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function sub>) + 2.36±0.08ms 17.1±0.7ms 7.23 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function truediv>) + 2.42±0.2ms 17.4±2ms 7.17 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function sub>) + 2.31±0.09ms 16.4±0.9ms 7.11 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function add>) + 7.34±0.9ms 52.2±2ms 7.10 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('add') + 2.32±0.1ms 16.4±0.9ms 7.07 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function add>) + 2.25±0.2ms 15.8±2ms 7.03 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function sub>) + 2.51±0.5ms 17.3±2ms 6.91 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function add>) + 2.43±0.1ms 16.7±0.8ms 6.84 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function mul>) + 2.24±0.1ms 15.2±2ms 6.81 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function mul>) + 7.81±1ms 52.9±4ms 6.78 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('sub') + 2.48±0.2ms 16.4±2ms 6.62 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function mul>) + 6.82±1ms 44.4±0.7ms 6.51 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('mul') + 2.25±0.05ms 14.6±0.8ms 6.48 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function sub>) + 3.14±0.7ms 19.8±2ms 6.30 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function mod>) + 2.57±0.2ms 15.9±2ms 6.19 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function sub>) + 2.57±0.1ms 15.8±2ms 6.16 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function truediv>) + 7.70±1ms 47.2±3ms 6.13 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('truediv') + 3.02±0.1ms 18.4±3ms 6.08 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function mod>) + 2.79±0.2ms 16.8±0.8ms 6.04 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function truediv>) + 3.16±0.3ms 19.1±0.7ms 6.04 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function mod>) + 2.51±0.2ms 14.9±0.5ms 5.92 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function mul>) + 2.71±0.1ms 15.9±0.8ms 5.86 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function mul>) + 2.72±0.3ms 15.9±1ms 5.83 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function truediv>) + 11.9±1ms 64.0±5ms 5.39 arithmetic.Ops2.time_frame_int_mod + 3.59±0.4ms 19.1±5ms 5.33 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 2, <built-in function mod>) + 6.23±0.4ms 32.7±6ms 5.25 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 2, <built-in function mod>) + 3.28±0.2ms 17.2±2ms 5.23 arithmetic.Ops.time_frame_add(True, 'default') + 23.7±6ms 112±7ms 4.70 arithmetic.FrameWithFrameWide.time_op_same_blocks(<built-in function floordiv>) + 3.51±0.4ms 16.5±0.6ms 4.70 arithmetic.Ops.time_frame_mult(True, 'default') + 3.61±2ms 16.3±1ms 4.52 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function truediv>) + 45.8±4ms 194±20ms 4.25 arithmetic.FrameWithFrameWide.time_op_different_blocks(<built-in function floordiv>) + 5.64±0.6ms 21.9±1ms 3.89 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 4, <built-in function mod>) + 3.13±0.1ms 11.4±0.5ms 3.63 arithmetic.Ops.time_frame_comparison(True, 1) + 12.2±0.8ms 42.5±4ms 3.47 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 5.0, <built-in function pow>) + 4.03±0.7ms 11.2±0.3ms 2.79 arithmetic.Ops.time_frame_add(True, 1) + 53.0±6ms 143±10ms 2.69 arithmetic.Ops2.time_frame_float_floor_by_zero + 4.11±0.2ms 11.1±1ms 2.69 arithmetic.Ops.time_frame_mult(True, 1) + 54.9±4ms 125±9ms 2.28 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('floordiv') + 25.0±0.6ms 55.9±5ms 2.24 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 4, <built-in function pow>) + 2.42±0.2ms 5.21±0.6ms 2.16 arithmetic.Ops.time_frame_comparison(False, 'default') + 16.2±1ms 31.9±3ms 1.97 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.int64'>, 3.0, <built-in function pow>) + 30.9±3ms 58.1±10ms 1.88 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 5.0, <built-in function pow>) + 3.36±0.3ms 5.76±0.4ms 1.71 arithmetic.Ops.time_frame_add(False, 'default') + 3.10±0.3ms 5.03±0.3ms 1.62 arithmetic.Ops.time_frame_comparison(False, 1) + 30.5±3ms 49.2±9ms 1.61 arithmetic.IntFrameWithScalar.time_frame_op_with_scalar(<class 'numpy.float64'>, 3.0, <built-in function pow>) + 3.42±0.3ms 5.51±0.4ms 1.61 arithmetic.Ops.time_frame_mult(False, 1) + 3.52±0.2ms 5.63±0.1ms 1.60 arithmetic.Ops.time_frame_add(False, 1) + 3.60±0.2ms 5.74±0.5ms 1.59 arithmetic.Ops.time_frame_mult(False, 'default') + 57.9±1ms 89.7±6ms 1.55 arithmetic.Ops2.time_frame_float_div + 32.1±0.5ms 48.7±2ms 1.52 arithmetic.Ops2.time_frame_dot + 2.96±0.06ms 4.32±0.4ms 1.46 arithmetic.DateInferOps.time_add_timedeltas + 65.9±2ms 93.8±1ms 1.42 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis1('pow') + 106±2ms 132±3ms 1.25 arithmetic.MixedFrameWithSeriesAxis.time_frame_op_with_series_axis0('pow') + 1.33±0.01ms 1.64±0.2ms 1.24 arithmetic.OffsetArrayArithmetic.time_add_series_offset(<YearEnd: month=12>) + 7.09±0.2ms 8.49±0.5ms 1.20 arithmetic.DateInferOps.time_subtract_datetimes + 1.13±0ms 1.33±0.09ms 1.18 arithmetic.OffsetArrayArithmetic.time_add_series_offset(<YearBegin: month=1>) + 1.25±0.02ms 1.47±0.1ms 1.18 arithmetic.OffsetArrayArithmetic.time_add_series_offset(<SemiMonthEnd: day_of_month=15>) + 2.52±0.04ms 2.97±0.2ms 1.18 arithmetic.OffsetArrayArithmetic.time_add_series_offset(<BusinessDay>) + 1.16±0.01ms 1.32±0.06ms 1.13 arithmetic.OffsetArrayArithmetic.time_add_series_offset(<QuarterBegin: startingMonth=3>) - 1.67±0.2ms 1.42±0.02ms 0.85 arithmetic.OffsetArrayArithmetic.time_add_dti_offset(<MonthEnd>) - 282±20μs 230±5μs 0.81 arithmetic.NumericInferOps.time_subtract(<class 'numpy.int8'>) - 4.36±0.2ms 3.54±0.3ms 0.81 arithmetic.NumericInferOps.time_modulo(<class 'numpy.uint16'>) - 1.29±0.1ms 1.03±0.06ms 0.80 arithmetic.NumericInferOps.time_multiply(<class 'numpy.int64'>) - 1.77±0.09ms 1.39±0.03ms 0.79 arithmetic.OffsetArrayArithmetic.time_add_dti_offset(<SemiMonthBegin: day_of_month=15>) - 1.54±0.2ms 1.13±0.02ms 0.74 arithmetic.NumericInferOps.time_divide(<class 'numpy.int8'>) - 301±40μs 221±4μs 0.73 arithmetic.OffsetArrayArithmetic.time_add_series_offset(<Day>) - 3.85±0.5ms 2.58±0.2ms 0.67 arithmetic.OffsetArrayArithmetic.time_add_dti_offset(<BusinessDay>) SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE DECREASED. ``` </details>
https://api.github.com/repos/pandas-dev/pandas/pulls/36010
2020-08-31T14:17:54Z
2021-01-13T13:23:14Z
2021-01-13T13:23:14Z
2021-01-13T14:10:37Z
Backport PR #35936: (REGR: Fix inplace updates on column to set correct values)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index a87e06678faad..b0d375a52f8ac 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`DatetimeIndex.intersection` incorrectly raising ``AssertionError`` when intersecting against a list (:issue:`35876`) +- Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) - diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 4c3805f812bb0..c4a866edba490 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1046,6 +1046,7 @@ def iset(self, loc: Union[int, slice, np.ndarray], value): Set new item in-place. Does not consolidate. Adds new Block if not contained in the current set of items """ + value = extract_array(value, extract_numpy=True) # FIXME: refactor, clearly separate broadcasting & zip-like assignment # can prob also fix the various if tests for sparse/categorical if self._blklocs is None and self.ndim > 1: diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 78000c0252375..11dc3069ee08e 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -354,6 +354,12 @@ def test_fillna_frame(self, data_missing): # Non-scalar "scalar" values. super().test_fillna_frame(data_missing) + @pytest.mark.skip("Invalid test") + def test_fillna_fill_other(self, data): + # inplace update doesn't work correctly with patched extension arrays + # extract_array returns PandasArray, while dtype is a numpy dtype + super().test_fillna_fill_other(data_missing) + class TestReshaping(BaseNumPyTests, base.BaseReshapingTests): @pytest.mark.skip("Incorrect parent test") diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index c9fec3215d57f..b8183eb9f4185 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -626,3 +626,17 @@ def test_add_column_with_pandas_array(self): assert type(df["c"]._mgr.blocks[0]) == ObjectBlock assert type(df2["c"]._mgr.blocks[0]) == ObjectBlock tm.assert_frame_equal(df, df2) + + +def test_update_inplace_sets_valid_block_values(): + # https://github.com/pandas-dev/pandas/issues/33457 + df = pd.DataFrame({"a": pd.Series([1, 2, None], dtype="category")}) + + # inplace update of a single column + df["a"].fillna(1, inplace=True) + + # check we havent put a Series into any block.values + assert isinstance(df._mgr.blocks[0].values, pd.Categorical) + + # smoketest for OP bug from GH#35731 + assert df.isnull().sum().sum() == 0
xref #35936
https://api.github.com/repos/pandas-dev/pandas/pulls/36009
2020-08-31T13:08:37Z
2020-09-01T14:16:35Z
2020-09-01T14:16:35Z
2020-09-01T14:16:51Z
TYP: check_untyped_defs core.internals.concat
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 99a586f056b12..88839d2211f81 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -1,10 +1,11 @@ from collections import defaultdict import copy -from typing import List +from typing import Dict, List import numpy as np from pandas._libs import NaT, internals as libinternals +from pandas._typing import DtypeObj from pandas.util._decorators import cache_readonly from pandas.core.dtypes.cast import maybe_promote @@ -100,10 +101,10 @@ def _get_mgr_concatenation_plan(mgr, indexers): """ # Calculate post-reindex shape , save for item axis which will be separate # for each block anyway. - mgr_shape = list(mgr.shape) + mgr_shape_list = list(mgr.shape) for ax, indexer in indexers.items(): - mgr_shape[ax] = len(indexer) - mgr_shape = tuple(mgr_shape) + mgr_shape_list[ax] = len(indexer) + mgr_shape = tuple(mgr_shape_list) if 0 in indexers: ax0_indexer = indexers.pop(0) @@ -126,9 +127,9 @@ def _get_mgr_concatenation_plan(mgr, indexers): join_unit_indexers = indexers.copy() - shape = list(mgr_shape) - shape[0] = len(placements) - shape = tuple(shape) + shape_list = list(mgr_shape) + shape_list[0] = len(placements) + shape = tuple(shape_list) if blkno == -1: unit = JoinUnit(None, shape) @@ -374,8 +375,8 @@ def _get_empty_dtype_and_na(join_units): else: dtypes[i] = unit.dtype - upcast_classes = defaultdict(list) - null_upcast_classes = defaultdict(list) + upcast_classes: Dict[str, List[DtypeObj]] = defaultdict(list) + null_upcast_classes: Dict[str, List[DtypeObj]] = defaultdict(list) for dtype, unit in zip(dtypes, join_units): if dtype is None: continue diff --git a/setup.cfg b/setup.cfg index 2ba22e5aad3c7..c10624d60aaff 100644 --- a/setup.cfg +++ b/setup.cfg @@ -184,9 +184,6 @@ check_untyped_defs=False [mypy-pandas.core.internals.blocks] check_untyped_defs=False -[mypy-pandas.core.internals.concat] -check_untyped_defs=False - [mypy-pandas.core.internals.construction] check_untyped_defs=False
pandas\core\internals\concat.py:106: error: Incompatible types in assignment (expression has type "Tuple[Any, ...]", variable has type "List[Any]") [assignment] pandas\core\internals\concat.py:131: error: Incompatible types in assignment (expression has type "Tuple[Any, ...]", variable has type "List[Any]") [assignment] pandas\core\internals\concat.py:377: error: Need type annotation for 'upcast_classes' [var-annotated] pandas\core\internals\concat.py:378: error: Need type annotation for 'null_upcast_classes' [var-annotated]
https://api.github.com/repos/pandas-dev/pandas/pulls/36008
2020-08-31T12:33:43Z
2020-08-31T20:26:35Z
2020-08-31T20:26:35Z
2020-09-01T09:16:11Z
TYP: misc typing cleanup in core/indexes/multi.py
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index b29c27982f087..f66b009e6d505 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -19,7 +19,7 @@ from pandas._libs import algos as libalgos, index as libindex, lib from pandas._libs.hashtable import duplicated_int64 -from pandas._typing import AnyArrayLike, Scalar +from pandas._typing import AnyArrayLike, Label, Scalar from pandas.compat.numpy import function as nv from pandas.errors import InvalidIndexError, PerformanceWarning, UnsortedIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -449,7 +449,12 @@ def from_arrays(cls, arrays, sortorder=None, names=lib.no_default) -> "MultiInde ) @classmethod - def from_tuples(cls, tuples, sortorder=None, names=None): + def from_tuples( + cls, + tuples, + sortorder: Optional[int] = None, + names: Optional[Sequence[Label]] = None, + ): """ Convert list of tuples to MultiIndex. @@ -490,6 +495,7 @@ def from_tuples(cls, tuples, sortorder=None, names=None): elif is_iterator(tuples): tuples = list(tuples) + arrays: List[Sequence[Label]] if len(tuples) == 0: if names is None: raise TypeError("Cannot infer number of levels from empty list") @@ -700,8 +706,13 @@ def levels(self): return FrozenList(result) def _set_levels( - self, levels, level=None, copy=False, validate=True, verify_integrity=False - ): + self, + levels, + level=None, + copy: bool = False, + validate: bool = True, + verify_integrity: bool = False, + ) -> None: # This is NOT part of the levels property because it should be # externally not allowed to set levels. User beware if you change # _levels directly @@ -719,10 +730,10 @@ def _set_levels( ) else: level_numbers = [self._get_level_number(lev) for lev in level] - new_levels = list(self._levels) + new_levels_list = list(self._levels) for lev_num, lev in zip(level_numbers, levels): - new_levels[lev_num] = ensure_index(lev, copy=copy)._shallow_copy() - new_levels = FrozenList(new_levels) + new_levels_list[lev_num] = ensure_index(lev, copy=copy)._shallow_copy() + new_levels = FrozenList(new_levels_list) if verify_integrity: new_codes = self._verify_integrity(levels=new_levels) @@ -875,8 +886,13 @@ def codes(self): return self._codes def _set_codes( - self, codes, level=None, copy=False, validate=True, verify_integrity=False - ): + self, + codes, + level=None, + copy: bool = False, + validate: bool = True, + verify_integrity: bool = False, + ) -> None: if validate: if level is None and len(codes) != self.nlevels: raise ValueError("Length of codes must match number of levels") @@ -890,11 +906,13 @@ def _set_codes( ) else: level_numbers = [self._get_level_number(lev) for lev in level] - new_codes = list(self._codes) + new_codes_list = list(self._codes) for lev_num, level_codes in zip(level_numbers, codes): lev = self.levels[lev_num] - new_codes[lev_num] = _coerce_indexer_frozen(level_codes, lev, copy=copy) - new_codes = FrozenList(new_codes) + new_codes_list[lev_num] = _coerce_indexer_frozen( + level_codes, lev, copy=copy + ) + new_codes = FrozenList(new_codes_list) if verify_integrity: new_codes = self._verify_integrity(codes=new_codes) @@ -2435,7 +2453,7 @@ def _get_partial_string_timestamp_match_key(self, key): if isinstance(key, str) and self.levels[0]._supports_partial_string_indexing: # Convert key '2016-01-01' to # ('2016-01-01'[, slice(None, None, None)]+) - key = tuple([key] + [slice(None)] * (len(self.levels) - 1)) + key = (key,) + (slice(None),) * (len(self.levels) - 1) if isinstance(key, tuple): # Convert (..., '2016-01-01', ...) in tuple to @@ -3086,7 +3104,7 @@ def _update_indexer(idxr, indexer=indexer): elif is_list_like(k): # a collection of labels to include from this level (these # are or'd) - indexers = None + indexers: Optional[Int64Index] = None for x in k: try: idxrs = _convert_to_indexer(
pandas\core\indexes\multi.py:496: error: Need type annotation for 'arrays' [var-annotated] pandas\core\indexes\multi.py:722: error: Incompatible types in assignment (expression has type "List[Any]", variable has type "FrozenList") [assignment] pandas\core\indexes\multi.py:893: error: Incompatible types in assignment (expression has type "List[Any]", variable has type "FrozenList") [assignment] pandas\core\indexes\multi.py:2438: error: List item 0 has incompatible type "slice"; expected "str" [list-item] pandas\core\indexes\multi.py:3095: error: Unsupported left operand type for | ("None") [operator]
https://api.github.com/repos/pandas-dev/pandas/pulls/36007
2020-08-31T11:52:25Z
2020-09-01T16:26:46Z
2020-09-01T16:26:46Z
2020-09-01T16:33:31Z
TYP: misc typing cleanup for core/computation/expressions.py
diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 05a5538a88772..a9c0cb0571446 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -6,6 +6,7 @@ """ import operator +from typing import List, Set import warnings import numpy as np @@ -21,7 +22,7 @@ import numexpr as ne _TEST_MODE = None -_TEST_RESULT = None +_TEST_RESULT: List[bool] = list() _USE_NUMEXPR = _NUMEXPR_INSTALLED _evaluate = None _where = None @@ -75,7 +76,7 @@ def _can_use_numexpr(op, op_str, a, b, dtype_check): # required min elements (otherwise we are adding overhead) if np.prod(a.shape) > _MIN_ELEMENTS: # check for dtype compatibility - dtypes = set() + dtypes: Set[str] = set() for o in [a, b]: # Series implements dtypes, check for dimension count as well if hasattr(o, "dtypes") and o.ndim > 1: @@ -247,25 +248,28 @@ def where(cond, a, b, use_numexpr=True): return _where(cond, a, b) if use_numexpr else _where_standard(cond, a, b) -def set_test_mode(v=True): +def set_test_mode(v: bool = True) -> None: """ - Keeps track of whether numexpr was used. Stores an additional ``True`` - for every successful use of evaluate with numexpr since the last - ``get_test_result`` + Keeps track of whether numexpr was used. + + Stores an additional ``True`` for every successful use of evaluate with + numexpr since the last ``get_test_result``. """ global _TEST_MODE, _TEST_RESULT _TEST_MODE = v _TEST_RESULT = [] -def _store_test_result(used_numexpr): +def _store_test_result(used_numexpr: bool) -> None: global _TEST_RESULT if used_numexpr: _TEST_RESULT.append(used_numexpr) -def get_test_result(): - """get test result and reset test_results""" +def get_test_result() -> List[bool]: + """ + Get test result and reset test_results. + """ global _TEST_RESULT res = _TEST_RESULT _TEST_RESULT = []
pandas\core\computation\expressions.py:78: error: Need type annotation for 'dtypes' (hint: "dtypes: Set[<type>] = ...") [var-annotated] pandas\core\computation\expressions.py:258: error: Need type annotation for '_TEST_RESULT' (hint: "_TEST_RESULT: List[<type>] = ...") [var-annotated]
https://api.github.com/repos/pandas-dev/pandas/pulls/36005
2020-08-31T11:07:47Z
2020-08-31T20:45:17Z
2020-08-31T20:45:17Z
2020-09-01T09:19:38Z
BUG: Can't restore index from parquet with offset-specified timezone #35997
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 21d54e2514f8b..a4597e61971a1 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -392,6 +392,7 @@ I/O - Bug in :meth:`read_csv` with ``engine='python'`` truncating data if multiple items present in first row and first element started with BOM (:issue:`36343`) - Removed ``private_key`` and ``verbose`` from :func:`read_gbq` as they are no longer supported in ``pandas-gbq`` (:issue:`34654`, :issue:`30200`) - Bumped minimum pytables version to 3.5.1 to avoid a ``ValueError`` in :meth:`read_hdf` (:issue:`24839`) +- Bug in :meth:`read_parquet` with fixed offset timezones. String representation of timezones was not recognized (:issue:`35997`, :issue:`36004`) Plotting ^^^^^^^^ diff --git a/pandas/_libs/tslibs/timezones.pyx b/pandas/_libs/tslibs/timezones.pyx index b82291a71057e..3deabc57ec522 100644 --- a/pandas/_libs/tslibs/timezones.pyx +++ b/pandas/_libs/tslibs/timezones.pyx @@ -1,4 +1,4 @@ -from datetime import timezone +from datetime import timedelta, timezone from cpython.datetime cimport datetime, timedelta, tzinfo @@ -102,6 +102,14 @@ cpdef inline tzinfo maybe_get_tz(object tz): # On Python 3 on Windows, the filename is not always set correctly. if isinstance(tz, _dateutil_tzfile) and '.tar.gz' in tz._filename: tz._filename = zone + elif tz[0] in {'-', '+'}: + hours = int(tz[0:3]) + minutes = int(tz[0] + tz[4:6]) + tz = timezone(timedelta(hours=hours, minutes=minutes)) + elif tz[0:4] in {'UTC-', 'UTC+'}: + hours = int(tz[3:6]) + minutes = int(tz[3] + tz[7:9]) + tz = timezone(timedelta(hours=hours, minutes=minutes)) else: tz = pytz.timezone(tz) elif is_integer_object(tz): diff --git a/pandas/conftest.py b/pandas/conftest.py index 5ac5e3670f69f..998c45d82fb4d 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -857,6 +857,10 @@ def iris(datapath): "Asia/Tokyo", "dateutil/US/Pacific", "dateutil/Asia/Singapore", + "+01:15", + "-02:15", + "UTC+01:15", + "UTC-02:15", tzutc(), tzlocal(), FixedOffset(300), diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index f7b25f8c0eeac..9114edc19315f 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -125,6 +125,21 @@ def df_full(): ) +@pytest.fixture( + params=[ + datetime.datetime.now(datetime.timezone.utc), + datetime.datetime.now(datetime.timezone.min), + datetime.datetime.now(datetime.timezone.max), + datetime.datetime.strptime("2019-01-04T16:41:24+0200", "%Y-%m-%dT%H:%M:%S%z"), + datetime.datetime.strptime("2019-01-04T16:41:24+0215", "%Y-%m-%dT%H:%M:%S%z"), + datetime.datetime.strptime("2019-01-04T16:41:24-0200", "%Y-%m-%dT%H:%M:%S%z"), + datetime.datetime.strptime("2019-01-04T16:41:24-0215", "%Y-%m-%dT%H:%M:%S%z"), + ] +) +def timezone_aware_date_list(request): + return request.param + + def check_round_trip( df, engine=None, @@ -134,6 +149,7 @@ def check_round_trip( expected=None, check_names=True, check_like=False, + check_dtype=True, repeat=2, ): """Verify parquet serializer and deserializer produce the same results. @@ -175,7 +191,11 @@ def compare(repeat): actual = read_parquet(path, **read_kwargs) tm.assert_frame_equal( - expected, actual, check_names=check_names, check_like=check_like + expected, + actual, + check_names=check_names, + check_like=check_like, + check_dtype=check_dtype, ) if path is None: @@ -739,6 +759,21 @@ def test_timestamp_nanoseconds(self, pa): df = pd.DataFrame({"a": pd.date_range("2017-01-01", freq="1n", periods=10)}) check_round_trip(df, pa, write_kwargs={"version": "2.0"}) + def test_timezone_aware_index(self, pa, timezone_aware_date_list): + idx = 5 * [timezone_aware_date_list] + df = pd.DataFrame(index=idx, data={"index_as_col": idx}) + + # see gh-36004 + # compare time(zone) values only, skip their class: + # pyarrow always creates fixed offset timezones using pytz.FixedOffset() + # even if it was datetime.timezone() originally + # + # technically they are the same: + # they both implement datetime.tzinfo + # they both wrap datetime.timedelta() + # this use-case sets the resolution to 1 minute + check_round_trip(df, pa, check_dtype=False) + @td.skip_if_no("pyarrow", min_version="0.17") def test_filter_row_groups(self, pa): # https://github.com/pandas-dev/pandas/issues/26551 @@ -877,3 +912,12 @@ def test_empty_dataframe(self, fp): expected = df.copy() expected.index.name = "index" check_round_trip(df, fp, expected=expected) + + def test_timezone_aware_index(self, fp, timezone_aware_date_list): + idx = 5 * [timezone_aware_date_list] + + df = pd.DataFrame(index=idx, data={"index_as_col": idx}) + + expected = df.copy() + expected.index.name = "index" + check_round_trip(df, fp, expected=expected) diff --git a/pandas/tests/tslibs/test_timezones.py b/pandas/tests/tslibs/test_timezones.py index 81b41f567976d..e49f511fe3cc4 100644 --- a/pandas/tests/tslibs/test_timezones.py +++ b/pandas/tests/tslibs/test_timezones.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, timedelta, timezone import dateutil.tz import pytest @@ -118,3 +118,25 @@ def test_maybe_get_tz_invalid_types(): msg = "<class 'pandas._libs.tslibs.timestamps.Timestamp'>" with pytest.raises(TypeError, match=msg): timezones.maybe_get_tz(Timestamp.now("UTC")) + + +def test_maybe_get_tz_offset_only(): + # see gh-36004 + + # timezone.utc + tz = timezones.maybe_get_tz(timezone.utc) + assert tz == timezone(timedelta(hours=0, minutes=0)) + + # without UTC+- prefix + tz = timezones.maybe_get_tz("+01:15") + assert tz == timezone(timedelta(hours=1, minutes=15)) + + tz = timezones.maybe_get_tz("-01:15") + assert tz == timezone(-timedelta(hours=1, minutes=15)) + + # with UTC+- prefix + tz = timezones.maybe_get_tz("UTC+02:45") + assert tz == timezone(timedelta(hours=2, minutes=45)) + + tz = timezones.maybe_get_tz("UTC-02:45") + assert tz == timezone(-timedelta(hours=2, minutes=45))
- [x] closes #35997 - [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/36004
2020-08-31T08:30:23Z
2020-10-07T01:44:44Z
2020-10-07T01:44:44Z
2020-10-07T09:23:21Z
CLN: remove ABCTimedelta
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 2c28a7bbb02d0..35c4b73b47695 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -22,9 +22,9 @@ cnp.import_array() from pandas._libs cimport util from pandas._libs.tslibs.nattype cimport c_NaT as NaT -from pandas._libs.tslibs.base cimport ABCTimedelta from pandas._libs.tslibs.period cimport is_period_object from pandas._libs.tslibs.timestamps cimport _Timestamp +from pandas._libs.tslibs.timedeltas cimport _Timedelta from pandas._libs.hashtable cimport HashTable @@ -471,7 +471,7 @@ cdef class TimedeltaEngine(DatetimeEngine): return 'm8[ns]' cdef int64_t _unbox_scalar(self, scalar) except? -1: - if not (isinstance(scalar, ABCTimedelta) or scalar is NaT): + if not (isinstance(scalar, _Timedelta) or scalar is NaT): raise TypeError(scalar) return scalar.value diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index c0244b6e18a12..b5f5ef0a3f593 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -42,9 +42,9 @@ from pandas._libs.tslibs.util cimport ( is_timedelta64_object, ) -from pandas._libs.tslibs.base cimport ABCTimedelta from pandas._libs.tslibs.timezones cimport tz_compare from pandas._libs.tslibs.timestamps cimport _Timestamp +from pandas._libs.tslibs.timedeltas cimport _Timedelta _VALID_CLOSED = frozenset(['left', 'right', 'both', 'neither']) @@ -340,7 +340,7 @@ cdef class Interval(IntervalMixin): def _validate_endpoint(self, endpoint): # GH 23013 if not (is_integer_object(endpoint) or is_float_object(endpoint) or - isinstance(endpoint, (_Timestamp, ABCTimedelta))): + isinstance(endpoint, (_Timestamp, _Timedelta))): raise ValueError("Only numeric, Timestamp and Timedelta endpoints " "are allowed when constructing an Interval.") diff --git a/pandas/_libs/tslibs/base.pxd b/pandas/_libs/tslibs/base.pxd index d8c76542f3457..3bffff7aca43e 100644 --- a/pandas/_libs/tslibs/base.pxd +++ b/pandas/_libs/tslibs/base.pxd @@ -1,7 +1,4 @@ -from cpython.datetime cimport datetime, timedelta - -cdef class ABCTimedelta(timedelta): - pass +from cpython.datetime cimport datetime cdef class ABCTimestamp(datetime): diff --git a/pandas/_libs/tslibs/base.pyx b/pandas/_libs/tslibs/base.pyx index 6a5ee3f784334..1677a8b0be1ec 100644 --- a/pandas/_libs/tslibs/base.pyx +++ b/pandas/_libs/tslibs/base.pyx @@ -5,11 +5,7 @@ in order to allow for fast isinstance checks without circular dependency issues. This is analogous to core.dtypes.generic. """ -from cpython.datetime cimport datetime, timedelta - - -cdef class ABCTimedelta(timedelta): - pass +from cpython.datetime cimport datetime cdef class ABCTimestamp(datetime): diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd index 95ddf8840e65d..70a418d7803d1 100644 --- a/pandas/_libs/tslibs/timedeltas.pxd +++ b/pandas/_libs/tslibs/timedeltas.pxd @@ -1,6 +1,18 @@ +from cpython.datetime cimport timedelta from numpy cimport int64_t # Exposed for tslib, not intended for outside use. cpdef int64_t delta_to_nanoseconds(delta) except? -1 cdef convert_to_timedelta64(object ts, object unit) cdef bint is_any_td_scalar(object obj) + + +cdef class _Timedelta(timedelta): + cdef readonly: + int64_t value # nanoseconds + object freq # frequency reference + bint is_populated # are my components populated + int64_t _d, _h, _m, _s, _ms, _us, _ns + + cpdef timedelta to_pytimedelta(_Timedelta self) + cpdef bint _has_ns(self) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 10c1a56a2eb4e..f7bbf2c9e1c8b 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -21,7 +21,7 @@ from pandas._libs.tslibs.util cimport ( is_float_object, is_array ) -from pandas._libs.tslibs.base cimport ABCTimedelta, ABCTimestamp +from pandas._libs.tslibs.base cimport ABCTimestamp from pandas._libs.tslibs.conversion cimport cast_from_unit @@ -675,12 +675,12 @@ cdef _to_py_int_float(v): # timedeltas that we need to do object instantiation in python. This will # serve as a C extension type that shadows the Python class, where we do any # heavy lifting. -cdef class _Timedelta(ABCTimedelta): - cdef readonly: - int64_t value # nanoseconds - object freq # frequency reference - bint is_populated # are my components populated - int64_t _d, _h, _m, _s, _ms, _us, _ns +cdef class _Timedelta(timedelta): + # cdef readonly: + # int64_t value # nanoseconds + # object freq # frequency reference + # bint is_populated # are my components populated + # int64_t _d, _h, _m, _s, _ms, _us, _ns # higher than np.ndarray and np.matrix __array_priority__ = 100
Hoping we can eventually remove ABCTimestamp too, not sure.
https://api.github.com/repos/pandas-dev/pandas/pulls/34559
2020-06-03T20:41:27Z
2020-06-03T22:24:32Z
2020-06-03T22:24:32Z
2020-06-03T22:27:45Z
DOC: Add bcpandas to Ecosystem in docs
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index 62065f016e438..72e24e34bc5c1 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -320,6 +320,20 @@ provide a pandas-like and pandas-compatible toolkit for analytics on multi- dimensional arrays, rather than the tabular data for which pandas excels. +.. _ecosystem.io: + +IO +-- + +`BCPandas <https://github.com/yehoshuadimarsky/bcpandas>`__ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +BCPandas provides high performance writes from pandas to Microsoft SQL Server, +far exceeding the performance of the native ``df.to_sql`` method. Internally, it uses +Microsoft's BCP utility, but the complexity is fully abstracted away from the end user. +Rigorously tested, it is a complete replacement for ``df.to_sql``. + + .. _ecosystem.out-of-core: Out-of-core
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Hi, I wrote this utility which I use in production almost daily at my job, and it's been super helpful for me personally to fill a gap - slow writes from Pandas to MS SQL. Figured I'd suggest it in the pandas ecosystem if it could be useful to others. Wasn't sure where to put it, and didn't want to start a new section, so I put it in `Out-of-core`. It appeared to be sorted alphabetically, so I put it in that order.
https://api.github.com/repos/pandas-dev/pandas/pulls/34558
2020-06-03T18:46:57Z
2020-06-14T15:51:17Z
2020-06-14T15:51:17Z
2020-06-14T18:01:51Z
REF: simplify wrapping in apply_index
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 0deaf082dd1c7..77b60d0c22322 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -40,6 +40,7 @@ from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, get_days_in_month, dayofwe from pandas._libs.tslibs.conversion cimport ( convert_datetime_to_tsobject, localize_pydatetime, + normalize_i8_timestamps, ) from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT from pandas._libs.tslibs.np_datetime cimport ( @@ -79,21 +80,14 @@ cdef bint _is_normalized(datetime dt): def apply_index_wraps(func): # Note: normally we would use `@functools.wraps(func)`, but this does # not play nicely with cython class methods - def wrapper(self, other): - - is_index = not util.is_array(other._data) - - # operate on DatetimeArray - arr = other._data if is_index else other - - result = func(self, arr) + def wrapper(self, other) -> np.ndarray: + # other is a DatetimeArray - if is_index: - # Wrap DatetimeArray result back to DatetimeIndex - result = type(other)._simple_new(result, name=other.name) + result = func(self, other) + result = np.asarray(result) if self.normalize: - result = result.to_period('D').to_timestamp() + result = normalize_i8_timestamps(result.view("i8"), None) return result # do @functools.wraps(func) manually since it doesn't work on cdef funcs @@ -1889,7 +1883,7 @@ cdef class YearOffset(SingleConstructorOffset): shifted = shift_quarters( dtindex.asi8, self.n, self.month, self._day_opt, modby=12 ) - return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) + return shifted cdef class BYearEnd(YearOffset): @@ -2033,7 +2027,7 @@ cdef class QuarterOffset(SingleConstructorOffset): shifted = shift_quarters( dtindex.asi8, self.n, self.startingMonth, self._day_opt ) - return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) + return shifted cdef class BQuarterEnd(QuarterOffset): @@ -2139,7 +2133,7 @@ cdef class MonthOffset(SingleConstructorOffset): @apply_index_wraps def apply_index(self, dtindex): shifted = shift_months(dtindex.asi8, self.n, self._day_opt) - return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) + return shifted cpdef __setstate__(self, state): state.pop("_use_relativedelta", False) @@ -2503,8 +2497,6 @@ cdef class Week(SingleConstructorOffset): @apply_index_wraps def apply_index(self, dtindex): if self.weekday is None: - # integer addition on PeriodIndex is deprecated, - # so we use _time_shift directly td = timedelta(days=7 * self.n) td64 = np.timedelta64(td, "ns") return dtindex + td64 diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 7bbe60c4fdcd1..053aeb6d81be4 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -685,7 +685,9 @@ def _add_offset(self, offset): values = self.tz_localize(None) else: values = self - result = offset.apply_index(values).tz_localize(self.tz) + result = offset.apply_index(values) + result = DatetimeArray._simple_new(result) + result = result.tz_localize(self.tz) except NotImplementedError: warnings.warn( diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 86cc7ff753660..e3a89d9ed57a6 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -3524,7 +3524,7 @@ def test_offset_whole_year(self): with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex - result = SemiMonthEnd().apply_index(s) + result = SemiMonthEnd() + s exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) @@ -3672,7 +3672,7 @@ def test_apply_index(self, case): with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex - result = offset.apply_index(s) + result = offset + s exp = DatetimeIndex(cases.values()) tm.assert_index_equal(result, exp) @@ -3783,7 +3783,7 @@ def test_offset_whole_year(self): with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex - result = SemiMonthBegin().apply_index(s) + result = SemiMonthBegin() + s exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) @@ -3936,7 +3936,7 @@ def test_apply_index(self, case): with tm.assert_produces_warning(None): # GH#22535 check that we don't get a FutureWarning from adding # an integer array to PeriodIndex - result = offset.apply_index(s) + result = offset + s exp = DatetimeIndex(cases.values()) tm.assert_index_equal(result, exp) diff --git a/pandas/tests/tseries/offsets/test_yqm_offsets.py b/pandas/tests/tseries/offsets/test_yqm_offsets.py index 13cab9be46d37..9921355bdf2ee 100644 --- a/pandas/tests/tseries/offsets/test_yqm_offsets.py +++ b/pandas/tests/tseries/offsets/test_yqm_offsets.py @@ -65,8 +65,6 @@ def test_apply_index(cls, n): res = rng + offset assert res.freq is None # not retained - res_v2 = offset.apply_index(rng) - assert (res == res_v2).all() assert res[0] == rng[0] + offset assert res[-1] == rng[-1] + offset res2 = ser + offset
Make the caller (DatetimeArray._add_offset) responsible for wrapping, so we can move the liboffsets methods towards only needing the ndarrays.
https://api.github.com/repos/pandas-dev/pandas/pulls/34555
2020-06-03T17:49:42Z
2020-06-03T22:24:51Z
2020-06-03T22:24:51Z
2020-06-03T22:28:14Z
CLN: Update imports
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index f11f3ad974b37..7bbe60c4fdcd1 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -406,7 +406,7 @@ def _generate_range( index = cls._simple_new(values, freq=freq, dtype=tz_to_dtype(_tz)) if tz is not None and index.tz is None: - arr = conversion.tz_localize_to_utc( + arr = tzconversion.tz_localize_to_utc( index.asi8, tz, ambiguous=ambiguous, nonexistent=nonexistent ) @@ -967,7 +967,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise"): tz = timezones.maybe_get_tz(tz) # Convert to UTC - new_dates = conversion.tz_localize_to_utc( + new_dates = tzconversion.tz_localize_to_utc( self.asi8, tz, ambiguous=ambiguous, nonexistent=nonexistent ) new_dates = new_dates.view(DT64NS_DTYPE) @@ -1881,7 +1881,7 @@ def sequence_to_dt64ns( dayfirst : bool, default False yearfirst : bool, default False ambiguous : str, bool, or arraylike, default 'raise' - See pandas._libs.tslibs.conversion.tz_localize_to_utc. + See pandas._libs.tslibs.tzconversion.tz_localize_to_utc. Returns ------- @@ -1961,7 +1961,7 @@ def sequence_to_dt64ns( if tz is not None: # Convert tz-naive to UTC tz = timezones.maybe_get_tz(tz) - data = conversion.tz_localize_to_utc( + data = tzconversion.tz_localize_to_utc( data.view("i8"), tz, ambiguous=ambiguous ) data = data.view(DT64NS_DTYPE)
https://api.github.com/repos/pandas-dev/pandas/pulls/34554
2020-06-03T17:30:20Z
2020-06-03T18:06:30Z
2020-06-03T18:06:30Z
2020-06-03T18:11:35Z
DEPR: Deprecate tshift and integrate it to shift
diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index 5351c3ee6b624..648d93a45d210 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -516,7 +516,7 @@ The ``DatetimeIndex`` class contains many time series related optimizations: * A large range of dates for various offsets are pre-computed and cached under the hood in order to make generating subsequent date ranges very fast (just have to grab a slice). -* Fast shifting using the ``shift`` and ``tshift`` method on pandas objects. +* Fast shifting using the ``shift`` method on pandas objects. * Unioning of overlapping ``DatetimeIndex`` objects with the same frequency is very fast (important for fast data alignment). * Quick access to date fields via properties such as ``year``, ``month``, etc. @@ -1462,23 +1462,19 @@ the pandas objects. The ``shift`` method accepts an ``freq`` argument which can accept a ``DateOffset`` class or other ``timedelta``-like object or also an -:ref:`offset alias <timeseries.offset_aliases>`: +:ref:`offset alias <timeseries.offset_aliases>`. + +When ``freq`` is specified, ``shift`` method changes all the dates in the index +rather than changing the alignment of the data and the index: .. ipython:: python + ts.shift(5, freq='D') ts.shift(5, freq=pd.offsets.BDay()) ts.shift(5, freq='BM') -Rather than changing the alignment of the data and the index, ``DataFrame`` and -``Series`` objects also have a :meth:`~Series.tshift` convenience method that -changes all the dates in the index by a specified number of offsets: - -.. ipython:: python - - ts.tshift(5, freq='D') - -Note that with ``tshift``, the leading entry is no longer NaN because the data -is not being realigned. +Note that with when ``freq`` is specified, the leading entry is no longer NaN +because the data is not being realigned. Frequency conversion ~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5f8668f85c3b3..3f25baa6b7fb4 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -748,6 +748,7 @@ Deprecations - :meth:`DatetimeIndex.week` and `DatetimeIndex.weekofyear` are deprecated and will be removed in a future version, use :meth:`DatetimeIndex.isocalendar().week` instead (:issue:`33595`) - :meth:`DatetimeArray.week` and `DatetimeArray.weekofyear` are deprecated and will be removed in a future version, use :meth:`DatetimeArray.isocalendar().week` instead (:issue:`33595`) - :meth:`DateOffset.__call__` is deprecated and will be removed in a future version, use ``offset + other`` instead (:issue:`34171`) +- :meth:`DataFrame.tshift` and :meth:`Series.tshift` are deprecated and will be removed in a future version, use :meth:`DataFrame.shift` and :meth:`Series.shift` instead (:issue:`11631`) - Indexing an :class:`Index` object with a float key is deprecated, and will raise an ``IndexError`` in the future. You can manually convert to an integer key instead (:issue:`34191`). diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9dcdcaca2f689..7c3e975c889e1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -182,7 +182,7 @@ class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): ] _internal_names_set: Set[str] = set(_internal_names) _accessors: Set[str] = set() - _deprecations: FrozenSet[str] = frozenset(["get_values"]) + _deprecations: FrozenSet[str] = frozenset(["get_values", "tshift"]) _metadata: List[str] = [] _is_copy = None _mgr: BlockManager @@ -9162,7 +9162,9 @@ def shift( When `freq` is not passed, shift the index without realigning the data. If `freq` is passed (in this case, the index must be date or datetime, or it will raise a `NotImplementedError`), the index will be - increased using the periods and the `freq`. + increased using the periods and the `freq`. `freq` can be inferred + when specified as "infer" as long as either freq or inferred_freq + attribute is set in the index. Parameters ---------- @@ -9173,6 +9175,9 @@ def shift( If `freq` is specified then the index values are shifted but the data is not realigned. That is, use `freq` if you would like to extend the index when shifting and preserve the original data. + If `freq` is specified as "infer" then it will be inferred from + the freq or inferred_freq attributes of the index. If neither of + those attributes exist, a ValueError is thrown axis : {{0 or 'index', 1 or 'columns', None}}, default None Shift direction. fill_value : object, optional @@ -9182,7 +9187,7 @@ def shift( For datetime, timedelta, or period data, etc. :attr:`NaT` is used. For extension dtypes, ``self.dtype.na_value`` is used. - .. versionchanged:: 0.24.0 + .. versionchanged:: 1.1.0 Returns ------- @@ -9199,46 +9204,99 @@ def shift( Examples -------- - >>> df = pd.DataFrame({{'Col1': [10, 20, 15, 30, 45], - ... 'Col2': [13, 23, 18, 33, 48], - ... 'Col3': [17, 27, 22, 37, 52]}}) + >>> df = pd.DataFrame({{"Col1": [10, 20, 15, 30, 45], + ... "Col2": [13, 23, 18, 33, 48], + ... "Col3": [17, 27, 22, 37, 52]}}, + ... index=pd.date_range("2020-01-01", "2020-01-05")) + >>> df + Col1 Col2 Col3 + 2020-01-01 10 13 17 + 2020-01-02 20 23 27 + 2020-01-03 15 18 22 + 2020-01-04 30 33 37 + 2020-01-05 45 48 52 >>> df.shift(periods=3) - Col1 Col2 Col3 - 0 NaN NaN NaN - 1 NaN NaN NaN - 2 NaN NaN NaN - 3 10.0 13.0 17.0 - 4 20.0 23.0 27.0 - - >>> df.shift(periods=1, axis='columns') - Col1 Col2 Col3 - 0 NaN 10.0 13.0 - 1 NaN 20.0 23.0 - 2 NaN 15.0 18.0 - 3 NaN 30.0 33.0 - 4 NaN 45.0 48.0 + Col1 Col2 Col3 + 2020-01-01 NaN NaN NaN + 2020-01-02 NaN NaN NaN + 2020-01-03 NaN NaN NaN + 2020-01-04 10.0 13.0 17.0 + 2020-01-05 20.0 23.0 27.0 + + >>> df.shift(periods=1, axis="columns") + Col1 Col2 Col3 + 2020-01-01 NaN 10.0 13.0 + 2020-01-02 NaN 20.0 23.0 + 2020-01-03 NaN 15.0 18.0 + 2020-01-04 NaN 30.0 33.0 + 2020-01-05 NaN 45.0 48.0 >>> df.shift(periods=3, fill_value=0) - Col1 Col2 Col3 - 0 0 0 0 - 1 0 0 0 - 2 0 0 0 - 3 10 13 17 - 4 20 23 27 + Col1 Col2 Col3 + 2020-01-01 0 0 0 + 2020-01-02 0 0 0 + 2020-01-03 0 0 0 + 2020-01-04 10 13 17 + 2020-01-05 20 23 27 + + >>> df.shift(periods=3, freq="D") + Col1 Col2 Col3 + 2020-01-04 10 13 17 + 2020-01-05 20 23 27 + 2020-01-06 15 18 22 + 2020-01-07 30 33 37 + 2020-01-08 45 48 52 + + >>> df.shift(periods=3, freq="infer") + Col1 Col2 Col3 + 2020-01-04 10 13 17 + 2020-01-05 20 23 27 + 2020-01-06 15 18 22 + 2020-01-07 30 33 37 + 2020-01-08 45 48 52 """ if periods == 0: return self.copy() - block_axis = self._get_block_manager_axis(axis) if freq is None: + # when freq is None, data is shifted, index is not + block_axis = self._get_block_manager_axis(axis) new_data = self._mgr.shift( periods=periods, axis=block_axis, fill_value=fill_value ) + return self._constructor(new_data).__finalize__(self, method="shift") + + # when freq is given, index is shifted, data is not + index = self._get_axis(axis) + + if freq == "infer": + freq = getattr(index, "freq", None) + + if freq is None: + freq = getattr(index, "inferred_freq", None) + + if freq is None: + msg = "Freq was not set in the index hence cannot be inferred" + raise ValueError(msg) + + elif isinstance(freq, str): + freq = to_offset(freq) + + if isinstance(index, PeriodIndex): + orig_freq = to_offset(index.freq) + if freq != orig_freq: + assert orig_freq is not None # for mypy + raise ValueError( + f"Given freq {freq.rule_code} does not match " + f"PeriodIndex freq {orig_freq.rule_code}" + ) + new_ax = index.shift(periods) else: - return self.tshift(periods, freq) + new_ax = index.shift(periods, freq) - return self._constructor(new_data).__finalize__(self, method="shift") + result = self.set_axis(new_ax, axis) + return result.__finalize__(self, method="shift") def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: """ @@ -9283,6 +9341,9 @@ def tshift( """ Shift the time index, using the index's frequency if available. + .. deprecated:: 1.1.0 + Use `shift` instead. + Parameters ---------- periods : int @@ -9303,39 +9364,19 @@ def tshift( attributes of the index. If neither of those attributes exist, a ValueError is thrown """ - index = self._get_axis(axis) - if freq is None: - freq = getattr(index, "freq", None) - - if freq is None: - freq = getattr(index, "inferred_freq", None) + warnings.warn( + ( + "tshift is deprecated and will be removed in a future version. " + "Please use shift instead." + ), + FutureWarning, + stacklevel=2, + ) if freq is None: - msg = "Freq was not given and was not set in the index" - raise ValueError(msg) - - if periods == 0: - return self - - if isinstance(freq, str): - freq = to_offset(freq) - - axis = self._get_axis_number(axis) - if isinstance(index, PeriodIndex): - orig_freq = to_offset(index.freq) - if freq != orig_freq: - assert orig_freq is not None # for mypy - raise ValueError( - f"Given freq {freq.rule_code} does not match " - f"PeriodIndex freq {orig_freq.rule_code}" - ) - new_ax = index.shift(periods) - else: - new_ax = index.shift(periods, freq) + freq = "infer" - result = self.copy() - result.set_axis(new_ax, axis, inplace=True) - return result.__finalize__(self, method="tshift") + return self.shift(periods, freq, axis) def truncate( self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 95f9fd9d7caf3..9ec029a6c4304 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -145,7 +145,10 @@ def test_shift_duplicate_columns(self): tm.assert_frame_equal(shifted[0], shifted[1]) tm.assert_frame_equal(shifted[0], shifted[2]) + @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_frame): + # TODO: remove this test when tshift deprecation is enforced + # PeriodIndex ps = tm.makePeriodFrame() shifted = ps.tshift(1) @@ -159,7 +162,8 @@ def test_tshift(self, datetime_frame): shifted3 = ps.tshift(freq=offsets.BDay()) tm.assert_frame_equal(shifted, shifted3) - with pytest.raises(ValueError, match="does not match"): + msg = "Given freq M does not match PeriodIndex freq B" + with pytest.raises(ValueError, match=msg): ps.tshift(freq="M") # DatetimeIndex @@ -186,10 +190,61 @@ def test_tshift(self, datetime_frame): tm.assert_frame_equal(unshifted, inferred_ts) no_freq = datetime_frame.iloc[[0, 5, 7], :] - msg = "Freq was not given and was not set in the index" + msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.tshift() + def test_tshift_deprecated(self, datetime_frame): + # GH#11631 + with tm.assert_produces_warning(FutureWarning): + datetime_frame.tshift() + + def test_period_index_frame_shift_with_freq(self): + ps = tm.makePeriodFrame() + + shifted = ps.shift(1, freq="infer") + unshifted = shifted.shift(-1, freq="infer") + tm.assert_frame_equal(unshifted, ps) + + shifted2 = ps.shift(freq="B") + tm.assert_frame_equal(shifted, shifted2) + + shifted3 = ps.shift(freq=offsets.BDay()) + tm.assert_frame_equal(shifted, shifted3) + + def test_datetime_frame_shift_with_freq(self, datetime_frame): + shifted = datetime_frame.shift(1, freq="infer") + unshifted = shifted.shift(-1, freq="infer") + tm.assert_frame_equal(datetime_frame, unshifted) + + shifted2 = datetime_frame.shift(freq=datetime_frame.index.freq) + tm.assert_frame_equal(shifted, shifted2) + + inferred_ts = DataFrame( + datetime_frame.values, + Index(np.asarray(datetime_frame.index)), + columns=datetime_frame.columns, + ) + shifted = inferred_ts.shift(1, freq="infer") + expected = datetime_frame.shift(1, freq="infer") + expected.index = expected.index._with_freq(None) + tm.assert_frame_equal(shifted, expected) + + unshifted = shifted.shift(-1, freq="infer") + tm.assert_frame_equal(unshifted, inferred_ts) + + def test_period_index_frame_shift_with_freq_error(self): + ps = tm.makePeriodFrame() + msg = "Given freq M does not match PeriodIndex freq B" + with pytest.raises(ValueError, match=msg): + ps.shift(freq="M") + + def test_datetime_frame_shift_with_freq_error(self, datetime_frame): + no_freq = datetime_frame.iloc[[0, 5, 7], :] + msg = "Freq was not set in the index hence cannot be inferred" + with pytest.raises(ValueError, match=msg): + no_freq.shift(freq="infer") + def test_shift_dt64values_int_fill_deprecated(self): # GH#31971 ser = pd.Series([pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")]) diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index d307eef8beb62..a152bc203721f 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -438,11 +438,21 @@ (pd.DataFrame, frame_data, operator.methodcaller("mask", np.array([[True]]))), (pd.Series, ([1, 2],), operator.methodcaller("slice_shift")), (pd.DataFrame, frame_data, operator.methodcaller("slice_shift")), - (pd.Series, (1, pd.date_range("2000", periods=4)), operator.methodcaller("tshift")), - ( - pd.DataFrame, - ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)), - operator.methodcaller("tshift"), + pytest.param( + ( + pd.Series, + (1, pd.date_range("2000", periods=4)), + operator.methodcaller("tshift"), + ), + marks=pytest.mark.filterwarnings("ignore::FutureWarning"), + ), + pytest.param( + ( + pd.DataFrame, + ({"A": [1, 1, 1, 1]}, pd.date_range("2000", periods=4)), + operator.methodcaller("tshift"), + ), + marks=pytest.mark.filterwarnings("ignore::FutureWarning"), ), (pd.Series, ([1, 2],), operator.methodcaller("truncate", before=0)), (pd.DataFrame, frame_data, operator.methodcaller("truncate", before=0)), diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 80f34bb91cdfd..9cb7e4acfbf2a 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1979,6 +1979,7 @@ def test_bool_aggs_dup_column_labels(bool_agg_func): @pytest.mark.parametrize( "idx", [pd.Index(["a", "a"]), pd.MultiIndex.from_tuples((("a", "a"), ("a", "a")))] ) +@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_dup_labels_output_shape(groupby_func, idx): if groupby_func in {"size", "ngroup", "cumcount"}: pytest.skip("Not applicable") diff --git a/pandas/tests/groupby/test_groupby_subclass.py b/pandas/tests/groupby/test_groupby_subclass.py index 6adae19005c3a..7271911c5f80f 100644 --- a/pandas/tests/groupby/test_groupby_subclass.py +++ b/pandas/tests/groupby/test_groupby_subclass.py @@ -14,6 +14,7 @@ tm.SubclassedSeries(np.arange(0, 10), name="A"), ], ) +@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_groupby_preserves_subclass(obj, groupby_func): # GH28330 -- preserve subclass through groupby operations diff --git a/pandas/tests/groupby/test_whitelist.py b/pandas/tests/groupby/test_whitelist.py index 1598cc24ba6fb..9b595328d9230 100644 --- a/pandas/tests/groupby/test_whitelist.py +++ b/pandas/tests/groupby/test_whitelist.py @@ -340,6 +340,7 @@ def test_groupby_function_rename(mframe): assert f.__name__ == name +@pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_groupby_selection_with_methods(df): # some methods which require DatetimeIndex rng = date_range("2014", periods=len(df)) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 43d2bf80505db..e7637a598403f 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1067,7 +1067,7 @@ def test_resample_anchored_intraday(simple_date_range_series): tm.assert_frame_equal(result, expected) result = df.resample("M", closed="left").mean() - exp = df.tshift(1, freq="D").resample("M", kind="period").mean() + exp = df.shift(1, freq="D").resample("M", kind="period").mean() exp = exp.to_timestamp(how="end") exp.index = exp.index + Timedelta(1, "ns") - Timedelta(1, "D") @@ -1086,7 +1086,7 @@ def test_resample_anchored_intraday(simple_date_range_series): tm.assert_frame_equal(result, expected) result = df.resample("Q", closed="left").mean() - expected = df.tshift(1, freq="D").resample("Q", kind="period", closed="left").mean() + expected = df.shift(1, freq="D").resample("Q", kind="period", closed="left").mean() expected = expected.to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index._data.freq = "Q" diff --git a/pandas/tests/series/methods/test_shift.py b/pandas/tests/series/methods/test_shift.py index f981e98100d31..6257eecf4fc08 100644 --- a/pandas/tests/series/methods/test_shift.py +++ b/pandas/tests/series/methods/test_shift.py @@ -181,7 +181,10 @@ def test_shift_dst(self): tm.assert_series_equal(res, exp) assert res.dtype == "datetime64[ns, US/Eastern]" + @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_tshift(self, datetime_series): + # TODO: remove this test when tshift deprecation is enforced + # PeriodIndex ps = tm.makePeriodSeries() shifted = ps.tshift(1) @@ -220,10 +223,59 @@ def test_tshift(self, datetime_series): tm.assert_series_equal(unshifted, inferred_ts) no_freq = datetime_series[[0, 5, 7]] - msg = "Freq was not given and was not set in the index" + msg = "Freq was not set in the index hence cannot be inferred" with pytest.raises(ValueError, match=msg): no_freq.tshift() + def test_tshift_deprecated(self, datetime_series): + # GH#11631 + with tm.assert_produces_warning(FutureWarning): + datetime_series.tshift() + + def test_period_index_series_shift_with_freq(self): + ps = tm.makePeriodSeries() + + shifted = ps.shift(1, freq="infer") + unshifted = shifted.shift(-1, freq="infer") + tm.assert_series_equal(unshifted, ps) + + shifted2 = ps.shift(freq="B") + tm.assert_series_equal(shifted, shifted2) + + shifted3 = ps.shift(freq=BDay()) + tm.assert_series_equal(shifted, shifted3) + + def test_datetime_series_shift_with_freq(self, datetime_series): + shifted = datetime_series.shift(1, freq="infer") + unshifted = shifted.shift(-1, freq="infer") + tm.assert_series_equal(datetime_series, unshifted) + + shifted2 = datetime_series.shift(freq=datetime_series.index.freq) + tm.assert_series_equal(shifted, shifted2) + + inferred_ts = Series( + datetime_series.values, Index(np.asarray(datetime_series.index)), name="ts" + ) + shifted = inferred_ts.shift(1, freq="infer") + expected = datetime_series.shift(1, freq="infer") + expected.index = expected.index._with_freq(None) + tm.assert_series_equal(shifted, expected) + + unshifted = shifted.shift(-1, freq="infer") + tm.assert_series_equal(unshifted, inferred_ts) + + def test_period_index_series_shift_with_freq_error(self): + ps = tm.makePeriodSeries() + msg = "Given freq M does not match PeriodIndex freq B" + with pytest.raises(ValueError, match=msg): + ps.shift(freq="M") + + def test_datetime_series_shift_with_freq_error(self, datetime_series): + no_freq = datetime_series[[0, 5, 7]] + msg = "Freq was not set in the index hence cannot be inferred" + with pytest.raises(ValueError, match=msg): + no_freq.shift(freq="infer") + def test_shift_int(self, datetime_series): ts = datetime_series.astype(int) shifted = ts.shift(1)
- [x] closes #11631 - xref #34452 - [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/34545
2020-06-03T10:41:20Z
2020-06-15T13:20:34Z
2020-06-15T13:20:34Z
2021-03-20T02:35:51Z
REF: avoid use of to_perioddelta
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 33b478c4d8da4..0deaf082dd1c7 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -36,7 +36,7 @@ from pandas._libs.tslibs.base cimport ABCTimestamp from pandas._libs.tslibs.ccalendar import ( MONTH_ALIASES, MONTH_TO_CAL_NUM, weekday_to_int, int_to_weekday, ) -from pandas._libs.tslibs.ccalendar cimport get_days_in_month, dayofweek +from pandas._libs.tslibs.ccalendar cimport DAY_NANOS, get_days_in_month, dayofweek from pandas._libs.tslibs.conversion cimport ( convert_datetime_to_tsobject, localize_pydatetime, @@ -1067,11 +1067,7 @@ cdef class RelativeDeltaOffset(BaseOffset): weeks = kwds.get("weeks", 0) * self.n if weeks: - # integer addition on PeriodIndex is deprecated, - # so we directly use _time_shift instead - asper = index.to_period("W") - shifted = asper._time_shift(weeks) - index = shifted.to_timestamp() + index.to_perioddelta("W") + index = index + timedelta(days=7 * weeks) timedelta_kwds = { k: v @@ -1383,7 +1379,9 @@ cdef class BusinessDay(BusinessMixin): @apply_index_wraps def apply_index(self, dtindex): - time = dtindex.to_perioddelta("D") + i8other = dtindex.asi8 + time = (i8other % DAY_NANOS).view("timedelta64[ns]") + # to_period rolls forward to next BDay; track and # reduce n where it does when rolling forward asper = dtindex.to_period("B") @@ -2276,6 +2274,7 @@ cdef class SemiMonthOffset(SingleConstructorOffset): from pandas import Timedelta dti = dtindex + i8other = dtindex.asi8 days_from_start = dtindex.to_perioddelta("M").asi8 delta = Timedelta(days=self.day_of_month - 1).value @@ -2289,7 +2288,7 @@ cdef class SemiMonthOffset(SingleConstructorOffset): roll = self._get_roll(dtindex, before_day_of_month, after_day_of_month) # isolate the time since it will be striped away one the next line - time = dtindex.to_perioddelta("D") + time = (i8other % DAY_NANOS).view("timedelta64[ns]") # apply the correct number of months @@ -2506,10 +2505,9 @@ cdef class Week(SingleConstructorOffset): if self.weekday is None: # integer addition on PeriodIndex is deprecated, # so we use _time_shift directly - asper = dtindex.to_period("W") - - shifted = asper._time_shift(self.n) - return shifted.to_timestamp() + dtindex.to_perioddelta("W") + td = timedelta(days=7 * self.n) + td64 = np.timedelta64(td, "ns") + return dtindex + td64 else: return self._end_apply_index(dtindex) @@ -2529,7 +2527,8 @@ cdef class Week(SingleConstructorOffset): from pandas import Timedelta from .frequencies import get_freq_code # TODO: avoid circular import - off = dtindex.to_perioddelta("D") + i8other = dtindex.asi8 + off = (i8other % DAY_NANOS).view("timedelta64") base, mult = get_freq_code(self.freqstr) base_period = dtindex.to_period(base)
tslibs is nominally self-contained, but several offsets methods still rely on DatetimeArray/PeriodArray behavior. This is the first of several steps whittling that away.
https://api.github.com/repos/pandas-dev/pandas/pulls/34539
2020-06-02T22:33:17Z
2020-06-03T18:03:30Z
2020-06-03T18:03:30Z
2021-11-20T23:22:30Z
REF: add to_offset to tslibs namespace
diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index 965adc82df676..25e2d8ba477e0 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -14,12 +14,14 @@ "ints_to_pytimedelta", "Timestamp", "tz_convert_single", + "to_offset", ] from .conversion import localize_pydatetime from .nattype import NaT, NaTType, iNaT, is_null_datetimelike, nat_strings from .np_datetime import OutOfBoundsDatetime +from .offsets import to_offset from .period import IncompatibleFrequency, Period from .resolution import Resolution from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index da8e9b4bfdd4e..e2ecb6c343b7a 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -14,6 +14,7 @@ Timestamp, delta_to_nanoseconds, iNaT, + to_offset, ) from pandas._libs.tslibs.timestamps import ( RoundTo, @@ -427,7 +428,7 @@ def _with_freq(self, freq): else: # As an internal method, we can ensure this assertion always holds assert freq == "infer" - freq = frequencies.to_offset(self.inferred_freq) + freq = to_offset(self.inferred_freq) arr = self.view() arr._freq = freq @@ -1081,7 +1082,7 @@ def freq(self): @freq.setter def freq(self, value): if value is not None: - value = frequencies.to_offset(value) + value = to_offset(value) self._validate_frequency(self, value) self._freq = value @@ -1367,7 +1368,7 @@ def _time_shift(self, periods, freq=None): """ if freq is not None and freq != self.freq: if isinstance(freq, str): - freq = frequencies.to_offset(freq) + freq = to_offset(freq) offset = periods * freq result = self + offset return result @@ -1779,7 +1780,7 @@ def maybe_infer_freq(freq): if not isinstance(freq, DateOffset): # if a passed freq is None, don't infer automatically if freq != "infer": - freq = frequencies.to_offset(freq) + freq = to_offset(freq) else: freq_infer = True freq = None diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index f11f3ad974b37..8e4ae339ae53e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -15,6 +15,7 @@ iNaT, resolution as libresolution, timezones, + to_offset, tzconversion, ) from pandas.errors import PerformanceWarning @@ -46,7 +47,7 @@ from pandas.core.arrays._ranges import generate_regular_range import pandas.core.common as com -from pandas.tseries.frequencies import get_period_alias, to_offset +from pandas.tseries.frequencies import get_period_alias from pandas.tseries.offsets import BDay, Day, Tick _midnight = time(0, 0) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 3d4b42de01810..1b8a0b2780a7d 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -7,9 +7,12 @@ from pandas._libs.tslibs import ( NaT, NaTType, + Timedelta, + delta_to_nanoseconds, frequencies as libfrequencies, iNaT, period as libperiod, + to_offset, ) from pandas._libs.tslibs.fields import isleapyear_arr from pandas._libs.tslibs.offsets import Tick, delta_to_tick @@ -20,7 +23,6 @@ get_period_field_arr, period_asfreq_arr, ) -from pandas._libs.tslibs.timedeltas import Timedelta, delta_to_nanoseconds from pandas._typing import AnyArrayLike from pandas.util._decorators import cache_readonly @@ -45,7 +47,6 @@ from pandas.core.arrays import datetimelike as dtl import pandas.core.common as com -from pandas.tseries import frequencies from pandas.tseries.offsets import DateOffset @@ -902,7 +903,7 @@ def validate_dtype_freq(dtype, freq): IncompatibleFrequency : mismatch between dtype and freq """ if freq is not None: - freq = frequencies.to_offset(freq) + freq = to_offset(freq) if dtype is not None: dtype = pandas_dtype(dtype) diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 4de105e8be364..f439f07790274 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -4,7 +4,7 @@ import numpy as np from pandas._libs import lib, tslibs -from pandas._libs.tslibs import NaT, Period, Timedelta, Timestamp, iNaT +from pandas._libs.tslibs import NaT, Period, Timedelta, Timestamp, iNaT, to_offset from pandas._libs.tslibs.conversion import precision_from_unit from pandas._libs.tslibs.fields import get_timedelta_field from pandas._libs.tslibs.timedeltas import array_to_timedelta64, parse_timedelta_unit @@ -35,7 +35,6 @@ from pandas.core.construction import extract_array from pandas.core.ops.common import unpack_zerodim_and_defer -from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import Tick diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index ff35876ab2e73..84284c581c9e5 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -20,7 +20,7 @@ import pytz from pandas._libs.interval import Interval -from pandas._libs.tslibs import NaT, Period, Timestamp, timezones +from pandas._libs.tslibs import NaT, Period, Timestamp, timezones, to_offset from pandas._libs.tslibs.offsets import BaseOffset from pandas._typing import DtypeObj, Ordered @@ -925,7 +925,6 @@ def _parse_dtype_strict(cls, freq): m = cls._match.search(freq) if m is not None: freq = m.group("freq") - from pandas.tseries.frequencies import to_offset freq = to_offset(freq) if freq is not None: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0260f30b9e7e2..e5f5cb232fdd1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -30,7 +30,8 @@ from pandas._config import config -from pandas._libs import Timestamp, lib +from pandas._libs import lib +from pandas._libs.tslibs import Timestamp, to_offset from pandas._typing import ( Axis, FilePathOrBuffer, @@ -106,7 +107,6 @@ from pandas.io.formats import format as fmt from pandas.io.formats.format import DataFrameFormatter, format_percentiles from pandas.io.formats.printing import pprint_thing -from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import Tick if TYPE_CHECKING: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 4677faa6b7d24..68c55426294ef 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -6,7 +6,7 @@ import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib -from pandas._libs.tslibs import Resolution, fields, parsing, timezones +from pandas._libs.tslibs import Resolution, fields, parsing, timezones, to_offset from pandas._libs.tslibs.frequencies import get_freq_group from pandas._libs.tslibs.offsets import prefix_mapping from pandas._typing import DtypeObj, Label @@ -30,8 +30,6 @@ from pandas.core.indexes.extension import inherit_names from pandas.core.tools.times import to_time -from pandas.tseries.frequencies import to_offset - def _new_DatetimeIndex(cls, d): """ diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 7d7572973707c..1a59e066879cc 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -7,8 +7,9 @@ from pandas._config import get_option -from pandas._libs import Timedelta, Timestamp, lib +from pandas._libs import lib from pandas._libs.interval import Interval, IntervalMixin, IntervalTree +from pandas._libs.tslibs import Timedelta, Timestamp, to_offset from pandas._typing import AnyArrayLike, Label from pandas.util._decorators import Appender, Substitution, cache_readonly from pandas.util._exceptions import rewrite_exception @@ -55,7 +56,6 @@ from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range from pandas.core.ops import get_op_result_name -from pandas.tseries.frequencies import to_offset from pandas.tseries.offsets import DateOffset _VALID_CLOSED = {"left", "right", "both", "neither"} diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index 184fae4b97416..ce3ff17814a25 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -1,6 +1,7 @@ """ implement the TimedeltaIndex """ -from pandas._libs import Timedelta, index as libindex, lib +from pandas._libs import index as libindex, lib +from pandas._libs.tslibs import Timedelta, to_offset from pandas._typing import DtypeObj, Label from pandas.util._decorators import doc @@ -24,8 +25,6 @@ ) from pandas.core.indexes.extension import inherit_names -from pandas.tseries.frequencies import to_offset - @inherit_names( ["__neg__", "__pos__", "__abs__", "total_seconds", "round", "floor", "ceil"] diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 5df80645c2b5d..32e947dc414d2 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -6,8 +6,14 @@ import numpy as np from pandas._libs import lib -from pandas._libs.tslibs import NaT, Period, Timedelta, Timestamp -from pandas._libs.tslibs.period import IncompatibleFrequency +from pandas._libs.tslibs import ( + IncompatibleFrequency, + NaT, + Period, + Timedelta, + Timestamp, + to_offset, +) from pandas._typing import TimedeltaConvertibleTypes, TimestampConvertibleTypes from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError @@ -28,7 +34,7 @@ from pandas.core.indexes.period import PeriodIndex, period_range from pandas.core.indexes.timedeltas import TimedeltaIndex, timedelta_range -from pandas.tseries.frequencies import is_subperiod, is_superperiod, to_offset +from pandas.tseries.frequencies import is_subperiod, is_superperiod from pandas.tseries.offsets import DateOffset, Day, Nano, Tick _shared_docs_kwargs: Dict[str, str] = dict() diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b06128052fa8f..92be2d056cfcb 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -10,6 +10,7 @@ import numpy as np +from pandas._libs.tslibs import to_offset import pandas._libs.window.aggregations as window_aggregations from pandas._typing import Axis, FrameOrSeries, Scalar from pandas.compat._optional import import_optional_dependency @@ -1977,8 +1978,6 @@ def _validate_freq(self): """ Validate & return window frequency. """ - from pandas.tseries.frequencies import to_offset - try: return to_offset(self.window) except (TypeError, ValueError) as err: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 631760c547985..d5a390dc34d39 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -5,8 +5,8 @@ import numpy as np +from pandas._libs.tslibs import Period, to_offset from pandas._libs.tslibs.frequencies import FreqGroup, base_and_stride, get_freq_code -from pandas._libs.tslibs.period import Period from pandas.core.dtypes.generic import ( ABCDatetimeIndex, @@ -20,12 +20,7 @@ TimeSeries_DateLocator, TimeSeries_TimedeltaFormatter, ) -from pandas.tseries.frequencies import ( - get_period_alias, - is_subperiod, - is_superperiod, - to_offset, -) +from pandas.tseries.frequencies import get_period_alias, is_subperiod, is_superperiod from pandas.tseries.offsets import DateOffset if TYPE_CHECKING: diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index d206622521816..ccd03e841a40d 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -6,17 +6,15 @@ import numpy as np import pytest -from pandas._libs.tslibs.period import IncompatibleFrequency +from pandas._libs.tslibs import IncompatibleFrequency, Period, Timestamp, to_offset from pandas.errors import PerformanceWarning import pandas as pd -from pandas import Period, PeriodIndex, Series, TimedeltaIndex, Timestamp, period_range +from pandas import PeriodIndex, Series, TimedeltaIndex, period_range import pandas._testing as tm from pandas.core import ops from pandas.core.arrays import TimedeltaArray -from pandas.tseries.frequencies import to_offset - from .common import assert_invalid_comparison # ------------------------------------------------------------------ diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index e5d1277aed9cd..23dedf6f86a09 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -6,14 +6,12 @@ import numpy as np import pytest -from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime +from pandas._libs.tslibs import OutOfBoundsDatetime, to_offset import pandas as pd from pandas import DatetimeIndex, Timestamp, date_range import pandas._testing as tm -from pandas.tseries.frequencies import to_offset - class TestDatetimeIndexOps: def test_dti_time(self): diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index eb9932f9a3a97..954301b979074 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -3,14 +3,16 @@ import numpy as np import pytest -from pandas.errors import OutOfBoundsDatetime +from pandas._libs.tslibs import ( + OutOfBoundsDatetime, + Timedelta, + Timestamp, + offsets, + to_offset, +) -from pandas import Timedelta, Timestamp import pandas._testing as tm -from pandas.tseries import offsets -from pandas.tseries.frequencies import to_offset - class TestTimestampArithmetic: def test_overflow_offset(self): diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index e657559b55d5a..388ff4ea039be 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -5,15 +5,12 @@ import pytz from pytz import utc -from pandas._libs.tslibs import conversion +from pandas._libs.tslibs import NaT, Timestamp, conversion, to_offset from pandas._libs.tslibs.frequencies import INVALID_FREQ_ERR_MSG import pandas.util._test_decorators as td -from pandas import NaT, Timestamp import pandas._testing as tm -from pandas.tseries.frequencies import to_offset - class TestTimestampUnaryOps: diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py index f82d225f0538c..d4eb31168b20e 100644 --- a/pandas/tests/tseries/frequencies/test_freq_code.py +++ b/pandas/tests/tseries/frequencies/test_freq_code.py @@ -1,5 +1,6 @@ import pytest +from pandas._libs.tslibs import to_offset from pandas._libs.tslibs.frequencies import ( FreqGroup, _attrname_to_abbrevs, @@ -10,7 +11,6 @@ ) from pandas._libs.tslibs.resolution import Resolution as _reso -from pandas.tseries.frequencies import to_offset import pandas.tseries.offsets as offsets diff --git a/pandas/tests/tseries/frequencies/test_to_offset.py b/pandas/tests/tseries/frequencies/test_to_offset.py index d3510eaa5c749..04be0e445a3b2 100644 --- a/pandas/tests/tseries/frequencies/test_to_offset.py +++ b/pandas/tests/tseries/frequencies/test_to_offset.py @@ -2,16 +2,13 @@ import pytest -from pandas import Timedelta - -import pandas.tseries.frequencies as frequencies -import pandas.tseries.offsets as offsets +from pandas._libs.tslibs import Timedelta, offsets, to_offset @pytest.mark.parametrize( "freq_input,expected", [ - (frequencies.to_offset("10us"), offsets.Micro(10)), + (to_offset("10us"), offsets.Micro(10)), (offsets.Hour(), offsets.Hour()), ((5, "T"), offsets.Minute(5)), ("2h30min", offsets.Minute(150)), @@ -33,7 +30,7 @@ ], ) def test_to_offset(freq_input, expected): - result = frequencies.to_offset(freq_input) + result = to_offset(freq_input) assert result == expected @@ -41,7 +38,7 @@ def test_to_offset(freq_input, expected): "freqstr,expected", [("-1S", -1), ("-2SM", -2), ("-1SMS", -1), ("-5min10s", -310)] ) def test_to_offset_negative(freqstr, expected): - result = frequencies.to_offset(freqstr) + result = to_offset(freqstr) assert result.n == expected @@ -88,12 +85,12 @@ def test_to_offset_invalid(freqstr): # inputs contain regex special characters. msg = re.escape(f"Invalid frequency: {freqstr}") with pytest.raises(ValueError, match=msg): - frequencies.to_offset(freqstr) + to_offset(freqstr) def test_to_offset_no_evaluate(): with pytest.raises(ValueError, match="Could not evaluate"): - frequencies.to_offset(("", "")) + to_offset(("", "")) @pytest.mark.parametrize( @@ -108,7 +105,7 @@ def test_to_offset_no_evaluate(): ], ) def test_to_offset_whitespace(freqstr, expected): - result = frequencies.to_offset(freqstr) + result = to_offset(freqstr) assert result == expected @@ -116,13 +113,13 @@ def test_to_offset_whitespace(freqstr, expected): "freqstr,expected", [("00H 00T 01S", 1), ("-00H 03T 14S", -194)] ) def test_to_offset_leading_zero(freqstr, expected): - result = frequencies.to_offset(freqstr) + result = to_offset(freqstr) assert result.n == expected @pytest.mark.parametrize("freqstr,expected", [("+1d", 1), ("+2h30min", 150)]) def test_to_offset_leading_plus(freqstr, expected): - result = frequencies.to_offset(freqstr) + result = to_offset(freqstr) assert result.n == expected @@ -135,7 +132,7 @@ def test_to_offset_leading_plus(freqstr, expected): (dict(hours=1, minutes=-10), offsets.Minute(50)), (dict(weeks=1), offsets.Day(7)), (dict(hours=1), offsets.Hour(1)), - (dict(hours=1), frequencies.to_offset("60min")), + (dict(hours=1), to_offset("60min")), (dict(microseconds=1), offsets.Micro(1)), (dict(microseconds=0), offsets.Nano(0)), ], @@ -143,7 +140,7 @@ def test_to_offset_leading_plus(freqstr, expected): def test_to_offset_pd_timedelta(kwargs, expected): # see gh-9064 td = Timedelta(**kwargs) - result = frequencies.to_offset(td) + result = to_offset(td) assert result == expected @@ -164,5 +161,5 @@ def test_to_offset_pd_timedelta(kwargs, expected): ], ) def test_anchored_shortcuts(shortcut, expected): - result = frequencies.to_offset(shortcut) + result = to_offset(shortcut) assert result == expected diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index 908f9fa699891..bbabfed4cb976 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -40,6 +40,7 @@ def test_namespace(): "ints_to_pytimedelta", "localize_pydatetime", "tz_convert_single", + "to_offset", ] expected = set(submodules + api)
- [ ] 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/34538
2020-06-02T21:22:59Z
2020-06-03T22:31:31Z
2020-06-03T22:31:31Z
2020-06-03T22:32:53Z
CI/TST #34131 fixed test_floordiv_axis0_numexpr_path
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index e7b7f3e524d44..39e064ae4dd5d 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -11,6 +11,7 @@ from pandas import DataFrame, MultiIndex, Series import pandas._testing as tm import pandas.core.common as com +from pandas.core.computation.expressions import _MIN_ELEMENTS, _NUMEXPR_INSTALLED from pandas.tests.frame.common import _check_mixed_float, _check_mixed_int # ------------------------------------------------------------------- @@ -374,13 +375,13 @@ def test_floordiv_axis0(self): result2 = df.floordiv(ser.values, axis=0) tm.assert_frame_equal(result2, expected) - @pytest.mark.slow + @pytest.mark.skipif(not _NUMEXPR_INSTALLED, reason="numexpr not installed") @pytest.mark.parametrize("opname", ["floordiv", "pow"]) def test_floordiv_axis0_numexpr_path(self, opname): # case that goes through numexpr and has to fall back to masked_arith_op op = getattr(operator, opname) - arr = np.arange(10 ** 6).reshape(100, -1) + arr = np.arange(_MIN_ELEMENTS + 100).reshape(_MIN_ELEMENTS // 100 + 1, -1) * 100 df = pd.DataFrame(arr) df["C"] = 1.0
xref #34131 - [ x ] passes `black pandas` - [ x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Test `/pandas/tests/frame/test_floordiv_axis0_numexpr_path` is slow. It builds a df with 10^6 elements to tests functions `floordiv` and `pow`. The number of elements can be reduced with keeping the same min/max values inside the dataframe. Before/after timeit comparison: ``` 26.6 s ± 1.04 s per loop (mean ± std. dev. of 7 runs, 1 loop each) 37.6 ms ± 3.45 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/34537
2020-06-02T21:04:50Z
2020-06-14T20:46:34Z
2020-06-14T20:46:33Z
2021-01-02T08:31:59Z
DOC: remove an extra colon
diff --git a/doc/source/user_guide/gotchas.rst b/doc/source/user_guide/gotchas.rst index e0f6c7570074b..a96c70405d859 100644 --- a/doc/source/user_guide/gotchas.rst +++ b/doc/source/user_guide/gotchas.rst @@ -321,7 +321,7 @@ Byte-ordering issues -------------------- Occasionally you may have to deal with data that were created on a machine with a different byte order than the one on which you are running Python. A common -symptom of this issue is an error like::: +symptom of this issue is an error like:: Traceback ...
fix a typo by removing an extra colon - [ ] 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/34533
2020-06-02T14:47:48Z
2020-06-02T19:56:26Z
2020-06-02T19:56:26Z
2020-06-02T21:30:44Z
CLN: remove Resolution.get_attrname_from_abbrev
diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 91059638cd73a..c0baabdc98acd 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -41,18 +41,6 @@ _reso_str_map = { _str_reso_map = {v: k for k, v in _reso_str_map.items()} -# factor to multiply a value by to convert it to the next finer grained -# resolution -_reso_mult_map = { - RESO_NS: None, - RESO_US: 1000, - RESO_MS: 1000, - RESO_SEC: 1000, - RESO_MIN: 60, - RESO_HR: 60, - RESO_DAY: 24, -} - # ---------------------------------------------------------------------- @@ -145,17 +133,17 @@ class Resolution(Enum): def __ge__(self, other): return self.value >= other.value - @classmethod - def get_str(cls, reso: "Resolution") -> str: + @property + def attrname(self) -> str: """ - Return resolution str against resolution code. + Return datetime attribute name corresponding to this Resolution. Examples -------- - >>> Resolution.get_str(Resolution.RESO_SEC) + >>> Resolution.RESO_SEC.attrname 'second' """ - return _reso_str_map[reso.value] + return _reso_str_map[self.value] @classmethod def from_attrname(cls, attrname: str) -> "Resolution": @@ -172,18 +160,6 @@ class Resolution(Enum): """ return cls(_str_reso_map[attrname]) - @classmethod - def get_attrname_from_abbrev(cls, freq: str) -> str: - """ - Return resolution str against frequency str. - - Examples - -------- - >>> Resolution.get_attrname_from_abbrev('H') - 'hour' - """ - return _abbrev_to_attrnames[freq] - @classmethod def get_reso_from_freq(cls, freq: str) -> "Resolution": """ @@ -199,7 +175,8 @@ class Resolution(Enum): >>> Resolution.get_reso_from_freq('H') == Resolution.RESO_HR True """ - return cls.from_attrname(cls.get_attrname_from_abbrev(freq)) + attr_name = _abbrev_to_attrnames[freq] + return cls.from_attrname(attr_name) # ---------------------------------------------------------------------- diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 55420181190aa..da8e9b4bfdd4e 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1126,7 +1126,7 @@ def resolution(self) -> str: # somewhere in the past it was decided we default to day return "day" # otherwise we fall through and will raise - return Resolution.get_str(self._resolution_obj) + return self._resolution_obj.attrname # type: ignore @classmethod def _validate_frequency(cls, index, freq, **kwargs): diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py index 133db0c3d611b..f82d225f0538c 100644 --- a/pandas/tests/tseries/frequencies/test_freq_code.py +++ b/pandas/tests/tseries/frequencies/test_freq_code.py @@ -93,9 +93,6 @@ def test_get_to_timestamp_base(freqstr, exp_freqstr): @pytest.mark.parametrize( "freqstr,expected", [ - ("A", "year"), - ("Q", "quarter"), - ("M", "month"), ("D", "day"), ("H", "hour"), ("T", "minute"), @@ -106,19 +103,20 @@ def test_get_to_timestamp_base(freqstr, exp_freqstr): ], ) def test_get_attrname_from_abbrev(freqstr, expected): - assert _reso.get_attrname_from_abbrev(freqstr) == expected + assert _reso.get_reso_from_freq(freqstr).attrname == expected -@pytest.mark.parametrize("freq", ["A", "Q", "M", "D", "H", "T", "S", "L", "U", "N"]) -def test_get_freq_roundtrip(freq): - result = _attrname_to_abbrevs[_reso.get_attrname_from_abbrev(freq)] - assert freq == result +@pytest.mark.parametrize("freq", ["A", "Q", "M"]) +def test_get_freq_unsupported_(freq): + # Lowest-frequency resolution is for Day + with pytest.raises(KeyError, match=freq.lower()): + _reso.get_reso_from_freq(freq) -@pytest.mark.parametrize("freq", ["D", "H", "T", "S", "L", "U"]) +@pytest.mark.parametrize("freq", ["D", "H", "T", "S", "L", "U", "N"]) def test_get_freq_roundtrip2(freq): obj = _reso.get_reso_from_freq(freq) - result = _attrname_to_abbrevs[_reso.get_str(obj)] + result = _attrname_to_abbrevs[obj.attrname] assert freq == result
rename get_str -> attrname, make it a property instead of a classmethod
https://api.github.com/repos/pandas-dev/pandas/pulls/34524
2020-06-02T03:05:17Z
2020-06-02T13:03:01Z
2020-06-02T13:03:01Z
2020-06-02T14:39:40Z
CLN: stronger typing for Period.freq
diff --git a/pandas/_libs/tslibs/offsets.pxd b/pandas/_libs/tslibs/offsets.pxd index 69b878c77f0b8..2b8ad97b83917 100644 --- a/pandas/_libs/tslibs/offsets.pxd +++ b/pandas/_libs/tslibs/offsets.pxd @@ -1,3 +1,11 @@ +from numpy cimport int64_t + cpdef to_offset(object obj) cdef bint is_offset_object(object obj) cdef bint is_tick_object(object obj) + +cdef class BaseOffset: + cdef readonly: + int64_t n + bint normalize + dict _cache diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 9e6a2c0507f7f..33b478c4d8da4 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -366,10 +366,10 @@ cdef class BaseOffset: _adjust_dst = True _deprecations = frozenset(["isAnchored", "onOffset"]) - cdef readonly: - int64_t n - bint normalize - dict _cache + # cdef readonly: + # int64_t n + # bint normalize + # dict _cache def __init__(self, n=1, normalize=False): n = self._validate_n(n) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index bc190825214c1..30c5dd1a881ea 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -69,7 +69,10 @@ from pandas._libs.tslibs.nattype cimport ( c_nat_strings as nat_strings, ) from pandas._libs.tslibs.offsets cimport ( - to_offset, is_tick_object, is_offset_object, + BaseOffset, + to_offset, + is_tick_object, + is_offset_object, ) from pandas._libs.tslibs.tzconversion cimport tz_convert_utc_to_tzlocal @@ -1509,9 +1512,9 @@ cdef class _Period: cdef readonly: int64_t ordinal - object freq + BaseOffset freq - def __cinit__(self, ordinal, freq): + def __cinit__(self, int64_t ordinal, BaseOffset freq): self.ordinal = ordinal self.freq = freq diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index f7f8b86359732..10c1a56a2eb4e 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1205,7 +1205,7 @@ class Timedelta(_Timedelta): cdef: int64_t result, unit - from pandas.tseries.frequencies import to_offset + from pandas._libs.tslibs.offsets import to_offset unit = to_offset(freq).nanos result = unit * rounder(self.value / float(unit)) return Timedelta(result, unit='ns')
https://api.github.com/repos/pandas-dev/pandas/pulls/34523
2020-06-02T02:14:35Z
2020-06-02T13:03:55Z
2020-06-02T13:03:55Z
2020-06-02T14:39:22Z
DEPR: tz kwarg in Period.to_timestamp
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 6e8cbc34be062..2230c6cb88843 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -702,6 +702,7 @@ Deprecations raise an ``IndexError`` in the future. You can manually convert to an integer key instead (:issue:`34191`). - The ``squeeze`` keyword in the ``groupby`` function is deprecated and will be removed in a future version (:issue:`32380`) +- The ``tz`` keyword in :meth:`Period.to_timestamp` is deprecated and will be removed in a future version; use `per.to_timestamp(...).tz_localize(tz)`` instead (:issue:`34522`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index bc190825214c1..e271518525008 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1,3 +1,5 @@ +import warnings + from cpython.object cimport PyObject_RichCompareBool, Py_EQ, Py_NE from numpy cimport int64_t, import_array, ndarray @@ -1724,6 +1726,16 @@ cdef class _Period: ------- Timestamp """ + if tz is not None: + # GH#34522 + warnings.warn( + "Period.to_timestamp `tz` argument is deprecated and will " + "be removed in a future version. Use " + "`per.to_timestamp(...).tz_localize(tz)` instead.", + FutureWarning, + stacklevel=1, + ) + how = validate_end_alias(how) end = how == 'E' diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 631760c547985..fc7fd037bebdd 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -221,7 +221,7 @@ def _use_dynamic_x(ax, data): x = data.index if base <= FreqGroup.FR_DAY: return x[:1].is_normalized - return Period(x[0], freq).to_timestamp(tz=x.tz) == x[0] + return Period(x[0], freq).to_timestamp().tz_localize(x.tz) == x[0] return True diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 41909b4b1a9bb..42bd20fd9640b 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -506,7 +506,9 @@ def test_hash(self): @pytest.mark.parametrize("tzstr", ["Europe/Brussels", "Asia/Tokyo", "US/Pacific"]) def test_to_timestamp_tz_arg(self, tzstr): - p = Period("1/1/2005", freq="M").to_timestamp(tz=tzstr) + # GH#34522 tz kwarg deprecated + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="M").to_timestamp(tz=tzstr) exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) exp_zone = pytz.timezone(tzstr).normalize(p) @@ -514,7 +516,8 @@ def test_to_timestamp_tz_arg(self, tzstr): assert p.tz == exp_zone.tzinfo assert p.tz == exp.tz - p = Period("1/1/2005", freq="3H").to_timestamp(tz=tzstr) + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="3H").to_timestamp(tz=tzstr) exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) exp_zone = pytz.timezone(tzstr).normalize(p) @@ -522,7 +525,8 @@ def test_to_timestamp_tz_arg(self, tzstr): assert p.tz == exp_zone.tzinfo assert p.tz == exp.tz - p = Period("1/1/2005", freq="A").to_timestamp(freq="A", tz=tzstr) + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="A").to_timestamp(freq="A", tz=tzstr) exp = Timestamp("31/12/2005", tz="UTC").tz_convert(tzstr) exp_zone = pytz.timezone(tzstr).normalize(p) @@ -530,7 +534,8 @@ def test_to_timestamp_tz_arg(self, tzstr): assert p.tz == exp_zone.tzinfo assert p.tz == exp.tz - p = Period("1/1/2005", freq="A").to_timestamp(freq="3H", tz=tzstr) + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="A").to_timestamp(freq="3H", tz=tzstr) exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) exp_zone = pytz.timezone(tzstr).normalize(p) @@ -544,20 +549,23 @@ def test_to_timestamp_tz_arg(self, tzstr): ) def test_to_timestamp_tz_arg_dateutil(self, tzstr): tz = maybe_get_tz(tzstr) - p = Period("1/1/2005", freq="M").to_timestamp(tz=tz) + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="M").to_timestamp(tz=tz) exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) assert p == exp assert p.tz == dateutil_gettz(tzstr.split("/", 1)[1]) assert p.tz == exp.tz - p = Period("1/1/2005", freq="M").to_timestamp(freq="3H", tz=tz) + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="M").to_timestamp(freq="3H", tz=tz) exp = Timestamp("1/1/2005", tz="UTC").tz_convert(tzstr) assert p == exp assert p.tz == dateutil_gettz(tzstr.split("/", 1)[1]) assert p.tz == exp.tz def test_to_timestamp_tz_arg_dateutil_from_string(self): - p = Period("1/1/2005", freq="M").to_timestamp(tz="dateutil/Europe/Brussels") + with tm.assert_produces_warning(FutureWarning): + p = Period("1/1/2005", freq="M").to_timestamp(tz="dateutil/Europe/Brussels") assert p.tz == dateutil_gettz("Europe/Brussels") def test_to_timestamp_mult(self):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry inconsistent with PeriodArray/PeriodIndex methods
https://api.github.com/repos/pandas-dev/pandas/pulls/34522
2020-06-01T23:20:39Z
2020-06-03T11:34:03Z
2020-06-03T11:34:03Z
2020-06-03T16:29:07Z
REF: add Resolution to tslibs.__init__
diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index 370b49f2c4fa3..965adc82df676 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -8,6 +8,7 @@ "OutOfBoundsDatetime", "IncompatibleFrequency", "Period", + "Resolution", "Timedelta", "delta_to_nanoseconds", "ints_to_pytimedelta", @@ -20,6 +21,7 @@ from .nattype import NaT, NaTType, iNaT, is_null_datetimelike, nat_strings from .np_datetime import OutOfBoundsDatetime from .period import IncompatibleFrequency, Period +from .resolution import Resolution from .timedeltas import Timedelta, delta_to_nanoseconds, ints_to_pytimedelta from .timestamps import Timestamp from .tzconversion import tz_convert_single diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index b9f712e4d64fe..55420181190aa 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -5,9 +5,16 @@ import numpy as np -from pandas._libs import NaT, NaTType, Period, Timestamp, algos, iNaT, lib -from pandas._libs.tslibs.resolution import Resolution -from pandas._libs.tslibs.timedeltas import delta_to_nanoseconds +from pandas._libs import algos, lib +from pandas._libs.tslibs import ( + NaT, + NaTType, + Period, + Resolution, + Timestamp, + delta_to_nanoseconds, + iNaT, +) from pandas._libs.tslibs.timestamps import ( RoundTo, integer_op_not_supported, @@ -1103,7 +1110,7 @@ def inferred_freq(self): return None @property # NB: override with cache_readonly in immutable subclasses - def _resolution(self) -> Optional[Resolution]: + def _resolution_obj(self) -> Optional[Resolution]: try: return Resolution.get_reso_from_freq(self.freqstr) except KeyError: @@ -1114,12 +1121,12 @@ def resolution(self) -> str: """ Returns day, hour, minute, second, millisecond or microsecond """ - if self._resolution is None: + if self._resolution_obj is None: if is_period_dtype(self.dtype): # somewhere in the past it was decided we default to day return "day" # otherwise we fall through and will raise - return Resolution.get_str(self._resolution) + return Resolution.get_str(self._resolution_obj) @classmethod def _validate_frequency(cls, index, freq, **kwargs): diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index bade1c031d556..f11f3ad974b37 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -537,7 +537,7 @@ def is_normalized(self): return conversion.is_date_array_normalized(self.asi8, self.tz) @property # NB: override with cache_readonly in immutable subclasses - def _resolution(self) -> libresolution.Resolution: + def _resolution_obj(self) -> libresolution.Resolution: return libresolution.get_resolution(self.asi8, self.tz) # ---------------------------------------------------------------- diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 2a7cd0eac04a6..21f4b3f8bb76a 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -7,7 +7,7 @@ import numpy as np from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib -from pandas._libs.tslibs import timezones +from pandas._libs.tslibs import Resolution, timezones from pandas._libs.tslibs.parsing import DateParseError from pandas._typing import Label from pandas.compat.numpy import function as nv @@ -78,7 +78,7 @@ def wrapper(left, right): @inherit_names( - ["inferred_freq", "_isnan", "_resolution", "resolution"], + ["inferred_freq", "_isnan", "_resolution_obj", "resolution"], DatetimeLikeArrayMixin, cache=True, ) @@ -93,7 +93,7 @@ class DatetimeIndexOpsMixin(ExtensionIndex): _data: Union[DatetimeArray, TimedeltaArray, PeriodArray] freq: Optional[DateOffset] freqstr: Optional[str] - _resolution: int + _resolution_obj: Resolution _bool_ops: List[str] = [] _field_ops: List[str] = [] diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 250038726b719..4677faa6b7d24 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -6,7 +6,7 @@ import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib, tslib -from pandas._libs.tslibs import fields, parsing, resolution as libresolution, timezones +from pandas._libs.tslibs import Resolution, fields, parsing, timezones from pandas._libs.tslibs.frequencies import get_freq_group from pandas._libs.tslibs.offsets import prefix_mapping from pandas._typing import DtypeObj, Label @@ -72,7 +72,9 @@ def _new_DatetimeIndex(cls, d): DatetimeArray, wrap=True, ) -@inherit_names(["_timezone", "is_normalized", "_resolution"], DatetimeArray, cache=True) +@inherit_names( + ["_timezone", "is_normalized", "_resolution_obj"], DatetimeArray, cache=True +) @inherit_names( [ "_bool_ops", @@ -525,7 +527,7 @@ def _validate_partial_date_slice(self, reso: str): if ( self.is_monotonic and reso in ["day", "hour", "minute", "second"] - and self._resolution >= libresolution.Resolution.from_attrname(reso) + and self._resolution_obj >= Resolution.from_attrname(reso) ): # These resolution/monotonicity validations came from GH3931, # GH3452 and GH2369. diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index 5518760dbacb3..908f9fa699891 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -33,6 +33,7 @@ def test_namespace(): "OutOfBoundsDatetime", "Period", "IncompatibleFrequency", + "Resolution", "Timedelta", "Timestamp", "delta_to_nanoseconds",
rename _resolution -> _resolution_obj
https://api.github.com/repos/pandas-dev/pandas/pulls/34518
2020-06-01T20:15:58Z
2020-06-02T01:13:39Z
2020-06-02T01:13:39Z
2020-06-02T01:21:46Z
TST #22663: Operation between DataFrame with non-numeric types and incomplete series
diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index e7b7f3e524d44..d9f251a1b5304 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1536,3 +1536,18 @@ def test_dataframe_blockwise_slicelike(): expected = pd.DataFrame({i: left[i] + right[i] for i in left.columns}) tm.assert_frame_equal(res, expected) + + +@pytest.mark.parametrize( + "df, col_dtype", + [ + (pd.DataFrame([[1.0, 2.0], [4.0, 5.0]], columns=list("ab")), "float64"), + (pd.DataFrame([[1.0, "b"], [4.0, "b"]], columns=list("ab")), "object"), + ], +) +def test_dataframe_operation_with_non_numeric_types(df, col_dtype): + # GH #22663 + expected = pd.DataFrame([[0.0, np.nan], [3.0, np.nan]], columns=list("ab")) + expected = expected.astype({"b": col_dtype}) + result = df + pd.Series([-1.0], index=list("a")) + tm.assert_frame_equal(result, expected)
- [ x ] closes #22663 - [ 1 ] tests added / passed - [ x ] passes `black pandas` - [ x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/34517
2020-06-01T16:05:43Z
2020-06-02T22:21:05Z
2020-06-02T22:21:04Z
2020-06-03T06:48:29Z
CI: Linux py37_np_dev failing on 1.0.x
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index eecb1e567bd8f..d4b60ec186b86 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -558,7 +558,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): object """ - dtype = np.object_ + dtype = np.dtype(np.object_) # a 1-element ndarray if isinstance(val, np.ndarray): @@ -577,7 +577,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): # instead of np.empty (but then you still don't want things # coming out as np.str_! - dtype = np.object_ + dtype = np.dtype(np.object_) elif isinstance(val, (np.datetime64, datetime)): val = tslibs.Timestamp(val) @@ -588,7 +588,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): dtype = DatetimeTZDtype(unit="ns", tz=val.tz) else: # return datetimetz as object - return np.object_, val + return np.dtype(np.object_), val val = val.value elif isinstance(val, (np.timedelta64, timedelta)): @@ -596,22 +596,22 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False): dtype = np.dtype("m8[ns]") elif is_bool(val): - dtype = np.bool_ + dtype = np.dtype(np.bool_) elif is_integer(val): if isinstance(val, np.integer): - dtype = type(val) + dtype = np.dtype(type(val)) else: - dtype = np.int64 + dtype = np.dtype(np.int64) elif is_float(val): if isinstance(val, np.floating): - dtype = type(val) + dtype = np.dtype(type(val)) else: - dtype = np.float64 + dtype = np.dtype(np.float64) elif is_complex(val): - dtype = np.complex_ + dtype = np.dtype(np.complex_) elif pandas_dtype: if lib.is_period(val): diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 3a92cfd9bf16d..0856f65306849 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -233,7 +233,7 @@ def init_dict(data, index, columns, dtype=None): if missing.any() and not is_integer_dtype(dtype): if dtype is None or np.issubdtype(dtype, np.flexible): # GH#1783 - nan_dtype = object + nan_dtype = np.dtype(object) else: nan_dtype = dtype val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype)
xref https://github.com/pandas-dev/pandas/pull/34503#issuecomment-636651219
https://api.github.com/repos/pandas-dev/pandas/pulls/34516
2020-06-01T15:14:54Z
2020-06-01T20:14:57Z
2020-06-01T20:14:57Z
2020-06-02T07:22:02Z
CLN: remove Resolution.get_stride_from_decimal
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 0caacd81c53f5..9e6a2c0507f7f 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -762,7 +762,7 @@ cdef class Tick(SingleConstructorOffset): return Micro(self.n * 1000) if type(self) is Micro: return Nano(self.n * 1000) - raise NotImplementedError(type(self)) + raise ValueError("Could not convert to integer offset at any resolution") # -------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index b3fc1e32f68e8..91059638cd73a 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -27,16 +27,6 @@ cdef: int RESO_HR = 5 int RESO_DAY = 6 -reso_str_bump_map = { - "D": "H", - "H": "T", - "T": "S", - "S": "L", - "L": "U", - "U": "N", - "N": None, -} - _abbrev_to_attrnames = {v: k for k, v in attrname_to_abbrevs.items()} _reso_str_map = { @@ -168,19 +158,19 @@ class Resolution(Enum): return _reso_str_map[reso.value] @classmethod - def get_reso(cls, resostr: str) -> "Resolution": + def from_attrname(cls, attrname: str) -> "Resolution": """ Return resolution str against resolution code. Examples -------- - >>> Resolution.get_reso('second') + >>> Resolution.from_attrname('second') 2 - >>> Resolution.get_reso('second') == Resolution.RESO_SEC + >>> Resolution.from_attrname('second') == Resolution.RESO_SEC True """ - return cls(_str_reso_map[resostr]) + return cls(_str_reso_map[attrname]) @classmethod def get_attrname_from_abbrev(cls, freq: str) -> str: @@ -209,47 +199,7 @@ class Resolution(Enum): >>> Resolution.get_reso_from_freq('H') == Resolution.RESO_HR True """ - return cls.get_reso(cls.get_attrname_from_abbrev(freq)) - - @classmethod - def get_stride_from_decimal(cls, value: float, freq: str): - """ - Convert freq with decimal stride into a higher freq with integer stride - - Parameters - ---------- - value : float - freq : str - Frequency string - - Raises - ------ - ValueError - If the float cannot be converted to an integer at any resolution. - - Examples - -------- - >>> Resolution.get_stride_from_decimal(1.5, 'T') - (90, 'S') - - >>> Resolution.get_stride_from_decimal(1.04, 'H') - (3744, 'S') - - >>> Resolution.get_stride_from_decimal(1, 'D') - (1, 'D') - """ - if np.isclose(value % 1, 0): - return int(value), freq - else: - start_reso = cls.get_reso_from_freq(freq) - if start_reso.value == 0: - raise ValueError( - "Could not convert to integer offset at any resolution" - ) - - next_value = _reso_mult_map[start_reso.value] * value - next_name = reso_str_bump_map[freq] - return cls.get_stride_from_decimal(next_value, next_name) + return cls.from_attrname(cls.get_attrname_from_abbrev(freq)) # ---------------------------------------------------------------------- diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 877d19ef68558..250038726b719 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -525,7 +525,7 @@ def _validate_partial_date_slice(self, reso: str): if ( self.is_monotonic and reso in ["day", "hour", "minute", "second"] - and self._resolution >= libresolution.Resolution.get_reso(reso) + and self._resolution >= libresolution.Resolution.from_attrname(reso) ): # These resolution/monotonicity validations came from GH3931, # GH3452 and GH2369. diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py index 51554854378ea..133db0c3d611b 100644 --- a/pandas/tests/tseries/frequencies/test_freq_code.py +++ b/pandas/tests/tseries/frequencies/test_freq_code.py @@ -10,6 +10,7 @@ ) from pandas._libs.tslibs.resolution import Resolution as _reso +from pandas.tseries.frequencies import to_offset import pandas.tseries.offsets as offsets @@ -116,7 +117,8 @@ def test_get_freq_roundtrip(freq): @pytest.mark.parametrize("freq", ["D", "H", "T", "S", "L", "U"]) def test_get_freq_roundtrip2(freq): - result = _attrname_to_abbrevs[_reso.get_str(_reso.get_reso_from_freq(freq))] + obj = _reso.get_reso_from_freq(freq) + result = _attrname_to_abbrevs[_reso.get_str(obj)] assert freq == result @@ -133,7 +135,9 @@ def test_get_freq_roundtrip2(freq): ) def test_resolution_bumping(args, expected): # see gh-14378 - assert _reso.get_stride_from_decimal(*args) == expected + off = to_offset(str(args[0]) + args[1]) + assert off.n == expected[0] + assert off._prefix == expected[1] @pytest.mark.parametrize( @@ -145,10 +149,10 @@ def test_resolution_bumping(args, expected): ], ) def test_cat(args): - msg = "Could not convert to integer offset at any resolution" + msg = "Invalid frequency" with pytest.raises(ValueError, match=msg): - _reso.get_stride_from_decimal(*args) + to_offset(str(args[0]) + args[1]) @pytest.mark.parametrize(
as it is no longer used; update its tests rename Resolution.get_reso -> Resolution.from_attrname
https://api.github.com/repos/pandas-dev/pandas/pulls/34515
2020-06-01T15:11:32Z
2020-06-01T21:55:36Z
2020-06-01T21:55:36Z
2020-06-01T22:57:15Z
BUG: asymmetric error bars for series (GH9536)
diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst index 27826e7cde9e1..5bc87bca87211 100644 --- a/doc/source/user_guide/visualization.rst +++ b/doc/source/user_guide/visualization.rst @@ -1425,7 +1425,7 @@ Horizontal and vertical error bars can be supplied to the ``xerr`` and ``yerr`` * As a ``str`` indicating which of the columns of plotting :class:`DataFrame` contain the error values. * As raw values (``list``, ``tuple``, or ``np.ndarray``). Must be the same length as the plotting :class:`DataFrame`/:class:`Series`. -Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a ``M`` length :class:`Series`, a ``Mx2`` array should be provided indicating lower and upper (or left and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors should be in a ``Mx2xN`` array. +Asymmetrical error bars are also supported, however raw error values must be provided in this case. For a ``N`` length :class:`Series`, a ``2xN`` array should be provided indicating lower and upper (or left and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors should be in a ``Mx2xN`` array. Here is an example of one way to easily plot group means with standard deviations from the raw data. diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index bdb844ded59b7..d74c1bca61de8 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -340,6 +340,7 @@ Other enhancements - :class:`pandas.core.window.ExponentialMovingWindow` now supports a ``times`` argument that allows ``mean`` to be calculated with observations spaced by the timestamps in ``times`` (:issue:`34839`) - :meth:`DataFrame.agg` and :meth:`Series.agg` now accept named aggregation for renaming the output columns/indexes. (:issue:`26513`) - ``compute.use_numba`` now exists as a configuration option that utilizes the numba engine when available (:issue:`33966`) +- :meth:`Series.plot` now supports asymmetric error bars. Previously, if :meth:`Series.plot` received a "2xN" array with error values for `yerr` and/or `xerr`, the left/lower values (first row) were mirrored, while the right/upper values (second row) were ignored. Now, the first row represents the left/lower error values and the second row the right/upper error values. (:issue:`9536`) .. --------------------------------------------------------------------------- diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index e510f7140519a..353bc8a8936a5 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -770,6 +770,12 @@ def _parse_errorbars(self, label, err): DataFrame/dict: error values are paired with keys matching the key in the plotted DataFrame str: the name of the column within the plotted DataFrame + + Asymmetrical error bars are also supported, however raw error values + must be provided in this case. For a ``N`` length :class:`Series`, a + ``2xN`` array should be provided indicating lower and upper (or left + and right) errors. For a ``MxN`` :class:`DataFrame`, asymmetrical errors + should be in a ``Mx2xN`` array. """ if err is None: return None @@ -810,7 +816,15 @@ def match_labels(data, e): err_shape = err.shape # asymmetrical error bars - if err.ndim == 3: + if isinstance(self.data, ABCSeries) and err_shape[0] == 2: + err = np.expand_dims(err, 0) + err_shape = err.shape + if err_shape[2] != len(self.data): + raise ValueError( + "Asymmetrical error bars should be provided " + f"with the shape (2, {len(self.data)})" + ) + elif isinstance(self.data, ABCDataFrame) and err.ndim == 3: if ( (err_shape[0] != self.nseries) or (err_shape[1] != 2) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 64da98f57676f..316ca6ce91af7 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -729,6 +729,26 @@ def test_dup_datetime_index_plot(self): s = Series(values, index=index) _check_plot_works(s.plot) + def test_errorbar_asymmetrical(self): + # GH9536 + s = Series(np.arange(10), name="x") + err = np.random.rand(2, 10) + + ax = s.plot(yerr=err, xerr=err) + + result = np.vstack([i.vertices[:, 1] for i in ax.collections[1].get_paths()]) + expected = (err.T * np.array([-1, 1])) + s.to_numpy().reshape(-1, 1) + tm.assert_numpy_array_equal(result, expected) + + msg = ( + "Asymmetrical error bars should be provided " + f"with the shape \\(2, {len(s)}\\)" + ) + with pytest.raises(ValueError, match=msg): + s.plot(yerr=np.random.rand(2, 11)) + + tm.close() + @pytest.mark.slow def test_errorbar_plot(self):
closes #9536 This fix enables asymmetric errors bars for pd.Series plots. In the current implementation the bars are symmetric, even if two sets of errors are provided. Took inspirations from #12046
https://api.github.com/repos/pandas-dev/pandas/pulls/34514
2020-06-01T14:46:29Z
2020-07-17T16:26:47Z
2020-07-17T16:26:47Z
2020-07-17T16:46:15Z
BUG: fix BooleanArray.astype('string') (GH34110)
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 6b7b282bfd940..5d791ffd20f01 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -370,11 +370,15 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: if incompatible type with an BooleanDtype, equivalent of same_kind casting """ + from pandas.core.arrays.string_ import StringDtype + dtype = pandas_dtype(dtype) if isinstance(dtype, BooleanDtype): values, mask = coerce_to_array(self, copy=copy) return BooleanArray(values, mask, copy=False) + elif isinstance(dtype, StringDtype): + return dtype.construct_array_type()._from_sequence(self, copy=False) if is_bool_dtype(dtype): # astype_nansafe converts np.nan to True
This should fix CI (bug caused by https://github.com/pandas-dev/pandas/pull/34110, due to another PR that was merged a few days ago adding this capability)
https://api.github.com/repos/pandas-dev/pandas/pulls/34509
2020-06-01T07:27:09Z
2020-06-01T08:07:26Z
2020-06-01T08:07:26Z
2020-06-01T08:29:49Z
DOC: Docstring updated for DataFrame.equals
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 843b602a12823..87f25f578c3c6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -1201,9 +1201,11 @@ def equals(self, other): This function allows two Series or DataFrames to be compared against each other to see if they have the same shape and elements. NaNs in - the same location are considered equal. The column headers do not - need to have the same type, but the elements within the columns must - be the same dtype. + the same location are considered equal. + + The row/column index do not need to have the same type, as long + as the values are considered equal. Corresponding columns must be of + the same dtype. Parameters ---------- @@ -1232,13 +1234,6 @@ def equals(self, other): numpy.array_equal : Return True if two arrays have the same shape and elements, False otherwise. - Notes - ----- - This function requires that the elements have the same dtype as their - respective elements in the other Series or DataFrame. However, the - column labels do not need to have the same type, as long as they are - still considered equal. - Examples -------- >>> df = pd.DataFrame({1: [10], 2: [20]})
- [ ] closes #34498
https://api.github.com/repos/pandas-dev/pandas/pulls/34508
2020-06-01T04:44:14Z
2020-08-07T19:16:40Z
2020-08-07T19:16:40Z
2020-08-07T19:16:54Z
REF: use standard pattern in normalize_i8_timestamps
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index cbb27bf8e9917..b0bad119d6a46 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -788,7 +788,16 @@ cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo t npy_datetimestruct dts int64_t delta, local_val - if is_tzlocal(tz): + if tz is None or is_utc(tz): + with nogil: + for i in range(n): + if stamps[i] == NPY_NAT: + result[i] = NPY_NAT + continue + local_val = stamps[i] + dt64_to_dtstruct(local_val, &dts) + result[i] = _normalized_stamp(&dts) + elif is_tzlocal(tz): for i in range(n): if stamps[i] == NPY_NAT: result[i] = NPY_NAT diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index a7c4b44cf95f8..fad87f9f910cb 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1451,13 +1451,8 @@ default 'raise' ndarray[int64_t] normalized tzinfo own_tz = self.tzinfo # could be None - if own_tz is None or is_utc(own_tz): - DAY_NS = ccalendar.DAY_NANOS - normalized_value = self.value - (self.value % DAY_NS) - return Timestamp(normalized_value).tz_localize(own_tz) - normalized = normalize_i8_timestamps( - np.array([self.value], dtype='i8'), tz=own_tz) + np.array([self.value], dtype="i8"), tz=own_tz) return Timestamp(normalized[0]).tz_localize(own_tz) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 4e31477571a5f..bade1c031d556 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -9,15 +9,14 @@ from pandas._libs.tslibs import ( NaT, Timestamp, - ccalendar, conversion, fields, + frequencies as libfrequencies, iNaT, resolution as libresolution, timezones, tzconversion, ) -import pandas._libs.tslibs.frequencies as libfrequencies from pandas.errors import PerformanceWarning from pandas.core.dtypes.common import ( @@ -1036,14 +1035,7 @@ def normalize(self): '2014-08-01 00:00:00+05:30'], dtype='datetime64[ns, Asia/Calcutta]', freq=None) """ - if self.tz is None or timezones.is_utc(self.tz): - not_null = ~self.isna() - DAY_NS = ccalendar.DAY_SECONDS * 1_000_000_000 - new_values = self.asi8.copy() - adjustment = new_values[not_null] % DAY_NS - new_values[not_null] = new_values[not_null] - adjustment - else: - new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz) + new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz) return type(self)(new_values)._with_freq("infer").tz_localize(self.tz) def to_period(self, freq=None):
From here the plan is to move to passing `int64_t*` which will allow us to share code between the scalar/vector versions of this function
https://api.github.com/repos/pandas-dev/pandas/pulls/34507
2020-06-01T00:04:20Z
2020-06-01T02:31:19Z
2020-06-01T02:31:19Z
2020-06-09T15:00:58Z
CLN: unreachable branch in tzconversion
diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 030549f2528ed..575088b8ab2cc 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -557,30 +557,25 @@ cdef int64_t[:] _tz_convert_dst( ndarray[int64_t] trans int64_t[:] deltas int64_t v - bint tz_is_local - tz_is_local = is_tzlocal(tz) + # tz is assumed _not_ to be tzlocal; that should go + # through _tz_convert_tzlocal_utc - if not tz_is_local: - # get_dst_info cannot extract offsets from tzlocal because its - # dependent on a datetime - trans, deltas, _ = get_dst_info(tz) - if not to_utc: - # We add `offset` below instead of subtracting it - deltas = -1 * np.array(deltas, dtype='i8') + trans, deltas, _ = get_dst_info(tz) + if not to_utc: + # We add `offset` below instead of subtracting it + deltas = -1 * np.array(deltas, dtype='i8') - # Previously, this search was done pointwise to try and benefit - # from getting to skip searches for iNaTs. However, it seems call - # overhead dominates the search time so doing it once in bulk - # is substantially faster (GH#24603) - pos = trans.searchsorted(values, side='right') - 1 + # Previously, this search was done pointwise to try and benefit + # from getting to skip searches for iNaTs. However, it seems call + # overhead dominates the search time so doing it once in bulk + # is substantially faster (GH#24603) + pos = trans.searchsorted(values, side='right') - 1 for i in range(n): v = values[i] if v == NPY_NAT: result[i] = v - elif tz_is_local: - result[i] = _tz_convert_tzlocal_utc(v, tz, to_utc=to_utc) else: if pos[i] < 0: raise ValueError('First time before start of DST info')
https://api.github.com/repos/pandas-dev/pandas/pulls/34505
2020-05-31T19:11:27Z
2020-05-31T21:46:24Z
2020-05-31T21:46:24Z
2020-05-31T22:34:18Z
CLN: stronger typing in tzconversion
diff --git a/pandas/_libs/tslibs/tzconversion.pxd b/pandas/_libs/tslibs/tzconversion.pxd index 190205d9c3c44..7f445d7549f45 100644 --- a/pandas/_libs/tslibs/tzconversion.pxd +++ b/pandas/_libs/tslibs/tzconversion.pxd @@ -3,4 +3,4 @@ from numpy cimport int64_t cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz, bint* fold=*) -cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2) +cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2) diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index 030549f2528ed..ffd076d0608f2 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -28,7 +28,7 @@ from pandas._libs.tslibs.timezones cimport ( # TODO: cdef scalar version to call from convert_str_to_tsobject @cython.boundscheck(False) @cython.wraparound(False) -def tz_localize_to_utc(ndarray[int64_t] vals, object tz, object ambiguous=None, +def tz_localize_to_utc(ndarray[int64_t] vals, tzinfo tz, object ambiguous=None, object nonexistent=None): """ Localize tzinfo-naive i8 to given time zone (using pytz). If @@ -329,7 +329,7 @@ cdef int64_t tz_convert_utc_to_tzlocal(int64_t utc_val, tzinfo tz, bint* fold=NU return _tz_convert_tzlocal_utc(utc_val, tz, to_utc=False, fold=fold) -cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): +cpdef int64_t tz_convert_single(int64_t val, tzinfo tz1, tzinfo tz2): """ Convert the val (in i8) from timezone1 to timezone2 @@ -338,18 +338,15 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): Parameters ---------- val : int64 - tz1 : string / timezone object - tz2 : string / timezone object + tz1 : tzinfo + tz2 : tzinfo Returns ------- converted: int64 """ cdef: - int64_t[:] deltas - Py_ssize_t pos - int64_t v, offset, utc_date - npy_datetimestruct dts + int64_t utc_date int64_t arr[1] # See GH#17734 We should always be converting either from UTC or to UTC @@ -381,17 +378,15 @@ cpdef int64_t tz_convert_single(int64_t val, object tz1, object tz2): return _tz_convert_dst(arr, tz2, to_utc=False)[0] -@cython.boundscheck(False) -@cython.wraparound(False) -def tz_convert(int64_t[:] vals, object tz1, object tz2): +def tz_convert(int64_t[:] vals, tzinfo tz1, tzinfo tz2): """ Convert the values (in i8) from timezone1 to timezone2 Parameters ---------- vals : int64 ndarray - tz1 : string / timezone object - tz2 : string / timezone object + tz1 : tzinfo + tz2 : tzinfo Returns ------- @@ -411,15 +406,15 @@ def tz_convert(int64_t[:] vals, object tz1, object tz2): @cython.boundscheck(False) @cython.wraparound(False) -cdef int64_t[:] _tz_convert_one_way(int64_t[:] vals, object tz, bint to_utc): +cdef int64_t[:] _tz_convert_one_way(int64_t[:] vals, tzinfo tz, bint to_utc): """ Convert the given values (in i8) either to UTC or from UTC. Parameters ---------- vals : int64 ndarray - tz1 : string / timezone object - to_utc : bint + tz1 : tzinfo + to_utc : bool Returns ------- @@ -430,7 +425,7 @@ cdef int64_t[:] _tz_convert_one_way(int64_t[:] vals, object tz, bint to_utc): Py_ssize_t i, n = len(vals) int64_t val - if not is_utc(get_timezone(tz)): + if not is_utc(tz): converted = np.empty(n, dtype=np.int64) if is_tzlocal(tz): for i in range(n):
https://api.github.com/repos/pandas-dev/pandas/pulls/34504
2020-05-31T18:33:03Z
2020-05-31T21:47:35Z
2020-05-31T21:47:35Z
2020-05-31T22:39:12Z
Backport PR #34481 on branch 1.0.x (DOC: start 1.0.5)
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index 0e0c7492da3be..dec0807b8aad1 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -16,6 +16,7 @@ Version 1.0 .. toctree:: :maxdepth: 2 + v1.0.5 v1.0.4 v1.0.3 v1.0.2 diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst index 5cc1edc9ca9cd..84b7e7d45e8b7 100644 --- a/doc/source/whatsnew/v1.0.4.rst +++ b/doc/source/whatsnew/v1.0.4.rst @@ -45,4 +45,4 @@ Bug fixes Contributors ~~~~~~~~~~~~ -.. contributors:: v1.0.3..v1.0.4|HEAD +.. contributors:: v1.0.3..v1.0.4 diff --git a/doc/source/whatsnew/v1.0.5.rst b/doc/source/whatsnew/v1.0.5.rst new file mode 100644 index 0000000000000..1edc7e1cad72f --- /dev/null +++ b/doc/source/whatsnew/v1.0.5.rst @@ -0,0 +1,31 @@ + +.. _whatsnew_105: + +What's new in 1.0.5 (June XX, 2020) +----------------------------------- + +These are the changes in pandas 1.0.5. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- + +.. _whatsnew_105.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. _whatsnew_105.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v1.0.4..v1.0.5|HEAD
Backport PR #34481: DOC: start 1.0.5
https://api.github.com/repos/pandas-dev/pandas/pulls/34503
2020-05-31T18:05:26Z
2020-06-01T07:00:22Z
2020-06-01T07:00:22Z
2020-06-01T14:25:15Z
CLN: GH29547 format with f-strings
diff --git a/pandas/tests/series/indexing/test_take.py b/pandas/tests/series/indexing/test_take.py index 9368d49e5ff2b..dc161b6be5d66 100644 --- a/pandas/tests/series/indexing/test_take.py +++ b/pandas/tests/series/indexing/test_take.py @@ -16,10 +16,10 @@ def test_take(): expected = Series([4, 2, 4], index=[4, 3, 4]) tm.assert_series_equal(actual, expected) - msg = "index {} is out of bounds for( axis 0 with)? size 5" - with pytest.raises(IndexError, match=msg.format(10)): + msg = lambda x: f"index {x} is out of bounds for( axis 0 with)? size 5" + with pytest.raises(IndexError, match=msg(10)): ser.take([1, 10]) - with pytest.raises(IndexError, match=msg.format(5)): + with pytest.raises(IndexError, match=msg(5)): ser.take([2, 5]) diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index 3f85abb4b2817..c4a2cb90f7090 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -222,12 +222,14 @@ def test_where_setitem_invalid(): # GH 2702 # make sure correct exceptions are raised on invalid list assignment - msg = "cannot set using a {} indexer with a different length than the value" - + msg = ( + lambda x: f"cannot set using a {x} indexer with a " + "different length than the value" + ) # slice s = Series(list("abc")) - with pytest.raises(ValueError, match=msg.format("slice")): + with pytest.raises(ValueError, match=msg("slice")): s[0:3] = list(range(27)) s[0:3] = list(range(3)) @@ -237,7 +239,7 @@ def test_where_setitem_invalid(): # slice with step s = Series(list("abcdef")) - with pytest.raises(ValueError, match=msg.format("slice")): + with pytest.raises(ValueError, match=msg("slice")): s[0:4:2] = list(range(27)) s = Series(list("abcdef")) @@ -248,7 +250,7 @@ def test_where_setitem_invalid(): # neg slices s = Series(list("abcdef")) - with pytest.raises(ValueError, match=msg.format("slice")): + with pytest.raises(ValueError, match=msg("slice")): s[:-1] = list(range(27)) s[-3:-1] = list(range(2)) @@ -258,12 +260,12 @@ def test_where_setitem_invalid(): # list s = Series(list("abc")) - with pytest.raises(ValueError, match=msg.format("list-like")): + with pytest.raises(ValueError, match=msg("list-like")): s[[0, 1, 2]] = list(range(27)) s = Series(list("abc")) - with pytest.raises(ValueError, match=msg.format("list-like")): + with pytest.raises(ValueError, match=msg("list-like")): s[[0, 1, 2]] = list(range(2)) # scalar
replace .format() for f-strings in the following: 1. pandas/tests/series/indexing/test_numeric.py 2. pandas/tests/series/indexing/test_take.py 3. pandas/tests/series/indexing/test_where.py
https://api.github.com/repos/pandas-dev/pandas/pulls/34502
2020-05-31T17:52:39Z
2020-06-20T19:59:22Z
2020-06-20T19:59:22Z
2020-06-20T19:59:26Z
REG: Fix read_parquet from file-like objects
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index cde7a98eb42ae..de9a14c82b3cb 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -122,11 +122,20 @@ def write( file_obj_or_path.close() def read(self, path, columns=None, **kwargs): - parquet_ds = self.api.parquet.ParquetDataset( - path, filesystem=get_fs_for_path(path), **kwargs - ) - kwargs["columns"] = columns - result = parquet_ds.read_pandas(**kwargs).to_pandas() + fs = get_fs_for_path(path) + should_close = None + # Avoid calling get_filepath_or_buffer for s3/gcs URLs since + # since it returns an S3File which doesn't support dir reads in arrow + if not fs: + path, _, _, should_close = get_filepath_or_buffer(path) + + kwargs["use_pandas_metadata"] = True + result = self.api.parquet.read_table( + path, columns=columns, filesystem=fs, **kwargs + ).to_pandas() + if should_close: + path.close() + return result diff --git a/pandas/tests/io/data/parquet/simple.parquet b/pandas/tests/io/data/parquet/simple.parquet new file mode 100644 index 0000000000000..2862a91f508ea Binary files /dev/null and b/pandas/tests/io/data/parquet/simple.parquet differ diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 8a43d4079159b..7ee551194bf76 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -1,6 +1,7 @@ """ test parquet compat """ import datetime from distutils.version import LooseVersion +from io import BytesIO import os from warnings import catch_warnings @@ -567,6 +568,23 @@ def test_s3_roundtrip_for_dir(self, df_compat, s3_resource, pa, partition_col): repeat=1, ) + @tm.network + @td.skip_if_no("pyarrow") + def test_parquet_read_from_url(self, df_compat): + url = ( + "https://raw.githubusercontent.com/pandas-dev/pandas/" + "master/pandas/tests/io/data/parquet/simple.parquet" + ) + df = pd.read_parquet(url) + tm.assert_frame_equal(df, df_compat) + + @td.skip_if_no("pyarrow") + def test_read_file_like_obj_support(self, df_compat): + buffer = BytesIO() + df_compat.to_parquet(buffer) + df_from_buf = pd.read_parquet(buffer) + tm.assert_frame_equal(df_compat, df_from_buf) + def test_partition_cols_supported(self, pa, df_full): # GH #23283 partition_cols = ["bool", "int"]
- [x] xref #34467 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry - waiting on https://github.com/pandas-dev/pandas/pull/34481 Use arrow parquet.read_table opposed to ParquetDataset
https://api.github.com/repos/pandas-dev/pandas/pulls/34500
2020-05-31T16:58:23Z
2020-06-12T18:17:07Z
2020-06-12T18:17:07Z
2020-06-12T22:33:50Z
REF/PERF: PeriodDtype decouple from DateOffset
diff --git a/pandas/_libs/tslibs/dtypes.pxd b/pandas/_libs/tslibs/dtypes.pxd new file mode 100644 index 0000000000000..23c473726e5a9 --- /dev/null +++ b/pandas/_libs/tslibs/dtypes.pxd @@ -0,0 +1,56 @@ + +cdef enum PeriodDtypeCode: + # Annual freqs with various fiscal year ends. + # eg, 2005 for A_FEB runs Mar 1, 2004 to Feb 28, 2005 + A = 1000 # Default alias + A_DEC = 1000 # Annual - December year end + A_JAN = 1001 # Annual - January year end + A_FEB = 1002 # Annual - February year end + A_MAR = 1003 # Annual - March year end + A_APR = 1004 # Annual - April year end + A_MAY = 1005 # Annual - May year end + A_JUN = 1006 # Annual - June year end + A_JUL = 1007 # Annual - July year end + A_AUG = 1008 # Annual - August year end + A_SEP = 1009 # Annual - September year end + A_OCT = 1010 # Annual - October year end + A_NOV = 1011 # Annual - November year end + + # Quarterly frequencies with various fiscal year ends. + # eg, Q42005 for Q_OCT runs Aug 1, 2005 to Oct 31, 2005 + Q_DEC = 2000 # Quarterly - December year end + Q_JAN = 2001 # Quarterly - January year end + Q_FEB = 2002 # Quarterly - February year end + Q_MAR = 2003 # Quarterly - March year end + Q_APR = 2004 # Quarterly - April year end + Q_MAY = 2005 # Quarterly - May year end + Q_JUN = 2006 # Quarterly - June year end + Q_JUL = 2007 # Quarterly - July year end + Q_AUG = 2008 # Quarterly - August year end + Q_SEP = 2009 # Quarterly - September year end + Q_OCT = 2010 # Quarterly - October year end + Q_NOV = 2011 # Quarterly - November year end + + M = 3000 # Monthly + + W_SUN = 4000 # Weekly - Sunday end of week + W_MON = 4001 # Weekly - Monday end of week + W_TUE = 4002 # Weekly - Tuesday end of week + W_WED = 4003 # Weekly - Wednesday end of week + W_THU = 4004 # Weekly - Thursday end of week + W_FRI = 4005 # Weekly - Friday end of week + W_SAT = 4006 # Weekly - Saturday end of week + + B = 5000 # Business days + D = 6000 # Daily + H = 7000 # Hourly + T = 8000 # Minutely + S = 9000 # Secondly + L = 10000 # Millisecondly + U = 11000 # Microsecondly + N = 12000 # Nanosecondly + + +cdef class PeriodPseudoDtype: + cdef readonly: + PeriodDtypeCode dtype_code diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx new file mode 100644 index 0000000000000..d0d4e579a456b --- /dev/null +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -0,0 +1,108 @@ +# period frequency constants corresponding to scikits timeseries +# originals + + +cdef class PeriodPseudoDtype: + """ + Similar to an actual dtype, this contains all of the information + describing a PeriodDtype in an integer code. + """ + # cdef readonly: + # PeriodDtypeCode dtype_code + + def __cinit__(self, PeriodDtypeCode code): + self.dtype_code = code + + def __eq__(self, other): + if not isinstance(other, PeriodPseudoDtype): + return False + if not isinstance(self, PeriodPseudoDtype): + # cython semantics, this is a reversed op + return False + return self.dtype_code == other.dtype_code + + @property + def date_offset(self): + """ + Corresponding DateOffset object. + + This mapping is mainly for backward-compatibility. + """ + from .offsets import to_offset + + freqstr = _reverse_period_code_map.get(self.dtype_code) + # equiv: freqstr = libfrequencies.get_freq_str(self.dtype_code) + + return to_offset(freqstr) + + @classmethod + def from_date_offset(cls, offset): + code = offset._period_dtype_code + return cls(code) + + +_period_code_map = { + # Annual freqs with various fiscal year ends. + # eg, 2005 for A-FEB runs Mar 1, 2004 to Feb 28, 2005 + "A-DEC": 1000, # Annual - December year end + "A-JAN": 1001, # Annual - January year end + "A-FEB": 1002, # Annual - February year end + "A-MAR": 1003, # Annual - March year end + "A-APR": 1004, # Annual - April year end + "A-MAY": 1005, # Annual - May year end + "A-JUN": 1006, # Annual - June year end + "A-JUL": 1007, # Annual - July year end + "A-AUG": 1008, # Annual - August year end + "A-SEP": 1009, # Annual - September year end + "A-OCT": 1010, # Annual - October year end + "A-NOV": 1011, # Annual - November year end + + # Quarterly frequencies with various fiscal year ends. + # eg, Q42005 for Q-OCT runs Aug 1, 2005 to Oct 31, 2005 + "Q-DEC": 2000, # Quarterly - December year end + "Q-JAN": 2001, # Quarterly - January year end + "Q-FEB": 2002, # Quarterly - February year end + "Q-MAR": 2003, # Quarterly - March year end + "Q-APR": 2004, # Quarterly - April year end + "Q-MAY": 2005, # Quarterly - May year end + "Q-JUN": 2006, # Quarterly - June year end + "Q-JUL": 2007, # Quarterly - July year end + "Q-AUG": 2008, # Quarterly - August year end + "Q-SEP": 2009, # Quarterly - September year end + "Q-OCT": 2010, # Quarterly - October year end + "Q-NOV": 2011, # Quarterly - November year end + + "M": 3000, # Monthly + + "W-SUN": 4000, # Weekly - Sunday end of week + "W-MON": 4001, # Weekly - Monday end of week + "W-TUE": 4002, # Weekly - Tuesday end of week + "W-WED": 4003, # Weekly - Wednesday end of week + "W-THU": 4004, # Weekly - Thursday end of week + "W-FRI": 4005, # Weekly - Friday end of week + "W-SAT": 4006, # Weekly - Saturday end of week + + "B": 5000, # Business days + "D": 6000, # Daily + "H": 7000, # Hourly + "T": 8000, # Minutely + "S": 9000, # Secondly + "L": 10000, # Millisecondly + "U": 11000, # Microsecondly + "N": 12000, # Nanosecondly +} + +_reverse_period_code_map = { + _period_code_map[key]: key for key in _period_code_map} + +# Yearly aliases; careful not to put these in _reverse_period_code_map +_period_code_map.update({"Y" + key[1:]: _period_code_map[key] + for key in _period_code_map + if key.startswith("A-")}) + +_period_code_map.update({ + "Q": 2000, # Quarterly - December year end (default quarterly) + "A": 1000, # Annual + "W": 4000, # Weekly + "C": 5000, # Custom Business Day +}) diff --git a/pandas/_libs/tslibs/frequencies.pyx b/pandas/_libs/tslibs/frequencies.pyx index 8246e24319dbd..8ca442de59f9f 100644 --- a/pandas/_libs/tslibs/frequencies.pyx +++ b/pandas/_libs/tslibs/frequencies.pyx @@ -12,6 +12,8 @@ from pandas._libs.tslibs.offsets import ( opattern, ) +from .dtypes import _period_code_map, _reverse_period_code_map + # --------------------------------------------------------------------- # Period codes @@ -31,73 +33,6 @@ class FreqGroup: FR_NS = 12000 -# period frequency constants corresponding to scikits timeseries -# originals -_period_code_map = { - # Annual freqs with various fiscal year ends. - # eg, 2005 for A-FEB runs Mar 1, 2004 to Feb 28, 2005 - "A-DEC": 1000, # Annual - December year end - "A-JAN": 1001, # Annual - January year end - "A-FEB": 1002, # Annual - February year end - "A-MAR": 1003, # Annual - March year end - "A-APR": 1004, # Annual - April year end - "A-MAY": 1005, # Annual - May year end - "A-JUN": 1006, # Annual - June year end - "A-JUL": 1007, # Annual - July year end - "A-AUG": 1008, # Annual - August year end - "A-SEP": 1009, # Annual - September year end - "A-OCT": 1010, # Annual - October year end - "A-NOV": 1011, # Annual - November year end - - # Quarterly frequencies with various fiscal year ends. - # eg, Q42005 for Q-OCT runs Aug 1, 2005 to Oct 31, 2005 - "Q-DEC": 2000, # Quarterly - December year end - "Q-JAN": 2001, # Quarterly - January year end - "Q-FEB": 2002, # Quarterly - February year end - "Q-MAR": 2003, # Quarterly - March year end - "Q-APR": 2004, # Quarterly - April year end - "Q-MAY": 2005, # Quarterly - May year end - "Q-JUN": 2006, # Quarterly - June year end - "Q-JUL": 2007, # Quarterly - July year end - "Q-AUG": 2008, # Quarterly - August year end - "Q-SEP": 2009, # Quarterly - September year end - "Q-OCT": 2010, # Quarterly - October year end - "Q-NOV": 2011, # Quarterly - November year end - - "M": 3000, # Monthly - - "W-SUN": 4000, # Weekly - Sunday end of week - "W-MON": 4001, # Weekly - Monday end of week - "W-TUE": 4002, # Weekly - Tuesday end of week - "W-WED": 4003, # Weekly - Wednesday end of week - "W-THU": 4004, # Weekly - Thursday end of week - "W-FRI": 4005, # Weekly - Friday end of week - "W-SAT": 4006, # Weekly - Saturday end of week - - "B": 5000, # Business days - "D": 6000, # Daily - "H": 7000, # Hourly - "T": 8000, # Minutely - "S": 9000, # Secondly - "L": 10000, # Millisecondly - "U": 11000, # Microsecondly - "N": 12000} # Nanosecondly - - -_reverse_period_code_map = { - _period_code_map[key]: key for key in _period_code_map} - -# Yearly aliases; careful not to put these in _reverse_period_code_map -_period_code_map.update({'Y' + key[1:]: _period_code_map[key] - for key in _period_code_map - if key.startswith('A-')}) - -_period_code_map.update({ - "Q": 2000, # Quarterly - December year end (default quarterly) - "A": 1000, # Annual - "W": 4000, # Weekly - "C": 5000}) # Custom Business Day - # Map attribute-name resolutions to resolution abbreviations _attrname_to_abbrevs = { "year": "A", diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 77b60d0c22322..63dc3407b4c55 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -48,6 +48,7 @@ from pandas._libs.tslibs.np_datetime cimport ( from pandas._libs.tslibs.timezones cimport utc_pytz as UTC from pandas._libs.tslibs.tzconversion cimport tz_convert_single +from .dtypes cimport PeriodDtypeCode from .timedeltas cimport delta_to_nanoseconds @@ -892,36 +893,43 @@ cdef class Tick(SingleConstructorOffset): cdef class Day(Tick): _nanos_inc = 24 * 3600 * 1_000_000_000 _prefix = "D" + _period_dtype_code = PeriodDtypeCode.D cdef class Hour(Tick): _nanos_inc = 3600 * 1_000_000_000 _prefix = "H" + _period_dtype_code = PeriodDtypeCode.H cdef class Minute(Tick): _nanos_inc = 60 * 1_000_000_000 _prefix = "T" + _period_dtype_code = PeriodDtypeCode.T cdef class Second(Tick): _nanos_inc = 1_000_000_000 _prefix = "S" + _period_dtype_code = PeriodDtypeCode.S cdef class Milli(Tick): _nanos_inc = 1_000_000 _prefix = "L" + _period_dtype_code = PeriodDtypeCode.L cdef class Micro(Tick): _nanos_inc = 1000 _prefix = "U" + _period_dtype_code = PeriodDtypeCode.U cdef class Nano(Tick): _nanos_inc = 1 _prefix = "N" + _period_dtype_code = PeriodDtypeCode.N def delta_to_tick(delta: timedelta) -> Tick: @@ -1281,7 +1289,7 @@ cdef class BusinessDay(BusinessMixin): """ DateOffset subclass representing possibly n business days. """ - + _period_dtype_code = PeriodDtypeCode.B _prefix = "B" _attributes = tuple(["n", "normalize", "offset"]) @@ -1945,6 +1953,15 @@ cdef class YearEnd(YearOffset): _prefix = "A" _day_opt = "end" + cdef readonly: + int _period_dtype_code + + def __init__(self, n=1, normalize=False, month=None): + # Because YearEnd can be the freq for a Period, define its + # _period_dtype_code at construction for performance + YearOffset.__init__(self, n, normalize, month) + self._period_dtype_code = PeriodDtypeCode.A + self.month % 12 + cdef class YearBegin(YearOffset): """ @@ -2099,6 +2116,14 @@ cdef class QuarterEnd(QuarterOffset): _prefix = "Q" _day_opt = "end" + cdef readonly: + int _period_dtype_code + + def __init__(self, n=1, normalize=False, startingMonth=None): + # Because QuarterEnd can be the freq for a Period, define its + # _period_dtype_code at construction for performance + QuarterOffset.__init__(self, n, normalize, startingMonth) + self._period_dtype_code = PeriodDtypeCode.Q_DEC + self.startingMonth % 12 cdef class QuarterBegin(QuarterOffset): """ @@ -2148,6 +2173,7 @@ cdef class MonthEnd(MonthOffset): """ DateOffset of one month end. """ + _period_dtype_code = PeriodDtypeCode.M _prefix = "M" _day_opt = "end" @@ -2452,6 +2478,7 @@ cdef class Week(SingleConstructorOffset): cdef readonly: object weekday # int or None + int _period_dtype_code def __init__(self, n=1, normalize=False, weekday=None): BaseOffset.__init__(self, n, normalize) @@ -2461,6 +2488,8 @@ cdef class Week(SingleConstructorOffset): if self.weekday < 0 or self.weekday > 6: raise ValueError(f"Day must be 0<=day<=6, got {self.weekday}") + self._period_dtype_code = PeriodDtypeCode.W_SUN + (weekday + 1) % 7 + cpdef __setstate__(self, state): self.n = state.pop("n") self.normalize = state.pop("normalize") diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 14cce1c000207..e88a20bc549bd 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -55,6 +55,9 @@ from pandas._libs.tslibs.ccalendar cimport ( get_days_in_month, ) from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS + +from pandas._libs.tslibs.dtypes cimport PeriodPseudoDtype + from pandas._libs.tslibs.frequencies cimport ( attrname_to_abbrevs, get_freq_code, @@ -1514,11 +1517,16 @@ cdef class _Period: cdef readonly: int64_t ordinal + PeriodPseudoDtype _dtype BaseOffset freq def __cinit__(self, int64_t ordinal, BaseOffset freq): self.ordinal = ordinal self.freq = freq + # Note: this is more performant than PeriodDtype.from_date_offset(freq) + # because from_date_offset cannot be made a cdef method (until cython + # supported cdef classmethods) + self._dtype = PeriodPseudoDtype(freq._period_dtype_code) @classmethod def _maybe_convert_freq(cls, object freq): @@ -1662,13 +1670,13 @@ cdef class _Period: """ freq = self._maybe_convert_freq(freq) how = validate_end_alias(how) - base1, mult1 = get_freq_code(self.freq) - base2, mult2 = get_freq_code(freq) + base1 = self._dtype.dtype_code + base2, _ = get_freq_code(freq) - # mult1 can't be negative or 0 + # self.n can't be negative or 0 end = how == 'E' if end: - ordinal = self.ordinal + mult1 - 1 + ordinal = self.ordinal + self.freq.n - 1 else: ordinal = self.ordinal ordinal = period_asfreq(ordinal, base1, base2, end) @@ -1751,12 +1759,12 @@ cdef class _Period: return endpoint - Timedelta(1, 'ns') if freq is None: - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code freq = get_to_timestamp_base(base) else: freq = self._maybe_convert_freq(freq) - base, mult = get_freq_code(freq) + base, _ = get_freq_code(freq) val = self.asfreq(freq, how) dt64 = period_ordinal_to_dt64(val.ordinal, base) @@ -1764,12 +1772,12 @@ cdef class _Period: @property def year(self) -> int: - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pyear(self.ordinal, base) @property def month(self) -> int: - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pmonth(self.ordinal, base) @property @@ -1792,7 +1800,7 @@ cdef class _Period: >>> p.day 11 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pday(self.ordinal, base) @property @@ -1822,7 +1830,7 @@ cdef class _Period: >>> p.hour 0 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return phour(self.ordinal, base) @property @@ -1846,7 +1854,7 @@ cdef class _Period: >>> p.minute 3 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pminute(self.ordinal, base) @property @@ -1870,12 +1878,12 @@ cdef class _Period: >>> p.second 12 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return psecond(self.ordinal, base) @property def weekofyear(self) -> int: - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pweek(self.ordinal, base) @property @@ -1956,7 +1964,7 @@ cdef class _Period: >>> per.end_time.dayofweek 2 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pweekday(self.ordinal, base) @property @@ -2044,12 +2052,12 @@ cdef class _Period: >>> period.dayofyear 1 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pday_of_year(self.ordinal, base) @property def quarter(self) -> int: - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pquarter(self.ordinal, base) @property @@ -2093,7 +2101,7 @@ cdef class _Period: >>> per.year 2017 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pqyear(self.ordinal, base) @property @@ -2127,7 +2135,7 @@ cdef class _Period: >>> p.days_in_month 29 """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return pdays_in_month(self.ordinal, base) @property @@ -2165,7 +2173,7 @@ cdef class _Period: return self.freq.freqstr def __repr__(self) -> str: - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code formatted = period_format(self.ordinal, base) return f"Period('{formatted}', '{self.freqstr}')" @@ -2173,7 +2181,7 @@ cdef class _Period: """ Return a string representation for a particular DataFrame """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code formatted = period_format(self.ordinal, base) value = str(formatted) return value @@ -2325,7 +2333,7 @@ cdef class _Period: >>> a.strftime('%b. %d, %Y was a %A') 'Jan. 01, 2001 was a Monday' """ - base, mult = get_freq_code(self.freq) + base = self._dtype.dtype_code return period_format(self.ordinal, base, fmt) diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index bbabfed4cb976..b0c524a257684 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -9,6 +9,7 @@ def test_namespace(): "base", "ccalendar", "conversion", + "dtypes", "fields", "frequencies", "nattype", diff --git a/setup.py b/setup.py index 63510867f0dd7..9f411ec10cd80 100755 --- a/setup.py +++ b/setup.py @@ -308,8 +308,8 @@ class CheckSDist(sdist_class): "pandas/_libs/ops.pyx", "pandas/_libs/parsers.pyx", "pandas/_libs/tslibs/base.pyx", - "pandas/_libs/tslibs/c_timestamp.pyx", "pandas/_libs/tslibs/ccalendar.pyx", + "pandas/_libs/tslibs/dtypes.pyx", "pandas/_libs/tslibs/period.pyx", "pandas/_libs/tslibs/strptime.pyx", "pandas/_libs/tslibs/np_datetime.pyx", @@ -605,6 +605,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "_libs.tslib": {"pyxfile": "_libs/tslib", "depends": tseries_depends}, "_libs.tslibs.base": {"pyxfile": "_libs/tslibs/base"}, "_libs.tslibs.ccalendar": {"pyxfile": "_libs/tslibs/ccalendar"}, + "_libs.tslibs.dtypes": {"pyxfile": "_libs/tslibs/dtypes"}, "_libs.tslibs.conversion": { "pyxfile": "_libs/tslibs/conversion", "depends": tseries_depends,
ATM we define PeriodDtype in terms of DateOffsets, but this is a misnomer. In fact, virtually every Period/PeriodArray method has to start off by taking its `.freq` and finding the corresponding integer code. This makes the integer code itself into a dtype. We lose a little bit of ground on the constructor, then make it back up in subsequent calls. ``` In [2]: per = pd.Period("2016Q1") In [3]: %timeit per.year 556 ns ± 13.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master 94.5 ns ± 1.36 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR In [4]: %timeit pd.Period("2016Q1") 21.2 µs ± 176 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- master 25.8 µs ± 457 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) # <-- PR ``` The constructor perf I think we can improve by eventually cutting the DateOffset out of the process altogether. We'll also be able to de-duplicate a _bunch_ of other stuff: FreqGroup can be defined in terms of PeriodDypeCode, Resolution can be defined in terms of FreqGroup (xref #34462), we can avoid redundant definitions of the dtype codes in period.pyx, and a lot of the rest of libfrequencies becomes unnecessary. In a follow-up I plan to mix the cython-space PeriodDtype into the core.dtypes PeriodDtype and we can get the same perf improvements in the PeriodArray methods.
https://api.github.com/repos/pandas-dev/pandas/pulls/34499
2020-05-31T15:49:01Z
2020-06-04T05:51:16Z
2020-06-04T05:51:16Z
2020-06-04T16:50:19Z
Test for pd.to_sql column error if data contains -np.inf
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 0ca19ffd1f496..3767c8f23f62d 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1044,6 +1044,7 @@ I/O - Bug in :meth:`HDFStore.append_to_multiple` was raising a ``ValueError`` when the min_itemsize parameter is set (:issue:`11238`) - Bug in :meth:`~HDFStore.create_table` now raises an error when `column` argument was not specified in `data_columns` on input (:issue:`28156`) - :meth:`read_json` now could read line-delimited json file from a file url while `lines` and `chunksize` are set. +- Bug in :meth:`DataFrame.to_sql` when reading DataFrames with ``-np.inf`` entries with MySQL now has a more explicit ``ValueError`` (:issue:`34431`) Plotting ^^^^^^^^ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index b137608475b3d..9177696ca13d6 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1391,7 +1391,20 @@ def to_sql( dtype=dtype, ) table.create() - table.insert(chunksize, method=method) + + from sqlalchemy import exc + + try: + table.insert(chunksize, method=method) + except exc.SQLAlchemyError as err: + # GH34431 + msg = "(1054, \"Unknown column 'inf' in 'field list'\")" + err_text = str(err.orig) + if re.search(msg, err_text): + raise ValueError("inf cannot be used with MySQL") from err + else: + raise err + if not name.isdigit() and not name.islower(): # check for potentially case sensitivity issues (GH7815) # Only check when name is not a number and name is not lower case diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index a07e7a74b7573..0991fae39138e 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1813,6 +1813,24 @@ def main(connectable): DataFrame({"test_foo_data": [0, 1, 2]}).to_sql("test_foo_data", self.conn) main(self.conn) + @pytest.mark.parametrize( + "input", + [{"foo": [np.inf]}, {"foo": [-np.inf]}, {"foo": [-np.inf], "infe0": ["bar"]}], + ) + def test_to_sql_with_negative_npinf(self, input): + # GH 34431 + + df = pd.DataFrame(input) + + if self.flavor == "mysql": + msg = "inf cannot be used with MySQL" + with pytest.raises(ValueError, match=msg): + df.to_sql("foobar", self.conn, index=False) + else: + df.to_sql("foobar", self.conn, index=False) + res = sql.read_sql_table("foobar", self.conn) + tm.assert_equal(df, res) + def test_temporary_table(self): test_data = "Hello, World!" expected = DataFrame({"spam": [test_data]})
- [x] closes #34431 - [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/34493
2020-05-31T03:31:31Z
2020-07-01T18:28:31Z
2020-07-01T18:28:31Z
2020-07-01T18:28:50Z
CLN: remove unused JsonReader.path_or_buf
diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index ac6f9ff372601..72aa8fdd16e6d 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -639,7 +639,6 @@ def __init__( compression, ): - self.path_or_buf = filepath_or_buffer self.orient = orient self.typ = typ self.dtype = dtype
- [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/34492
2020-05-31T01:53:57Z
2020-05-31T21:30:38Z
2020-05-31T21:30:38Z
2020-05-31T22:04:02Z
CLN: de-duplicate bits lib timestamps
diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 48c4afe7d4c1b..4e377656f213f 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -25,7 +25,7 @@ from pandas._libs.tslibs.util cimport ( is_timedelta64_object, is_array, ) -from pandas._libs.tslibs.base cimport ABCTimedelta, ABCTimestamp +from pandas._libs.tslibs.base cimport ABCTimestamp from pandas._libs.tslibs cimport ccalendar @@ -41,6 +41,7 @@ from pandas._libs.tslibs.np_datetime cimport ( ) from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime from pandas._libs.tslibs.offsets cimport to_offset, is_tick_object, is_offset_object +from pandas._libs.tslibs.timedeltas cimport is_any_td_scalar, delta_to_nanoseconds from pandas._libs.tslibs.timedeltas import Timedelta from pandas._libs.tslibs.timezones cimport ( is_utc, maybe_get_tz, treat_tz_as_pytz, utc_pytz as UTC, @@ -344,37 +345,15 @@ cdef class _Timestamp(ABCTimestamp): def __add__(self, other): cdef: - int64_t other_int, nanos = 0 - - if is_timedelta64_object(other): - other_int = other.astype('timedelta64[ns]').view('i8') - return type(self)(self.value + other_int, tz=self.tzinfo, freq=self.freq) - - elif is_integer_object(other): - raise integer_op_not_supported(self) - - elif PyDelta_Check(other): - # logic copied from delta_to_nanoseconds to prevent circular import - if isinstance(other, ABCTimedelta): - # pd.Timedelta - nanos = other.value - else: - nanos = (other.days * 24 * 60 * 60 * 1000000 + - other.seconds * 1000000 + - other.microseconds) * 1000 + int64_t nanos = 0 + if is_any_td_scalar(other): + nanos = delta_to_nanoseconds(other) result = type(self)(self.value + nanos, tz=self.tzinfo, freq=self.freq) return result - elif is_tick_object(other): - try: - nanos = other.nanos - except OverflowError as err: - raise OverflowError( - f"the add operation between {other} and {self} will overflow" - ) from err - result = type(self)(self.value + nanos, tz=self.tzinfo, freq=self.freq) - return result + elif is_integer_object(other): + raise integer_op_not_supported(self) elif is_array(other): if other.dtype.kind in ['i', 'u']: @@ -395,8 +374,7 @@ cdef class _Timestamp(ABCTimestamp): def __sub__(self, other): - if (is_timedelta64_object(other) or is_integer_object(other) or - PyDelta_Check(other) or is_tick_object(other)): + if is_any_td_scalar(other) or is_integer_object(other): neg_other = -other return self + neg_other @@ -434,7 +412,6 @@ cdef class _Timestamp(ABCTimestamp): # scalar Timestamp/datetime - Timestamp/datetime -> yields a # Timedelta - from pandas._libs.tslibs.timedeltas import Timedelta try: return Timedelta(self.value - other.value) except (OverflowError, OutOfBoundsDatetime) as err: diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index ed0045bcab989..eb9932f9a3a97 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -38,14 +38,17 @@ def test_overflow_offset_raises(self): r"\<-?\d+ \* Days\> and \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} " "will overflow" ) + lmsg = "|".join( + ["Python int too large to convert to C long", "int too big to convert"] + ) - with pytest.raises(OverflowError, match=msg): + with pytest.raises(OverflowError, match=lmsg): stamp + offset_overflow with pytest.raises(OverflowError, match=msg): offset_overflow + stamp - with pytest.raises(OverflowError, match=msg): + with pytest.raises(OverflowError, match=lmsg): stamp - offset_overflow # xref https://github.com/pandas-dev/pandas/issues/14080 @@ -54,13 +57,13 @@ def test_overflow_offset_raises(self): stamp = Timestamp("2000/1/1") offset_overflow = to_offset("D") * 100 ** 5 - with pytest.raises(OverflowError, match=msg): + with pytest.raises(OverflowError, match=lmsg): stamp + offset_overflow with pytest.raises(OverflowError, match=msg): offset_overflow + stamp - with pytest.raises(OverflowError, match=msg): + with pytest.raises(OverflowError, match=lmsg): stamp - offset_overflow def test_overflow_timestamp_raises(self):
- [ ] 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/34491
2020-05-31T00:50:29Z
2020-05-31T22:20:10Z
2020-05-31T22:20:10Z
2020-05-31T22:32:59Z
DOC: Added documentation for building using pyenv
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index d02896f777348..3022609f976c6 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -270,7 +270,7 @@ Creating a Python environment (pip) If you aren't using conda for your development environment, follow these instructions. You'll need to have at least Python 3.6.1 installed on your system. -**Unix**/**Mac OS** +**Unix**/**Mac OS with virtualenv** .. code-block:: bash @@ -286,7 +286,31 @@ You'll need to have at least Python 3.6.1 installed on your system. python -m pip install -r requirements-dev.txt # Build and install pandas - python setup.py build_ext --inplace -j 0 + python setup.py build_ext --inplace -j 4 + python -m pip install -e . --no-build-isolation --no-use-pep517 + +**Unix**/**Mac OS with pyenv** + +Consult the docs for setting up pyenv `here <https://github.com/pyenv/pyenv>`__. + +.. code-block:: bash + + # Create a virtual environment + # Use an ENV_DIR of your choice. We'll use ~/Users/<yourname>/.pyenv/versions/pandas-dev + + pyenv virtualenv <version> <name-to-give-it> + + # For instance: + pyenv virtualenv 3.7.6 pandas-dev + + # Activate the virtualenv + pyenv activate pandas-dev + + # Now install the build dependencies in the cloned pandas repo + python -m pip install -r requirements-dev.txt + + # Build and install pandas + python setup.py build_ext --inplace -j 4 python -m pip install -e . --no-build-isolation --no-use-pep517 **Windows** @@ -312,7 +336,7 @@ should already exist. python -m pip install -r requirements-dev.txt # Build and install pandas - python setup.py build_ext --inplace -j 0 + python setup.py build_ext --inplace -j 4 python -m pip install -e . --no-build-isolation --no-use-pep517 Creating a branch
Added documentation for building using pyenv. Discussed this PR with @WillAyd on gitter on May 20. Also fixed up another line he mentioned (python setup.py build_ext --inplace -j 4 instead of: python setup.py build_ext --inplace -j 0) for conda/venv/pyenv. Have rebuilt the docs and ensured they build properly.
https://api.github.com/repos/pandas-dev/pandas/pulls/34490
2020-05-30T20:52:29Z
2020-06-07T20:09:52Z
2020-06-07T20:09:52Z
2020-06-07T20:10:05Z
BUG: Raise ValueError for non numerical join columns in merge_asof
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index b4b98ec0403a8..84f1fa6ad8086 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -302,8 +302,7 @@ Reshaping - Bug in :meth:`DataFrame.unstack` with missing levels led to incorrect index names (:issue:`37510`) - Bug in :func:`join` over :class:`MultiIndex` returned wrong result, when one of both indexes had only one level (:issue:`36909`) - Bug in :func:`concat` incorrectly casting to ``object`` dtype in some cases when one or more of the operands is empty (:issue:`38843`, :issue:`38907`) -- - +- :meth:`merge_asof` raises ``ValueError`` instead of cryptic ``TypeError`` in case of non-numerical merge columns (:issue:`29130`) Sparse ^^^^^^ diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index ac5fc7cddf82a..1caf1a2a023da 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1708,6 +1708,23 @@ def _validate_specification(self): if self.left_by is not None and self.right_by is None: raise MergeError("missing right_by") + # GH#29130 Check that merge keys do not have dtype object + lo_dtype = ( + self.left[self.left_on[0]].dtype + if not self.left_index + else self.left.index.dtype + ) + ro_dtype = ( + self.right[self.right_on[0]].dtype + if not self.right_index + else self.right.index.dtype + ) + if is_object_dtype(lo_dtype) or is_object_dtype(ro_dtype): + raise MergeError( + f"Incompatible merge dtype, {repr(ro_dtype)} and " + f"{repr(lo_dtype)}, both sides must have numeric dtype" + ) + # add 'by' to our key-list so we can have it in the # output as a key if self.left_by is not None: diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index 5cb7bdd603517..ecff63b495fbb 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -1168,7 +1168,7 @@ def test_on_float_by_int(self): tm.assert_frame_equal(result, expected) def test_merge_datatype_error_raises(self): - msg = r"incompatible merge keys \[0\] .*, must be the same type" + msg = r"Incompatible merge dtype, .*, both sides must have numeric dtype" left = pd.DataFrame({"left_val": [1, 5, 10], "a": ["a", "b", "c"]}) right = pd.DataFrame({"right_val": [1, 2, 3, 6, 7], "a": [1, 2, 3, 6, 7]}) @@ -1373,3 +1373,39 @@ def test_left_index_right_index_tolerance(self): tolerance=Timedelta(seconds=0.5), ) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "kwargs", [{"on": "x"}, {"left_index": True, "right_index": True}] +) +@pytest.mark.parametrize( + "data", + [["2019-06-01 00:09:12", "2019-06-01 00:10:29"], [1.0, "2019-06-01 00:10:29"]], +) +def test_merge_asof_non_numerical_dtype(kwargs, data): + # GH#29130 + left = pd.DataFrame({"x": data}, index=data) + right = pd.DataFrame({"x": data}, index=data) + with pytest.raises( + MergeError, + match=r"Incompatible merge dtype, .*, both sides must have numeric dtype", + ): + pd.merge_asof(left, right, **kwargs) + + +def test_merge_asof_non_numerical_dtype_object(): + # GH#29130 + left = pd.DataFrame({"a": ["12", "13", "15"], "left_val1": ["a", "b", "c"]}) + right = pd.DataFrame({"a": ["a", "b", "c"], "left_val": ["d", "e", "f"]}) + with pytest.raises( + MergeError, + match=r"Incompatible merge dtype, .*, both sides must have numeric dtype", + ): + pd.merge_asof( + left, + right, + left_on="left_val1", + right_on="a", + left_by="a", + right_by="left_val", + )
- [x] closes #29130 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry I checked for dtype object. Normally, I would try to check for allowed dtypes, but that would require a lot of dtype checks instead of only one. I hope object dtype is sufficient to exclude
https://api.github.com/repos/pandas-dev/pandas/pulls/34488
2020-05-30T19:57:50Z
2021-01-06T00:16:29Z
2021-01-06T00:16:28Z
2021-07-25T21:58:03Z
TST, TYP: _use_dynamic_x
diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 9d8c26093296e..475452c71db58 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -7,6 +7,7 @@ from pandas._libs.tslibs import Period, to_offset from pandas._libs.tslibs.frequencies import FreqGroup, base_and_stride, get_freq_code +from pandas._typing import FrameOrSeriesUnion from pandas.core.dtypes.generic import ( ABCDatetimeIndex, @@ -192,7 +193,7 @@ def _get_freq(ax, series: "Series"): return freq, ax_freq -def _use_dynamic_x(ax, data): +def _use_dynamic_x(ax, data: "FrameOrSeriesUnion") -> bool: freq = _get_index_freq(data.index) ax_freq = _get_ax_freq(ax) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 7dcb692e29337..738df5244955a 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -16,7 +16,7 @@ from pandas.core.resample import DatetimeIndex from pandas.tests.plotting.common import TestPlotBase -from pandas.tseries.offsets import DateOffset +from pandas.tseries.offsets import DateOffset, WeekOfMonth @td.skip_if_no_mpl @@ -325,6 +325,18 @@ def test_business_freq_convert(self): idx = ax.get_lines()[0].get_xdata() assert PeriodIndex(data=idx).freqstr == "M" + def test_freq_with_no_period_alias(self): + # GH34487 + freq = WeekOfMonth() + bts = tm.makeTimeSeries(5).asfreq(freq) + _, ax = self.plt.subplots() + bts.plot(ax=ax) + assert ax.get_lines()[0].get_xydata()[0, 0] == bts.index[0].toordinal() + idx = ax.get_lines()[0].get_xdata() + msg = "freq not specified and cannot be inferred" + with pytest.raises(ValueError, match=msg): + PeriodIndex(data=idx) + def test_nonzero_base(self): # GH2571 idx = date_range("2012-12-20", periods=24, freq="H") + timedelta(minutes=30)
This condition (which, from the current plotting test suite, is unreachable) was introduced in #9814, when `_use_dynamic_x` was written. Is there any reason why `get_period_alias(freq)` would return `None` if `freq` is a valid time frequency? If so, I'll add a test - else, this PR removes unreachable code. Added an annotation for `data` and the return type while I was here - is there a way to annotate `ax`? UPDATE ------ As it turns out (thanks jbrockmendel and jorisvandenbossche), this line can be hit, so I've included a test which does
https://api.github.com/repos/pandas-dev/pandas/pulls/34487
2020-05-30T18:54:09Z
2020-06-04T19:37:09Z
2020-06-04T19:37:09Z
2020-06-04T19:52:48Z
ENH: mul(Tick, float); simplify to_offset
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 88bf0e005a221..77adf6dfe53a9 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -994,6 +994,7 @@ Other - Bug in :meth:`DataFrame.plot.scatter` caused an error when plotting variable marker sizes (:issue:`32904`) - :class:`IntegerArray` now implements the ``sum`` operation (:issue:`33172`) - Bug in :class:`Tick` comparisons raising ``TypeError`` when comparing against timedelta-like objects (:issue:`34088`) +- Bug in :class:`Tick` multiplication raising ``TypeError`` when multiplying by a float (:issue:`34486`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 7f7dd62540387..0caacd81c53f5 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -25,7 +25,11 @@ cnp.import_array() from pandas._libs.properties import cache_readonly from pandas._libs.tslibs cimport util -from pandas._libs.tslibs.util cimport is_integer_object, is_datetime64_object +from pandas._libs.tslibs.util cimport ( + is_integer_object, + is_datetime64_object, + is_float_object, +) from pandas._libs.tslibs.base cimport ABCTimestamp @@ -743,6 +747,25 @@ cdef class Tick(SingleConstructorOffset): "Tick offset with `normalize=True` are not allowed." ) + # FIXME: Without making this cpdef, we get AttributeError when calling + # from __mul__ + cpdef Tick _next_higher_resolution(Tick self): + if type(self) is Day: + return Hour(self.n * 24) + if type(self) is Hour: + return Minute(self.n * 60) + if type(self) is Minute: + return Second(self.n * 60) + if type(self) is Second: + return Milli(self.n * 1000) + if type(self) is Milli: + return Micro(self.n * 1000) + if type(self) is Micro: + return Nano(self.n * 1000) + raise NotImplementedError(type(self)) + + # -------------------------------------------------------------------- + def _repr_attrs(self) -> str: # Since cdef classes have no __dict__, we need to override return "" @@ -791,6 +814,21 @@ cdef class Tick(SingleConstructorOffset): def __gt__(self, other): return self.delta.__gt__(other) + def __mul__(self, other): + if not isinstance(self, Tick): + # cython semantics, this is __rmul__ + return other.__mul__(self) + if is_float_object(other): + n = other * self.n + # If the new `n` is an integer, we can represent it using the + # same Tick subclass as self, otherwise we need to move up + # to a higher-resolution subclass + if np.isclose(n % 1, 0): + return type(self)(int(n)) + new_self = self._next_higher_resolution() + return new_self * other + return BaseOffset.__mul__(self, other) + def __truediv__(self, other): if not isinstance(self, Tick): # cython semantics mean the args are sometimes swapped @@ -3563,6 +3601,9 @@ cpdef to_offset(freq): >>> to_offset(Hour()) <Hour> """ + # TODO: avoid runtime imports + from pandas._libs.tslibs.timedeltas import Timedelta + if freq is None: return None @@ -3589,7 +3630,9 @@ cpdef to_offset(freq): if split[-1] != "" and not split[-1].isspace(): # the last element must be blank raise ValueError("last element must be blank") - for sep, stride, name in zip(split[0::4], split[1::4], split[2::4]): + + tups = zip(split[0::4], split[1::4], split[2::4]) + for n, (sep, stride, name) in enumerate(tups): if sep != "" and not sep.isspace(): raise ValueError("separator must be spaces") prefix = _lite_rule_alias.get(name) or name @@ -3598,16 +3641,22 @@ cpdef to_offset(freq): if not stride: stride = 1 - # TODO: avoid runtime import - from .resolution import Resolution, reso_str_bump_map + if prefix in {"D", "H", "T", "S", "L", "U", "N"}: + # For these prefixes, we have something like "3H" or + # "2.5T", so we can construct a Timedelta with the + # matching unit and get our offset from delta_to_tick + td = Timedelta(1, unit=prefix) + off = delta_to_tick(td) + offset = off * float(stride) + if n != 0: + # If n==0, then stride_sign is already incorporated + # into the offset + offset *= stride_sign + else: + stride = int(stride) + offset = _get_offset(name) + offset = offset * int(np.fabs(stride) * stride_sign) - if prefix in reso_str_bump_map: - stride, name = Resolution.get_stride_from_decimal( - float(stride), prefix - ) - stride = int(stride) - offset = _get_offset(name) - offset = offset * int(np.fabs(stride) * stride_sign) if delta is None: delta = offset else: diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py index e5b0142dae48b..10c239c683bc0 100644 --- a/pandas/tests/tseries/offsets/test_ticks.py +++ b/pandas/tests/tseries/offsets/test_ticks.py @@ -244,6 +244,22 @@ def test_tick_division(cls): assert result.delta == off.delta / 0.001 +def test_tick_mul_float(): + off = Micro(2) + + # Case where we retain type + result = off * 1.5 + expected = Micro(3) + assert result == expected + assert isinstance(result, Micro) + + # Case where we bump up to the next type + result = off * 1.25 + expected = Nano(2500) + assert result == expected + assert isinstance(result, Nano) + + @pytest.mark.parametrize("cls", tick_classes) def test_tick_rdiv(cls): off = cls(10)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This will let us remove Resolution.get_stride_from_decimal
https://api.github.com/repos/pandas-dev/pandas/pulls/34486
2020-05-30T18:50:31Z
2020-06-01T02:40:02Z
2020-06-01T02:40:02Z
2020-06-01T03:22:12Z
DOC: updating the `indicator` wording in `merge` doc
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2666597cbf765..5c906bf4daa2e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -233,14 +233,13 @@ copy : bool, default True If False, avoid copy if possible. indicator : bool or str, default False - If True, adds a column to output DataFrame called "_merge" with - information on the source of each row. - If string, column with information on source of each row will be added to - output DataFrame, and column will be named value of string. - Information column is Categorical-type and takes on a value of "left_only" - for observations whose merge key only appears in 'left' DataFrame, - "right_only" for observations whose merge key only appears in 'right' - DataFrame, and "both" if the observation's merge key is found in both. + If True, adds a column to the output DataFrame called "_merge" with + information on the source of each row. The column can be given a different + name by providing a string argument. The column will have a Categorical + type with the value of "left_only" for observations whose merge key only + appears in the left DataFrame, "right_only" for observations + whose merge key only appears in the right DataFrame, and "both" + if the observation's merge key is found in both DataFrames. validate : str, optional If specified, checks if merge is of specified type.
- [ ] closes #34480 - [ ] 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/34485
2020-05-30T18:00:46Z
2020-06-07T20:26:14Z
2020-06-07T20:26:14Z
2020-06-07T20:26:21Z
BUG: merge_asof should be treated as a left join
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c9267a756bef3..f3d4d53b00aa2 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -786,6 +786,7 @@ Reshaping ^^^^^^^^^ - Bug in :func:`merge` raising error when performing an inner join with partial index and ``right_index`` when no overlap between indices (:issue:`33814`) - Bug in :meth:`DataFrame.unstack` with missing levels led to incorrect index names (:issue:`37510`) +- Bug in :func:`merge_asof` propagating the right Index with ``left_index=True`` and ``right_on`` specification instead of left Index (:issue:`33463`) - Bug in :func:`join` over :class:`MultiIndex` returned wrong result, when one of both indexes had only one level (:issue:`36909`) - :meth:`merge_asof` raises ``ValueError`` instead of cryptic ``TypeError`` in case of non-numerical merge columns (:issue:`29130`) - Bug in :meth:`DataFrame.join` not assigning values correctly when having :class:`MultiIndex` where at least one dimension is from dtype ``Categorical`` with non-alphabetically sorted categories (:issue:`38502`) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 94d78f6b54b91..8cee0dd2abb88 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -969,7 +969,16 @@ def _get_join_info( join_index = self.right.index.take(right_indexer) left_indexer = np.array([-1] * len(join_index), dtype=np.intp) elif self.left_index: - if len(self.right) > 0: + if self.how == "asof": + # GH#33463 asof should always behave like a left merge + join_index = self._create_join_index( + self.left.index, + self.right.index, + left_indexer, + how="left", + ) + + elif len(self.right) > 0: join_index = self._create_join_index( self.right.index, self.left.index, diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index 3f5bb9b84372c..671f0ad2d26c7 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -6,6 +6,7 @@ import pandas as pd from pandas import ( + Index, Timedelta, merge_asof, read_csv, @@ -1338,7 +1339,9 @@ def test_merge_index_column_tz(self): "from_date": index[1:], "abc": [2.46] * 3 + [2.19], }, - index=pd.Index([1, 2, 3, 4]), + index=pd.date_range( + "2019-10-01 00:30:00", freq="30min", periods=4, tz="UTC" + ), ) tm.assert_frame_equal(result, expected) @@ -1351,7 +1354,7 @@ def test_merge_index_column_tz(self): "abc": [2.46] * 4 + [2.19], "xyz": [np.nan, 0.9, 0.8, 0.7, 0.6], }, - index=pd.Index([0, 1, 2, 3, 4]), + index=Index([0, 1, 2, 3, 4]), ) tm.assert_frame_equal(result, expected) @@ -1412,3 +1415,25 @@ def test_merge_asof_non_numerical_dtype_object(): left_by="a", right_by="left_val", ) + + +@pytest.mark.parametrize( + "kwargs", + [ + {"right_index": True, "left_index": True}, + {"left_on": "left_time", "right_index": True}, + {"left_index": True, "right_on": "right"}, + ], +) +def test_merge_asof_index_behavior(kwargs): + # GH 33463 + index = Index([1, 5, 10], name="test") + left = pd.DataFrame({"left": ["a", "b", "c"], "left_time": [1, 4, 10]}, index=index) + right = pd.DataFrame({"right": [1, 2, 3, 6, 7]}, index=[1, 2, 3, 6, 7]) + result = merge_asof(left, right, **kwargs) + + expected = pd.DataFrame( + {"left": ["a", "b", "c"], "left_time": [1, 4, 10], "right": [1, 3, 7]}, + index=index, + ) + tm.assert_frame_equal(result, expected)
- [x] closes #33463 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The fix broke one test (`test_merge_index_column_tz` in `test_merge_asof.py`) which expected the right index instead of the left index. The default index selection does not work in case of asof and `left_index=True`. I had to catch this case here.
https://api.github.com/repos/pandas-dev/pandas/pulls/34484
2020-05-30T16:17:34Z
2021-04-12T14:41:14Z
2021-04-12T14:41:14Z
2021-04-12T17:33:51Z
DOC: start 1.0.5
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index b381dae3579c8..ad5bb5a5b2d72 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -24,6 +24,7 @@ Version 1.0 .. toctree:: :maxdepth: 2 + v1.0.5 v1.0.4 v1.0.3 v1.0.2 diff --git a/doc/source/whatsnew/v1.0.4.rst b/doc/source/whatsnew/v1.0.4.rst index 5cc1edc9ca9cd..84b7e7d45e8b7 100644 --- a/doc/source/whatsnew/v1.0.4.rst +++ b/doc/source/whatsnew/v1.0.4.rst @@ -45,4 +45,4 @@ Bug fixes Contributors ~~~~~~~~~~~~ -.. contributors:: v1.0.3..v1.0.4|HEAD +.. contributors:: v1.0.3..v1.0.4 diff --git a/doc/source/whatsnew/v1.0.5.rst b/doc/source/whatsnew/v1.0.5.rst new file mode 100644 index 0000000000000..1edc7e1cad72f --- /dev/null +++ b/doc/source/whatsnew/v1.0.5.rst @@ -0,0 +1,31 @@ + +.. _whatsnew_105: + +What's new in 1.0.5 (June XX, 2020) +----------------------------------- + +These are the changes in pandas 1.0.5. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- + +.. _whatsnew_105.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. _whatsnew_105.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v1.0.4..v1.0.5|HEAD
xref https://github.com/pandas-dev/pandas/pull/33970#issuecomment-624029963
https://api.github.com/repos/pandas-dev/pandas/pulls/34481
2020-05-30T14:13:52Z
2020-05-31T18:04:34Z
2020-05-31T18:04:34Z
2020-06-01T15:43:56Z
CLN: Removed duplicated test data
diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index f1de15dd34464..fcee25c258efa 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -10,7 +10,7 @@ @pytest.fixture def tips_file(datapath): """Path to the tips dataset""" - return datapath("io", "parser", "data", "tips.csv") + return datapath("io", "data", "csv", "tips.csv") @pytest.fixture diff --git a/pandas/tests/io/parser/data/test1.csv.bz2 b/pandas/tests/io/data/csv/test1.csv.bz2 similarity index 100% rename from pandas/tests/io/parser/data/test1.csv.bz2 rename to pandas/tests/io/data/csv/test1.csv.bz2 diff --git a/pandas/tests/io/parser/data/test1.csv.gz b/pandas/tests/io/data/csv/test1.csv.gz similarity index 100% rename from pandas/tests/io/parser/data/test1.csv.gz rename to pandas/tests/io/data/csv/test1.csv.gz diff --git a/pandas/tests/io/parser/data/tips.csv.bz2 b/pandas/tests/io/data/csv/tips.csv.bz2 similarity index 100% rename from pandas/tests/io/parser/data/tips.csv.bz2 rename to pandas/tests/io/data/csv/tips.csv.bz2 diff --git a/pandas/tests/io/parser/data/tips.csv.gz b/pandas/tests/io/data/csv/tips.csv.gz similarity index 100% rename from pandas/tests/io/parser/data/tips.csv.gz rename to pandas/tests/io/data/csv/tips.csv.gz diff --git a/pandas/tests/io/parser/conftest.py b/pandas/tests/io/parser/conftest.py index 15967e3be176a..d03c85f65ea8d 100644 --- a/pandas/tests/io/parser/conftest.py +++ b/pandas/tests/io/parser/conftest.py @@ -53,11 +53,11 @@ def csv_dir_path(datapath): @pytest.fixture -def csv1(csv_dir_path): +def csv1(datapath): """ The path to the data file "test1.csv" needed for parser tests. """ - return os.path.join(csv_dir_path, "test1.csv") + return os.path.join(datapath("io", "data", "csv"), "test1.csv") _cParserHighMemory = CParserHighMemory() diff --git a/pandas/tests/io/parser/data/test1.csv b/pandas/tests/io/parser/data/test1.csv deleted file mode 100644 index 4bdb62943c4c8..0000000000000 --- a/pandas/tests/io/parser/data/test1.csv +++ /dev/null @@ -1,8 +0,0 @@ -index,A,B,C,D -2000-01-03 00:00:00,0.980268513777,3.68573087906,-0.364216805298,-1.15973806169 -2000-01-04 00:00:00,1.04791624281,-0.0412318367011,-0.16181208307,0.212549316967 -2000-01-05 00:00:00,0.498580885705,0.731167677815,-0.537677223318,1.34627041952 -2000-01-06 00:00:00,1.12020151869,1.56762092543,0.00364077397681,0.67525259227 -2000-01-07 00:00:00,-0.487094399463,0.571454623474,-1.6116394093,0.103468562917 -2000-01-10 00:00:00,0.836648671666,0.246461918642,0.588542635376,1.0627820613 -2000-01-11 00:00:00,-0.157160753327,1.34030689438,1.19577795622,-1.09700699751 \ No newline at end of file diff --git a/pandas/tests/io/parser/data/tips.csv b/pandas/tests/io/parser/data/tips.csv deleted file mode 100644 index 856a65a69e647..0000000000000 --- a/pandas/tests/io/parser/data/tips.csv +++ /dev/null @@ -1,245 +0,0 @@ -total_bill,tip,sex,smoker,day,time,size -16.99,1.01,Female,No,Sun,Dinner,2 -10.34,1.66,Male,No,Sun,Dinner,3 -21.01,3.5,Male,No,Sun,Dinner,3 -23.68,3.31,Male,No,Sun,Dinner,2 -24.59,3.61,Female,No,Sun,Dinner,4 -25.29,4.71,Male,No,Sun,Dinner,4 -8.77,2.0,Male,No,Sun,Dinner,2 -26.88,3.12,Male,No,Sun,Dinner,4 -15.04,1.96,Male,No,Sun,Dinner,2 -14.78,3.23,Male,No,Sun,Dinner,2 -10.27,1.71,Male,No,Sun,Dinner,2 -35.26,5.0,Female,No,Sun,Dinner,4 -15.42,1.57,Male,No,Sun,Dinner,2 -18.43,3.0,Male,No,Sun,Dinner,4 -14.83,3.02,Female,No,Sun,Dinner,2 -21.58,3.92,Male,No,Sun,Dinner,2 -10.33,1.67,Female,No,Sun,Dinner,3 -16.29,3.71,Male,No,Sun,Dinner,3 -16.97,3.5,Female,No,Sun,Dinner,3 -20.65,3.35,Male,No,Sat,Dinner,3 -17.92,4.08,Male,No,Sat,Dinner,2 -20.29,2.75,Female,No,Sat,Dinner,2 -15.77,2.23,Female,No,Sat,Dinner,2 -39.42,7.58,Male,No,Sat,Dinner,4 -19.82,3.18,Male,No,Sat,Dinner,2 -17.81,2.34,Male,No,Sat,Dinner,4 -13.37,2.0,Male,No,Sat,Dinner,2 -12.69,2.0,Male,No,Sat,Dinner,2 -21.7,4.3,Male,No,Sat,Dinner,2 -19.65,3.0,Female,No,Sat,Dinner,2 -9.55,1.45,Male,No,Sat,Dinner,2 -18.35,2.5,Male,No,Sat,Dinner,4 -15.06,3.0,Female,No,Sat,Dinner,2 -20.69,2.45,Female,No,Sat,Dinner,4 -17.78,3.27,Male,No,Sat,Dinner,2 -24.06,3.6,Male,No,Sat,Dinner,3 -16.31,2.0,Male,No,Sat,Dinner,3 -16.93,3.07,Female,No,Sat,Dinner,3 -18.69,2.31,Male,No,Sat,Dinner,3 -31.27,5.0,Male,No,Sat,Dinner,3 -16.04,2.24,Male,No,Sat,Dinner,3 -17.46,2.54,Male,No,Sun,Dinner,2 -13.94,3.06,Male,No,Sun,Dinner,2 -9.68,1.32,Male,No,Sun,Dinner,2 -30.4,5.6,Male,No,Sun,Dinner,4 -18.29,3.0,Male,No,Sun,Dinner,2 -22.23,5.0,Male,No,Sun,Dinner,2 -32.4,6.0,Male,No,Sun,Dinner,4 -28.55,2.05,Male,No,Sun,Dinner,3 -18.04,3.0,Male,No,Sun,Dinner,2 -12.54,2.5,Male,No,Sun,Dinner,2 -10.29,2.6,Female,No,Sun,Dinner,2 -34.81,5.2,Female,No,Sun,Dinner,4 -9.94,1.56,Male,No,Sun,Dinner,2 -25.56,4.34,Male,No,Sun,Dinner,4 -19.49,3.51,Male,No,Sun,Dinner,2 -38.01,3.0,Male,Yes,Sat,Dinner,4 -26.41,1.5,Female,No,Sat,Dinner,2 -11.24,1.76,Male,Yes,Sat,Dinner,2 -48.27,6.73,Male,No,Sat,Dinner,4 -20.29,3.21,Male,Yes,Sat,Dinner,2 -13.81,2.0,Male,Yes,Sat,Dinner,2 -11.02,1.98,Male,Yes,Sat,Dinner,2 -18.29,3.76,Male,Yes,Sat,Dinner,4 -17.59,2.64,Male,No,Sat,Dinner,3 -20.08,3.15,Male,No,Sat,Dinner,3 -16.45,2.47,Female,No,Sat,Dinner,2 -3.07,1.0,Female,Yes,Sat,Dinner,1 -20.23,2.01,Male,No,Sat,Dinner,2 -15.01,2.09,Male,Yes,Sat,Dinner,2 -12.02,1.97,Male,No,Sat,Dinner,2 -17.07,3.0,Female,No,Sat,Dinner,3 -26.86,3.14,Female,Yes,Sat,Dinner,2 -25.28,5.0,Female,Yes,Sat,Dinner,2 -14.73,2.2,Female,No,Sat,Dinner,2 -10.51,1.25,Male,No,Sat,Dinner,2 -17.92,3.08,Male,Yes,Sat,Dinner,2 -27.2,4.0,Male,No,Thur,Lunch,4 -22.76,3.0,Male,No,Thur,Lunch,2 -17.29,2.71,Male,No,Thur,Lunch,2 -19.44,3.0,Male,Yes,Thur,Lunch,2 -16.66,3.4,Male,No,Thur,Lunch,2 -10.07,1.83,Female,No,Thur,Lunch,1 -32.68,5.0,Male,Yes,Thur,Lunch,2 -15.98,2.03,Male,No,Thur,Lunch,2 -34.83,5.17,Female,No,Thur,Lunch,4 -13.03,2.0,Male,No,Thur,Lunch,2 -18.28,4.0,Male,No,Thur,Lunch,2 -24.71,5.85,Male,No,Thur,Lunch,2 -21.16,3.0,Male,No,Thur,Lunch,2 -28.97,3.0,Male,Yes,Fri,Dinner,2 -22.49,3.5,Male,No,Fri,Dinner,2 -5.75,1.0,Female,Yes,Fri,Dinner,2 -16.32,4.3,Female,Yes,Fri,Dinner,2 -22.75,3.25,Female,No,Fri,Dinner,2 -40.17,4.73,Male,Yes,Fri,Dinner,4 -27.28,4.0,Male,Yes,Fri,Dinner,2 -12.03,1.5,Male,Yes,Fri,Dinner,2 -21.01,3.0,Male,Yes,Fri,Dinner,2 -12.46,1.5,Male,No,Fri,Dinner,2 -11.35,2.5,Female,Yes,Fri,Dinner,2 -15.38,3.0,Female,Yes,Fri,Dinner,2 -44.3,2.5,Female,Yes,Sat,Dinner,3 -22.42,3.48,Female,Yes,Sat,Dinner,2 -20.92,4.08,Female,No,Sat,Dinner,2 -15.36,1.64,Male,Yes,Sat,Dinner,2 -20.49,4.06,Male,Yes,Sat,Dinner,2 -25.21,4.29,Male,Yes,Sat,Dinner,2 -18.24,3.76,Male,No,Sat,Dinner,2 -14.31,4.0,Female,Yes,Sat,Dinner,2 -14.0,3.0,Male,No,Sat,Dinner,2 -7.25,1.0,Female,No,Sat,Dinner,1 -38.07,4.0,Male,No,Sun,Dinner,3 -23.95,2.55,Male,No,Sun,Dinner,2 -25.71,4.0,Female,No,Sun,Dinner,3 -17.31,3.5,Female,No,Sun,Dinner,2 -29.93,5.07,Male,No,Sun,Dinner,4 -10.65,1.5,Female,No,Thur,Lunch,2 -12.43,1.8,Female,No,Thur,Lunch,2 -24.08,2.92,Female,No,Thur,Lunch,4 -11.69,2.31,Male,No,Thur,Lunch,2 -13.42,1.68,Female,No,Thur,Lunch,2 -14.26,2.5,Male,No,Thur,Lunch,2 -15.95,2.0,Male,No,Thur,Lunch,2 -12.48,2.52,Female,No,Thur,Lunch,2 -29.8,4.2,Female,No,Thur,Lunch,6 -8.52,1.48,Male,No,Thur,Lunch,2 -14.52,2.0,Female,No,Thur,Lunch,2 -11.38,2.0,Female,No,Thur,Lunch,2 -22.82,2.18,Male,No,Thur,Lunch,3 -19.08,1.5,Male,No,Thur,Lunch,2 -20.27,2.83,Female,No,Thur,Lunch,2 -11.17,1.5,Female,No,Thur,Lunch,2 -12.26,2.0,Female,No,Thur,Lunch,2 -18.26,3.25,Female,No,Thur,Lunch,2 -8.51,1.25,Female,No,Thur,Lunch,2 -10.33,2.0,Female,No,Thur,Lunch,2 -14.15,2.0,Female,No,Thur,Lunch,2 -16.0,2.0,Male,Yes,Thur,Lunch,2 -13.16,2.75,Female,No,Thur,Lunch,2 -17.47,3.5,Female,No,Thur,Lunch,2 -34.3,6.7,Male,No,Thur,Lunch,6 -41.19,5.0,Male,No,Thur,Lunch,5 -27.05,5.0,Female,No,Thur,Lunch,6 -16.43,2.3,Female,No,Thur,Lunch,2 -8.35,1.5,Female,No,Thur,Lunch,2 -18.64,1.36,Female,No,Thur,Lunch,3 -11.87,1.63,Female,No,Thur,Lunch,2 -9.78,1.73,Male,No,Thur,Lunch,2 -7.51,2.0,Male,No,Thur,Lunch,2 -14.07,2.5,Male,No,Sun,Dinner,2 -13.13,2.0,Male,No,Sun,Dinner,2 -17.26,2.74,Male,No,Sun,Dinner,3 -24.55,2.0,Male,No,Sun,Dinner,4 -19.77,2.0,Male,No,Sun,Dinner,4 -29.85,5.14,Female,No,Sun,Dinner,5 -48.17,5.0,Male,No,Sun,Dinner,6 -25.0,3.75,Female,No,Sun,Dinner,4 -13.39,2.61,Female,No,Sun,Dinner,2 -16.49,2.0,Male,No,Sun,Dinner,4 -21.5,3.5,Male,No,Sun,Dinner,4 -12.66,2.5,Male,No,Sun,Dinner,2 -16.21,2.0,Female,No,Sun,Dinner,3 -13.81,2.0,Male,No,Sun,Dinner,2 -17.51,3.0,Female,Yes,Sun,Dinner,2 -24.52,3.48,Male,No,Sun,Dinner,3 -20.76,2.24,Male,No,Sun,Dinner,2 -31.71,4.5,Male,No,Sun,Dinner,4 -10.59,1.61,Female,Yes,Sat,Dinner,2 -10.63,2.0,Female,Yes,Sat,Dinner,2 -50.81,10.0,Male,Yes,Sat,Dinner,3 -15.81,3.16,Male,Yes,Sat,Dinner,2 -7.25,5.15,Male,Yes,Sun,Dinner,2 -31.85,3.18,Male,Yes,Sun,Dinner,2 -16.82,4.0,Male,Yes,Sun,Dinner,2 -32.9,3.11,Male,Yes,Sun,Dinner,2 -17.89,2.0,Male,Yes,Sun,Dinner,2 -14.48,2.0,Male,Yes,Sun,Dinner,2 -9.6,4.0,Female,Yes,Sun,Dinner,2 -34.63,3.55,Male,Yes,Sun,Dinner,2 -34.65,3.68,Male,Yes,Sun,Dinner,4 -23.33,5.65,Male,Yes,Sun,Dinner,2 -45.35,3.5,Male,Yes,Sun,Dinner,3 -23.17,6.5,Male,Yes,Sun,Dinner,4 -40.55,3.0,Male,Yes,Sun,Dinner,2 -20.69,5.0,Male,No,Sun,Dinner,5 -20.9,3.5,Female,Yes,Sun,Dinner,3 -30.46,2.0,Male,Yes,Sun,Dinner,5 -18.15,3.5,Female,Yes,Sun,Dinner,3 -23.1,4.0,Male,Yes,Sun,Dinner,3 -15.69,1.5,Male,Yes,Sun,Dinner,2 -19.81,4.19,Female,Yes,Thur,Lunch,2 -28.44,2.56,Male,Yes,Thur,Lunch,2 -15.48,2.02,Male,Yes,Thur,Lunch,2 -16.58,4.0,Male,Yes,Thur,Lunch,2 -7.56,1.44,Male,No,Thur,Lunch,2 -10.34,2.0,Male,Yes,Thur,Lunch,2 -43.11,5.0,Female,Yes,Thur,Lunch,4 -13.0,2.0,Female,Yes,Thur,Lunch,2 -13.51,2.0,Male,Yes,Thur,Lunch,2 -18.71,4.0,Male,Yes,Thur,Lunch,3 -12.74,2.01,Female,Yes,Thur,Lunch,2 -13.0,2.0,Female,Yes,Thur,Lunch,2 -16.4,2.5,Female,Yes,Thur,Lunch,2 -20.53,4.0,Male,Yes,Thur,Lunch,4 -16.47,3.23,Female,Yes,Thur,Lunch,3 -26.59,3.41,Male,Yes,Sat,Dinner,3 -38.73,3.0,Male,Yes,Sat,Dinner,4 -24.27,2.03,Male,Yes,Sat,Dinner,2 -12.76,2.23,Female,Yes,Sat,Dinner,2 -30.06,2.0,Male,Yes,Sat,Dinner,3 -25.89,5.16,Male,Yes,Sat,Dinner,4 -48.33,9.0,Male,No,Sat,Dinner,4 -13.27,2.5,Female,Yes,Sat,Dinner,2 -28.17,6.5,Female,Yes,Sat,Dinner,3 -12.9,1.1,Female,Yes,Sat,Dinner,2 -28.15,3.0,Male,Yes,Sat,Dinner,5 -11.59,1.5,Male,Yes,Sat,Dinner,2 -7.74,1.44,Male,Yes,Sat,Dinner,2 -30.14,3.09,Female,Yes,Sat,Dinner,4 -12.16,2.2,Male,Yes,Fri,Lunch,2 -13.42,3.48,Female,Yes,Fri,Lunch,2 -8.58,1.92,Male,Yes,Fri,Lunch,1 -15.98,3.0,Female,No,Fri,Lunch,3 -13.42,1.58,Male,Yes,Fri,Lunch,2 -16.27,2.5,Female,Yes,Fri,Lunch,2 -10.09,2.0,Female,Yes,Fri,Lunch,2 -20.45,3.0,Male,No,Sat,Dinner,4 -13.28,2.72,Male,No,Sat,Dinner,2 -22.12,2.88,Female,Yes,Sat,Dinner,2 -24.01,2.0,Male,Yes,Sat,Dinner,4 -15.69,3.0,Male,Yes,Sat,Dinner,3 -11.61,3.39,Male,No,Sat,Dinner,2 -10.77,1.47,Male,No,Sat,Dinner,2 -15.53,3.0,Male,Yes,Sat,Dinner,2 -10.07,1.25,Male,No,Sat,Dinner,2 -12.6,1.0,Male,Yes,Sat,Dinner,2 -32.83,1.17,Male,Yes,Sat,Dinner,2 -35.83,4.67,Female,No,Sat,Dinner,3 -29.03,5.92,Male,No,Sat,Dinner,3 -27.18,2.0,Female,Yes,Sat,Dinner,2 -22.67,2.0,Male,Yes,Sat,Dinner,2 -17.82,1.75,Male,No,Sat,Dinner,2 -18.78,3.0,Female,No,Thur,Dinner,2 diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py index 13b74cf29f857..de7b3bed034c7 100644 --- a/pandas/tests/io/parser/test_encoding.py +++ b/pandas/tests/io/parser/test_encoding.py @@ -133,19 +133,21 @@ def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): @pytest.mark.parametrize( - "fname,encoding", + "file_path,encoding", [ - ("test1.csv", "utf-8"), - ("unicode_series.csv", "latin-1"), - ("sauron.SHIFT_JIS.csv", "shiftjis"), + (("io", "data", "csv", "test1.csv"), "utf-8"), + (("io", "parser", "data", "unicode_series.csv"), "latin-1"), + (("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"), ], ) -def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding): +def test_binary_mode_file_buffers( + all_parsers, csv_dir_path, file_path, encoding, datapath +): # gh-23779: Python csv engine shouldn't error on files opened in binary. # gh-31575: Python csv engine shouldn't error on files opened in raw binary. parser = all_parsers - fpath = os.path.join(csv_dir_path, fname) + fpath = datapath(*file_path) expected = parser.read_csv(fpath, encoding=encoding) with open(fpath, mode="r", encoding=encoding) as fa: diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index e0dee878006b8..509ae89909699 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -49,7 +49,7 @@ def check_compressed_urls(salaries_table, compression, extension, mode, engine): @pytest.fixture def tips_df(datapath): """DataFrame with the tips dataset.""" - return read_csv(datapath("io", "parser", "data", "tips.csv")) + return read_csv(datapath("io", "data", "csv", "tips.csv")) @pytest.mark.usefixtures("s3_resource") diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index 8d5af85c20d33..1c2518646bb29 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -21,7 +21,8 @@ class TestTextReader: @pytest.fixture(autouse=True) def setup_method(self, datapath): self.dirpath = datapath("io", "parser", "data") - self.csv1 = os.path.join(self.dirpath, "test1.csv") + csv1_dirpath = datapath("io", "data", "csv") + self.csv1 = os.path.join(csv1_dirpath, "test1.csv") self.csv2 = os.path.join(self.dirpath, "test2.csv") self.xls1 = os.path.join(self.dirpath, "test.xls")
Remove duplicated test data. "test1.csv" & "tips.csv" are present in both "tests/io/parser/data" & "tests/io/data/csv". Move the "*.csv.bz2" & "*.csv.gz" files since the s3_resource fixture in tests/io/conftest requires these. Follow up from: https://github.com/pandas-dev/pandas/issues/29439 Think we should move all the data in io/parser/data/* into io/data/ so it can be re-used. Will save for follow up.
https://api.github.com/repos/pandas-dev/pandas/pulls/34477
2020-05-30T01:17:43Z
2020-06-08T01:45:23Z
2020-06-08T01:45:23Z
2020-06-08T01:45:31Z
REF: make normalize_i8_timestamps cpdef
diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index 15313c0c2c3dd..94f6d1d9020d2 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -1,6 +1,6 @@ -from cpython.datetime cimport datetime +from cpython.datetime cimport datetime, tzinfo -from numpy cimport int64_t, int32_t +from numpy cimport int64_t, int32_t, ndarray from pandas._libs.tslibs.np_datetime cimport npy_datetimestruct @@ -24,3 +24,5 @@ cdef int64_t get_datetime64_nanos(object val) except? -1 cpdef datetime localize_pydatetime(datetime dt, object tz) cdef int64_t cast_from_unit(object ts, str unit) except? -1 + +cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo tz) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 8fd2f6b476e1c..cbb27bf8e9917 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -763,7 +763,7 @@ cpdef inline datetime localize_pydatetime(datetime dt, object tz): @cython.wraparound(False) @cython.boundscheck(False) -def normalize_i8_timestamps(int64_t[:] stamps, object tz): +cpdef ndarray[int64_t] normalize_i8_timestamps(const int64_t[:] stamps, tzinfo tz): """ Normalize each of the (nanosecond) timezone aware timestamps in the given array by rounding down to the beginning of the day (i.e. midnight). @@ -774,31 +774,6 @@ def normalize_i8_timestamps(int64_t[:] stamps, object tz): stamps : int64 ndarray tz : tzinfo or None - Returns - ------- - result : int64 ndarray of converted of normalized nanosecond timestamps - """ - cdef: - int64_t[:] result - - result = _normalize_local(stamps, tz) - - return result.base # .base to access underlying np.ndarray - - -@cython.wraparound(False) -@cython.boundscheck(False) -cdef int64_t[:] _normalize_local(const int64_t[:] stamps, tzinfo tz): - """ - Normalize each of the (nanosecond) timestamps in the given array by - rounding down to the beginning of the day (i.e. midnight) for the - given timezone `tz`. - - Parameters - ---------- - stamps : int64 ndarray - tz : tzinfo - Returns ------- result : int64 ndarray of converted of normalized nanosecond timestamps @@ -843,7 +818,7 @@ cdef int64_t[:] _normalize_local(const int64_t[:] stamps, tzinfo tz): dt64_to_dtstruct(stamps[i] + deltas[pos[i]], &dts) result[i] = _normalized_stamp(&dts) - return result + return result.base # `.base` to access underlying ndarray cdef inline int64_t _normalized_stamp(npy_datetimestruct *dts) nogil: diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 48c4afe7d4c1b..82068c2178704 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -16,8 +16,15 @@ cnp.import_array() from cpython.object cimport (PyObject_RichCompareBool, PyObject_RichCompare, Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE) -from cpython.datetime cimport (datetime, time, PyDateTime_Check, PyDelta_Check, - PyTZInfo_Check, PyDateTime_IMPORT) +from cpython.datetime cimport ( + datetime, + time, + tzinfo, + PyDateTime_Check, + PyDelta_Check, + PyTZInfo_Check, + PyDateTime_IMPORT, +) PyDateTime_IMPORT from pandas._libs.tslibs.util cimport ( @@ -29,10 +36,12 @@ from pandas._libs.tslibs.base cimport ABCTimedelta, ABCTimestamp from pandas._libs.tslibs cimport ccalendar -from pandas._libs.tslibs.conversion import normalize_i8_timestamps from pandas._libs.tslibs.conversion cimport ( - _TSObject, convert_to_tsobject, - convert_datetime_to_tsobject) + _TSObject, + convert_to_tsobject, + convert_datetime_to_tsobject, + normalize_i8_timestamps, +) from pandas._libs.tslibs.fields import get_start_end_field, get_date_name_field from pandas._libs.tslibs.nattype cimport NPY_NAT, c_NaT as NaT from pandas._libs.tslibs.np_datetime cimport ( @@ -1461,13 +1470,18 @@ default 'raise' """ Normalize Timestamp to midnight, preserving tz information. """ - if self.tz is None or is_utc(self.tz): + cdef: + ndarray[int64_t] normalized + tzinfo own_tz = self.tzinfo # could be None + + if own_tz is None or is_utc(own_tz): DAY_NS = ccalendar.DAY_NANOS normalized_value = self.value - (self.value % DAY_NS) - return Timestamp(normalized_value).tz_localize(self.tz) - normalized_value = normalize_i8_timestamps( - np.array([self.value], dtype='i8'), tz=self.tz)[0] - return Timestamp(normalized_value).tz_localize(self.tz) + return Timestamp(normalized_value).tz_localize(own_tz) + + normalized = normalize_i8_timestamps( + np.array([self.value], dtype='i8'), tz=own_tz) + return Timestamp(normalized[0]).tz_localize(own_tz) # Add the min and max fields at the class level
there's a tiny perf bump, but it all comes from doing `own_tz = self.tzinfo` up-front instead of accessing `self.tz` multiple times within `Timestamp.normalize`. With just the cimport, this is actually slightly slower, which is something of a mystery. The main upside is that we now only cimport from libconversion, which im hopeful will make some other circular-imports easier to simplify.the perf improvement
https://api.github.com/repos/pandas-dev/pandas/pulls/34476
2020-05-30T01:15:05Z
2020-05-31T23:01:05Z
2020-05-31T23:01:05Z
2020-05-31T23:06:19Z
BUG: fix origin epoch when freq is Day and harmonize epoch between timezones
diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 4a4c9a1d7434b..5df80645c2b5d 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1693,11 +1693,15 @@ def _get_timestamp_range_edges( ------- A tuple of length 2, containing the adjusted pd.Timestamp objects. """ - index_tz = first.tz - if isinstance(origin, Timestamp) and (origin.tz is None) != (index_tz is None): - raise ValueError("The origin must have the same timezone as the index.") - if isinstance(freq, Tick): + index_tz = first.tz + if isinstance(origin, Timestamp) and (origin.tz is None) != (index_tz is None): + raise ValueError("The origin must have the same timezone as the index.") + elif origin == "epoch": + # set the epoch based on the timezone to have similar bins results when + # resampling on the same kind of indexes on different timezones + origin = Timestamp("1970-01-01", tz=index_tz) + if isinstance(freq, Day): # _adjust_dates_anchored assumes 'D' means 24H, but first/last # might contain a DST transition (23H, 24H, or 25H). diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index fe005801aaa53..9909e554aa14d 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -846,6 +846,34 @@ def test_resample_origin_with_tz(): ts.resample("5min", origin="12/31/1999 23:57:00+03:00").mean() +def test_resample_origin_epoch_with_tz_day_vs_24h(): + # GH 34474 + start, end = "2000-10-01 23:30:00+0500", "2000-12-02 00:30:00+0500" + rng = pd.date_range(start, end, freq="7min") + random_values = np.random.randn(len(rng)) + ts_1 = pd.Series(random_values, index=rng) + + result_1 = ts_1.resample("D", origin="epoch").mean() + result_2 = ts_1.resample("24H", origin="epoch").mean() + tm.assert_series_equal(result_1, result_2) + + # check that we have the same behavior with epoch even if we are not timezone aware + ts_no_tz = ts_1.tz_localize(None) + result_3 = ts_no_tz.resample("D", origin="epoch").mean() + result_4 = ts_no_tz.resample("24H", origin="epoch").mean() + tm.assert_series_equal(result_1, result_3.tz_localize(rng.tz), check_freq=False) + tm.assert_series_equal(result_1, result_4.tz_localize(rng.tz), check_freq=False) + + # check that we have the similar results with two different timezones (+2H and +5H) + start, end = "2000-10-01 23:30:00+0200", "2000-12-02 00:30:00+0200" + rng = pd.date_range(start, end, freq="7min") + ts_2 = pd.Series(random_values, index=rng) + result_5 = ts_2.resample("D", origin="epoch").mean() + result_6 = ts_2.resample("24H", origin="epoch").mean() + tm.assert_series_equal(result_1.tz_localize(None), result_5.tz_localize(None)) + tm.assert_series_equal(result_1.tz_localize(None), result_6.tz_localize(None)) + + def test_resample_origin_with_day_freq_on_dst(): # GH 31809 tz = "America/Chicago"
Follow-up of #31809. The purpose of this PR is to fix the current behavior on master: ```python import pandas as pd import numpy as np start, end = "2000-08-02 23:30:00+0500", "2000-12-02 00:30:00+0500" rng = pd.date_range(start, end, freq="7min") ts = pd.Series(np.random.randn(len(rng)), index=rng) result_1 = ts.resample("D", origin="epoch").count() result_2 = ts.resample("24H", origin="epoch").count() print(f"result_1:\n\n{result_1}\n") print(f"result_2:\n\n{result_2}\n") ``` Outputs on master: ``` result_1: 2000-08-02 00:00:00+05:00 5 2000-08-03 00:00:00+05:00 205 2000-08-04 00:00:00+05:00 206 2000-08-05 00:00:00+05:00 206 2000-08-06 00:00:00+05:00 206 ... 2000-11-28 00:00:00+05:00 206 2000-11-29 00:00:00+05:00 206 2000-11-30 00:00:00+05:00 205 2000-12-01 00:00:00+05:00 206 2000-12-02 00:00:00+05:00 5 Freq: D, Length: 123, dtype: int64 result_2: 2000-08-02 05:00:00+05:00 48 2000-08-03 05:00:00+05:00 205 2000-08-04 05:00:00+05:00 206 2000-08-05 05:00:00+05:00 206 2000-08-06 05:00:00+05:00 205 ... 2000-11-27 05:00:00+05:00 206 2000-11-28 05:00:00+05:00 206 2000-11-29 05:00:00+05:00 206 2000-11-30 05:00:00+05:00 205 2000-12-01 05:00:00+05:00 168 Freq: 24H, Length: 122, dtype: int64 ``` Expected Outputs (with this PR): ``` result_1: 2000-08-02 00:00:00+05:00 5 2000-08-03 00:00:00+05:00 205 2000-08-04 00:00:00+05:00 206 2000-08-05 00:00:00+05:00 206 2000-08-06 00:00:00+05:00 206 ... 2000-11-28 00:00:00+05:00 206 2000-11-29 00:00:00+05:00 206 2000-11-30 00:00:00+05:00 205 2000-12-01 00:00:00+05:00 206 2000-12-02 00:00:00+05:00 5 Freq: D, Length: 123, dtype: int64 result_2: 2000-08-02 00:00:00+05:00 5 2000-08-03 00:00:00+05:00 205 2000-08-04 00:00:00+05:00 206 2000-08-05 00:00:00+05:00 206 2000-08-06 00:00:00+05:00 206 ... 2000-11-28 00:00:00+05:00 206 2000-11-29 00:00:00+05:00 206 2000-11-30 00:00:00+05:00 205 2000-12-01 00:00:00+05:00 206 2000-12-02 00:00:00+05:00 5 Freq: 24H, Length: 123, dtype: int64 ``` ------ I thought of two possible solutions while fixing that: 1. Consider 'epoch' as a UNIX epoch: `pd.Timestamp(0, tz=index_tz)` 2. Consider that 'epoch' is just an helper to fix the origin: `pd.Timestamp("1970-01-01", tz=index_tz)` To have similar results between timezones, I thought the solution 2 was a better choice. The solution 2 could also help us to set the behavior `origin=epoch` as the default one in a future version since the results would be quite similar with `origin=start_day` (that is not quite the case with a DST timezone, I can provide further details if needed on why this is the case). (The solution 1 is correct in theory but is giving results that could be hard to explain to the end user.) ------ - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry (follow-up PR, not necessary I think)
https://api.github.com/repos/pandas-dev/pandas/pulls/34474
2020-05-30T00:44:46Z
2020-06-01T22:18:00Z
2020-06-01T22:18:00Z
2020-06-01T22:18:07Z
fix to_json for numbers larger than sys.maxsize
diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py index a490e250943f5..ed0fb5b8fe342 100644 --- a/asv_bench/benchmarks/io/json.py +++ b/asv_bench/benchmarks/io/json.py @@ -1,3 +1,5 @@ +import sys + import numpy as np from pandas import DataFrame, concat, date_range, read_json, timedelta_range @@ -82,6 +84,7 @@ def setup(self, orient, frame): timedeltas = timedelta_range(start=1, periods=N, freq="s") datetimes = date_range(start=1, periods=N, freq="s") ints = np.random.randint(100000000, size=N) + longints = sys.maxsize * np.random.randint(100000000, size=N) floats = np.random.randn(N) strings = tm.makeStringIndex(N) self.df = DataFrame(np.random.randn(N, ncols), index=np.arange(N)) @@ -120,6 +123,18 @@ def setup(self, orient, frame): index=index, ) + self.df_longint_float_str = DataFrame( + { + "longint_1": longints, + "longint_2": longints, + "float_1": floats, + "float_2": floats, + "str_1": strings, + "str_2": strings, + }, + index=index, + ) + def time_to_json(self, orient, frame): getattr(self, frame).to_json(self.fname, orient=orient) @@ -172,6 +187,7 @@ def setup(self): timedeltas = timedelta_range(start=1, periods=N, freq="s") datetimes = date_range(start=1, periods=N, freq="s") ints = np.random.randint(100000000, size=N) + longints = sys.maxsize * np.random.randint(100000000, size=N) floats = np.random.randn(N) strings = tm.makeStringIndex(N) self.df = DataFrame(np.random.randn(N, ncols), index=np.arange(N)) @@ -209,6 +225,17 @@ def setup(self): }, index=index, ) + self.df_longint_float_str = DataFrame( + { + "longint_1": longints, + "longint_2": longints, + "float_1": floats, + "float_2": floats, + "str_1": strings, + "str_2": strings, + }, + index=index, + ) def time_floats_with_int_idex_lines(self): self.df.to_json(self.fname, orient="records", lines=True) @@ -225,6 +252,9 @@ def time_float_int_lines(self): def time_float_int_str_lines(self): self.df_int_float_str.to_json(self.fname, orient="records", lines=True) + def time_float_longint_str_lines(self): + self.df_longint_float_str.to_json(self.fname, orient="records", lines=True) + class ToJSONMem: def setup_cache(self): diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7c9fa53568f45..d6f313b5c3b35 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -1020,6 +1020,7 @@ I/O - Bug in :meth:`~pandas.io.stata.StataReader` which resulted in categorical variables with difference dtypes when reading data using an iterator. (:issue:`31544`) - :meth:`HDFStore.keys` has now an optional `include` parameter that allows the retrieval of all native HDF5 table names (:issue:`29916`) - Bug in :meth:`read_excel` for ODS files removes 0.0 values (:issue:`27222`) +- Bug in :meth:`ujson.encode` was raising an `OverflowError` with numbers larger than sys.maxsize (:issue: `34395`) Plotting ^^^^^^^^ diff --git a/pandas/_libs/src/ujson/lib/ultrajson.h b/pandas/_libs/src/ujson/lib/ultrajson.h index acb66b668e8dc..69284e1c3f2ab 100644 --- a/pandas/_libs/src/ujson/lib/ultrajson.h +++ b/pandas/_libs/src/ujson/lib/ultrajson.h @@ -150,6 +150,7 @@ enum JSTYPES { JT_INT, // (JSINT32 (signed 32-bit)) JT_LONG, // (JSINT64 (signed 64-bit)) JT_DOUBLE, // (double) + JT_BIGNUM, // integer larger than sys.maxsize JT_UTF8, // (char 8-bit) JT_ARRAY, // Array structure JT_OBJECT, // Key/Value structure @@ -187,6 +188,8 @@ typedef struct __JSONObjectEncoder { JSINT64 (*getLongValue)(JSOBJ obj, JSONTypeContext *tc); JSINT32 (*getIntValue)(JSOBJ obj, JSONTypeContext *tc); double (*getDoubleValue)(JSOBJ obj, JSONTypeContext *tc); + const char *(*getBigNumStringValue)(JSOBJ obj, JSONTypeContext *tc, + size_t *_outLen); /* Begin iteration of an iteratable object (JS_ARRAY or JS_OBJECT) diff --git a/pandas/_libs/src/ujson/lib/ultrajsonenc.c b/pandas/_libs/src/ujson/lib/ultrajsonenc.c index 065e3b2c60cf9..51aa39a16920e 100644 --- a/pandas/_libs/src/ujson/lib/ultrajsonenc.c +++ b/pandas/_libs/src/ujson/lib/ultrajsonenc.c @@ -1107,6 +1107,35 @@ void encode(JSOBJ obj, JSONObjectEncoder *enc, const char *name, Buffer_AppendCharUnchecked(enc, '\"'); break; } + + case JT_BIGNUM: { + value = enc->getBigNumStringValue(obj, &tc, &szlen); + + Buffer_Reserve(enc, RESERVE_STRING(szlen)); + if (enc->errorMsg) { + enc->endTypeContext(obj, &tc); + return; + } + + if (enc->forceASCII) { + if (!Buffer_EscapeStringValidated(obj, enc, value, + value + szlen)) { + enc->endTypeContext(obj, &tc); + enc->level--; + return; + } + } else { + if (!Buffer_EscapeStringUnvalidated(enc, value, + value + szlen)) { + enc->endTypeContext(obj, &tc); + enc->level--; + return; + } + } + + break; + + } } enc->endTypeContext(obj, &tc); diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index c71e941f7d6e8..1de9642761961 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -1629,15 +1629,20 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { if (PyLong_Check(obj)) { PRINTMARK(); tc->type = JT_LONG; - GET_TC(tc)->longValue = PyLong_AsLongLong(obj); + int overflow = 0; + GET_TC(tc)->longValue = PyLong_AsLongLongAndOverflow(obj, &overflow); + int err; + err = (GET_TC(tc)->longValue == -1) && PyErr_Occurred(); - exc = PyErr_Occurred(); - - if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { + if (overflow){ + PRINTMARK(); + tc->type = JT_BIGNUM; + } + else if (err) { PRINTMARK(); goto INVALID; } - + return; } else if (PyFloat_Check(obj)) { PRINTMARK(); @@ -2105,7 +2110,6 @@ void Object_endTypeContext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { NpyArr_freeLabels(GET_TC(tc)->columnLabels, GET_TC(tc)->columnLabelsLen); GET_TC(tc)->columnLabels = NULL; - PyObject_Free(GET_TC(tc)->cStr); GET_TC(tc)->cStr = NULL; PyObject_Free(tc->prv); @@ -2126,6 +2130,19 @@ double Object_getDoubleValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->doubleValue; } +const char *Object_getBigNumStringValue(JSOBJ obj, JSONTypeContext *tc, + size_t *_outLen) { + PyObject* repr = PyObject_Str(obj); + const char *str = PyUnicode_AsUTF8AndSize(repr, (Py_ssize_t *) _outLen); + char* bytes = PyObject_Malloc(*_outLen + 1); + memcpy(bytes, str, *_outLen + 1); + GET_TC(tc)->cStr = bytes; + + Py_DECREF(repr); + + return GET_TC(tc)->cStr; +} + static void Object_releaseObject(JSOBJ _obj) { Py_DECREF((PyObject *)_obj); } void Object_iterBegin(JSOBJ obj, JSONTypeContext *tc) { @@ -2181,6 +2198,7 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, Object_getLongValue, NULL, // getIntValue is unused Object_getDoubleValue, + Object_getBigNumStringValue, Object_iterBegin, Object_iterNext, Object_iterEnd, @@ -2294,7 +2312,6 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, if (ret != buffer) { encoder->free(ret); } - PyErr_Format(PyExc_OverflowError, "%s", encoder->errorMsg); return NULL; } diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 8578b31fbb81e..10f49b9b81528 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -4,6 +4,7 @@ from io import StringIO import json import os +import sys import numpy as np import pytest @@ -1242,6 +1243,29 @@ def test_read_jsonl_unicode_chars(self): expected = DataFrame([["foo\u201d", "bar"], ["foo", "bar"]], columns=["a", "b"]) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize("bigNum", [sys.maxsize + 1, -(sys.maxsize + 2)]) + def test_to_json_large_numbers(self, bigNum): + # GH34473 + series = Series(bigNum, dtype=object, index=["articleId"]) + json = series.to_json() + expected = '{"articleId":' + str(bigNum) + "}" + assert json == expected + # GH 20599 + with pytest.raises(ValueError): + json = StringIO(json) + result = read_json(json) + tm.assert_series_equal(series, result) + + df = DataFrame(bigNum, dtype=object, index=["articleId"], columns=[0]) + json = df.to_json() + expected = '{"0":{"articleId":' + str(bigNum) + "}}" + assert json == expected + # GH 20599 + with pytest.raises(ValueError): + json = StringIO(json) + result = read_json(json) + tm.assert_frame_equal(df, result) + def test_read_json_large_numbers(self): # GH18842 json = '{"articleId": "1404366058080022500245"}' diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 7dc73d5be1538..e1a136e1a3728 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -5,6 +5,7 @@ import locale import math import re +import sys import time import dateutil @@ -559,6 +560,17 @@ def test_encode_long_conversion(self): assert output == json.dumps(long_input) assert long_input == ujson.decode(output) + @pytest.mark.parametrize("bigNum", [sys.maxsize + 1, -(sys.maxsize + 2)]) + def test_dumps_ints_larger_than_maxsize(self, bigNum): + # GH34395 + bigNum = sys.maxsize + 1 + encoding = ujson.encode(bigNum) + assert str(bigNum) == encoding + + # GH20599 + with pytest.raises(ValueError): + assert ujson.loads(encoding) == bigNum + @pytest.mark.parametrize( "int_exp", ["1337E40", "1.337E40", "1337E+9", "1.337e+40", "1.337E-4"] ) @@ -570,18 +582,6 @@ def test_loads_non_str_bytes_raises(self): with pytest.raises(TypeError, match=msg): ujson.loads(None) - def test_encode_numeric_overflow(self): - with pytest.raises(OverflowError): - ujson.encode(12839128391289382193812939) - - def test_encode_numeric_overflow_nested(self): - class Nested: - x = 12839128391289382193812939 - - for _ in range(0, 100): - with pytest.raises(OverflowError): - ujson.encode(Nested()) - @pytest.mark.parametrize("val", [3590016419, 2 ** 31, 2 ** 32, (2 ** 32) - 1]) def test_decode_number_with_32bit_sign_bit(self, val): # Test that numbers that fit within 32 bits but would have the
- [x] closes #34395 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] passes performance benchmarks - [x] whatsnew entry Currently this patch causes a significant reduction for a number of the JSON performance benchmarks. A printout of my results is included below. [json_benchmarks_results.txt](https://github.com/pandas-dev/pandas/files/4704831/json_benchmarks_results.txt) I'd love to keep working on this if anybody has ideas for making the solution more efficient!
https://api.github.com/repos/pandas-dev/pandas/pulls/34473
2020-05-30T00:40:35Z
2020-06-24T23:44:41Z
2020-06-24T23:44:41Z
2020-06-26T17:51:37Z
TYP: annotations in plotting code
diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 1358ddf7005a3..b8be8a66a59fd 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -113,7 +113,7 @@ def deregister(): units.registry[unit] = formatter -def _to_ordinalf(tm): +def _to_ordinalf(tm: pydt.time) -> float: tot_sec = tm.hour * 3600 + tm.minute * 60 + tm.second + float(tm.microsecond / 1e6) return tot_sec @@ -160,7 +160,7 @@ class TimeFormatter(Formatter): def __init__(self, locs): self.locs = locs - def __call__(self, x, pos=0): + def __call__(self, x, pos=0) -> str: """ Return the time of day as a formatted string. @@ -1049,7 +1049,7 @@ def set_locs(self, locs): (vmin, vmax) = (vmax, vmin) self._set_default_format(vmin, vmax) - def __call__(self, x, pos=0): + def __call__(self, x, pos=0) -> str: if self.formatdict is None: return "" @@ -1066,7 +1066,7 @@ class TimeSeries_TimedeltaFormatter(Formatter): """ @staticmethod - def format_timedelta_ticks(x, pos, n_decimals): + def format_timedelta_ticks(x, pos, n_decimals: int) -> str: """ Convert seconds to 'D days HH:MM:SS.F' """ @@ -1082,7 +1082,7 @@ def format_timedelta_ticks(x, pos, n_decimals): s = f"{int(d):d} days {s}" return s - def __call__(self, x, pos=0): + def __call__(self, x, pos=0) -> str: (vmin, vmax) = tuple(self.axis.get_view_interval()) n_decimals = int(np.ceil(np.log10(100 * 1e9 / (vmax - vmin)))) if n_decimals > 9: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index e73a109449d62..631760c547985 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -1,7 +1,7 @@ # TODO: Use the fact that axis can have units to simplify the process import functools -from typing import Optional +from typing import TYPE_CHECKING, Optional import numpy as np @@ -20,15 +20,23 @@ TimeSeries_DateLocator, TimeSeries_TimedeltaFormatter, ) -import pandas.tseries.frequencies as frequencies -from pandas.tseries.frequencies import is_subperiod, is_superperiod +from pandas.tseries.frequencies import ( + get_period_alias, + is_subperiod, + is_superperiod, + to_offset, +) from pandas.tseries.offsets import DateOffset +if TYPE_CHECKING: + from pandas import Series, Index # noqa:F401 + + # --------------------------------------------------------------------- # Plotting functions and monkey patches -def _maybe_resample(series, ax, kwargs): +def _maybe_resample(series: "Series", ax, kwargs): # resample against axes freq if necessary freq, ax_freq = _get_freq(ax, series) @@ -42,7 +50,7 @@ def _maybe_resample(series, ax, kwargs): if ax_freq is not None and freq != ax_freq: if is_superperiod(freq, ax_freq): # upsample input series = series.copy() - series.index = series.index.asfreq(ax_freq, how="s") + series.index = series.index.asfreq(ax_freq, how="s") # type: ignore freq = ax_freq elif _is_sup(freq, ax_freq): # one is weekly how = kwargs.pop("how", "last") @@ -161,21 +169,22 @@ def _get_ax_freq(ax): return ax_freq -def get_period_alias(freq) -> Optional[str]: +def _get_period_alias(freq) -> Optional[str]: if isinstance(freq, DateOffset): freq = freq.rule_code else: freq = base_and_stride(freq)[0] - freq = frequencies.get_period_alias(freq) + freq = get_period_alias(freq) return freq -def _get_freq(ax, series): +def _get_freq(ax, series: "Series"): # get frequency from data freq = getattr(series.index, "freq", None) if freq is None: freq = getattr(series.index, "inferred_freq", None) + freq = to_offset(freq) ax_freq = _get_ax_freq(ax) @@ -184,12 +193,12 @@ def _get_freq(ax, series): freq = ax_freq # get the period frequency - freq = get_period_alias(freq) + freq = _get_period_alias(freq) return freq, ax_freq def _use_dynamic_x(ax, data): - freq = _get_index_freq(data) + freq = _get_index_freq(data.index) ax_freq = _get_ax_freq(ax) if freq is None: # convert irregular if axes has freq info @@ -201,7 +210,7 @@ def _use_dynamic_x(ax, data): if freq is None: return False - freq = get_period_alias(freq) + freq = _get_period_alias(freq) if freq is None: return False @@ -216,14 +225,16 @@ def _use_dynamic_x(ax, data): return True -def _get_index_freq(data): - freq = getattr(data.index, "freq", None) +def _get_index_freq(index: "Index") -> Optional[DateOffset]: + freq = getattr(index, "freq", None) if freq is None: - freq = getattr(data.index, "inferred_freq", None) + freq = getattr(index, "inferred_freq", None) if freq == "B": - weekdays = np.unique(data.index.dayofweek) + weekdays = np.unique(index.dayofweek) # type: ignore if (5 in weekdays) or (6 in weekdays): freq = None + + freq = to_offset(freq) return freq @@ -231,10 +242,12 @@ def _maybe_convert_index(ax, data): # tsplot converts automatically, but don't want to convert index # over and over for DataFrames if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)): - freq = getattr(data.index, "freq", None) + freq = data.index.freq if freq is None: - freq = getattr(data.index, "inferred_freq", None) + # We only get here for DatetimeIndex + freq = data.index.inferred_freq + freq = to_offset(freq) if freq is None: freq = _get_ax_freq(ax) @@ -242,7 +255,7 @@ def _maybe_convert_index(ax, data): if freq is None: raise ValueError("Could not get frequency alias for plotting") - freq = get_period_alias(freq) + freq = _get_period_alias(freq) if isinstance(data.index, ABCDatetimeIndex): data = data.tz_localize(None).to_period(freq=freq)
Trying to sort out what is getting passed to the tseries.frequencies funcs in these modules.
https://api.github.com/repos/pandas-dev/pandas/pulls/34469
2020-05-29T22:46:13Z
2020-05-31T23:02:31Z
2020-05-31T23:02:31Z
2020-05-31T23:07:50Z
CLN: drop **kwds from pd.read_excel
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 88bf0e005a221..f320ad97d3dfa 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -394,6 +394,8 @@ Backwards incompatible API changes - :meth:`Series.to_timestamp` now raises a ``TypeError`` if the axis is not a :class:`PeriodIndex`. Previously an ``AttributeError`` was raised (:issue:`33327`) - :meth:`Series.to_period` now raises a ``TypeError`` if the axis is not a :class:`DatetimeIndex`. Previously an ``AttributeError`` was raised (:issue:`33327`) - :func: `pandas.api.dtypes.is_string_dtype` no longer incorrectly identifies categorical series as string. +- :func:`read_excel` no longer takes ``**kwds`` arguments. This means that passing in keyword ``chunksize`` now raises a ``TypeError`` + (previously raised a ``NotImplementedError``), while passing in keyword ``encoding`` now raises a ``TypeError`` (:issue:`34464`) ``MultiIndex.get_indexer`` interprets `method` argument differently ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index d55bdffe689f2..12019c7477fe0 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -193,8 +193,6 @@ Duplicate columns will be specified as 'X', 'X.1', ...'X.N', rather than 'X'...'X'. Passing in False will cause data to be overwritten if there are duplicate names in the columns. -**kwds : optional - Optional keyword arguments can be passed to ``TextFileReader``. Returns ------- @@ -285,6 +283,7 @@ def read_excel( nrows=None, na_values=None, keep_default_na=True, + na_filter=True, verbose=False, parse_dates=False, date_parser=None, @@ -293,13 +292,8 @@ def read_excel( skipfooter=0, convert_float=True, mangle_dupe_cols=True, - **kwds, ): - for arg in ("sheet", "sheetname", "parse_cols"): - if arg in kwds: - raise TypeError(f"read_excel() got an unexpected keyword argument `{arg}`") - if not isinstance(io, ExcelFile): io = ExcelFile(io, engine=engine) elif engine and engine != io.engine: @@ -323,6 +317,7 @@ def read_excel( nrows=nrows, na_values=na_values, keep_default_na=keep_default_na, + na_filter=na_filter, verbose=verbose, parse_dates=parse_dates, date_parser=date_parser, @@ -331,7 +326,6 @@ def read_excel( skipfooter=skipfooter, convert_float=convert_float, mangle_dupe_cols=mangle_dupe_cols, - **kwds, ) @@ -861,11 +855,6 @@ def parse( DataFrame or dict of DataFrames DataFrame from the passed in Excel file. """ - if "chunksize" in kwds: - raise NotImplementedError( - "chunksize keyword of read_excel is not implemented" - ) - return self._reader.parse( sheet_name=sheet_name, header=header, diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index fd1533dd65dc4..109da630f76a2 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -897,12 +897,6 @@ def test_read_excel_bool_header_arg(self, read_ext): with pytest.raises(TypeError, match=msg): pd.read_excel("test1" + read_ext, header=arg) - def test_read_excel_chunksize(self, read_ext): - # GH 8011 - msg = "chunksize keyword of read_excel is not implemented" - with pytest.raises(NotImplementedError, match=msg): - pd.read_excel("test1" + read_ext, chunksize=100) - def test_read_excel_skiprows_list(self, read_ext): # GH 4903 if pd.read_excel.keywords["engine"] == "pyxlsb": @@ -1048,17 +1042,6 @@ def test_excel_passes_na_filter(self, read_ext, na_filter): expected = DataFrame(expected, columns=["Test"]) tm.assert_frame_equal(parsed, expected) - @pytest.mark.parametrize("arg", ["sheet", "sheetname", "parse_cols"]) - @td.check_file_leaks - def test_unexpected_kwargs_raises(self, read_ext, arg): - # gh-17964 - kwarg = {arg: "Sheet1"} - msg = fr"unexpected keyword argument `{arg}`" - - with pd.ExcelFile("test1" + read_ext) as excel: - with pytest.raises(TypeError, match=msg): - pd.read_excel(excel, **kwarg) - def test_excel_table_sheet_by_index(self, read_ext, df_ref): # For some reason pd.read_excel has no attribute 'keywords' here. # Skipping based on read_ext instead. diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index b909f1f3a958f..ba759c7766fa5 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -836,9 +836,7 @@ def test_to_excel_output_encoding(self, ext): with tm.ensure_clean("__tmp_to_excel_float_format__." + ext) as filename: df.to_excel(filename, sheet_name="TestSheet", encoding="utf8") - result = pd.read_excel( - filename, sheet_name="TestSheet", encoding="utf8", index_col=0 - ) + result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0) tm.assert_frame_equal(result, df) def test_to_excel_unicode_filename(self, ext, path):
Drop ``**kwds`` from ``pd.read_excel``. Wrt. "new" keyword parameter ``na_filter``: This parameter already exists in the doc string and is just masked in the ``kwds`` in the signature. If you follow the code paths all the way down to parsers.py, you can see that it indeed has a default of `True``.
https://api.github.com/repos/pandas-dev/pandas/pulls/34464
2020-05-29T21:02:10Z
2020-06-01T15:37:10Z
2020-06-01T15:37:10Z
2020-06-01T16:06:50Z
REF: make Resolution an enum
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index b804ed883e693..7f7dd62540387 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -3598,9 +3598,10 @@ cpdef to_offset(freq): if not stride: stride = 1 - from .resolution import Resolution # TODO: avoid runtime import + # TODO: avoid runtime import + from .resolution import Resolution, reso_str_bump_map - if prefix in Resolution.reso_str_bump_map: + if prefix in reso_str_bump_map: stride, name = Resolution.get_stride_from_decimal( float(stride), prefix ) diff --git a/pandas/_libs/tslibs/resolution.pyx b/pandas/_libs/tslibs/resolution.pyx index 2133573ee7554..b3fc1e32f68e8 100644 --- a/pandas/_libs/tslibs/resolution.pyx +++ b/pandas/_libs/tslibs/resolution.pyx @@ -1,3 +1,5 @@ +from enum import Enum + import numpy as np from numpy cimport ndarray, int64_t, int32_t @@ -25,10 +27,46 @@ cdef: int RESO_HR = 5 int RESO_DAY = 6 +reso_str_bump_map = { + "D": "H", + "H": "T", + "T": "S", + "S": "L", + "L": "U", + "U": "N", + "N": None, +} + +_abbrev_to_attrnames = {v: k for k, v in attrname_to_abbrevs.items()} + +_reso_str_map = { + RESO_NS: "nanosecond", + RESO_US: "microsecond", + RESO_MS: "millisecond", + RESO_SEC: "second", + RESO_MIN: "minute", + RESO_HR: "hour", + RESO_DAY: "day", +} + +_str_reso_map = {v: k for k, v in _reso_str_map.items()} + +# factor to multiply a value by to convert it to the next finer grained +# resolution +_reso_mult_map = { + RESO_NS: None, + RESO_US: 1000, + RESO_MS: 1000, + RESO_SEC: 1000, + RESO_MIN: 60, + RESO_HR: 60, + RESO_DAY: 24, +} # ---------------------------------------------------------------------- -def resolution(const int64_t[:] stamps, tz=None): + +def get_resolution(const int64_t[:] stamps, tz=None): cdef: Py_ssize_t i, n = len(stamps) npy_datetimestruct dts @@ -82,7 +120,7 @@ def resolution(const int64_t[:] stamps, tz=None): if curr_reso < reso: reso = curr_reso - return reso + return Resolution(reso) cdef inline int _reso_stamp(npy_datetimestruct *dts): @@ -99,7 +137,7 @@ cdef inline int _reso_stamp(npy_datetimestruct *dts): return RESO_DAY -class Resolution: +class Resolution(Enum): # Note: cython won't allow us to reference the cdef versions at the # module level @@ -111,41 +149,14 @@ class Resolution: RESO_HR = 5 RESO_DAY = 6 - _reso_str_map = { - RESO_NS: 'nanosecond', - RESO_US: 'microsecond', - RESO_MS: 'millisecond', - RESO_SEC: 'second', - RESO_MIN: 'minute', - RESO_HR: 'hour', - RESO_DAY: 'day'} - - # factor to multiply a value by to convert it to the next finer grained - # resolution - _reso_mult_map = { - RESO_NS: None, - RESO_US: 1000, - RESO_MS: 1000, - RESO_SEC: 1000, - RESO_MIN: 60, - RESO_HR: 60, - RESO_DAY: 24} - - reso_str_bump_map = { - 'D': 'H', - 'H': 'T', - 'T': 'S', - 'S': 'L', - 'L': 'U', - 'U': 'N', - 'N': None} - - _str_reso_map = {v: k for k, v in _reso_str_map.items()} - - _freq_reso_map = {v: k for k, v in attrname_to_abbrevs.items()} + def __lt__(self, other): + return self.value < other.value + + def __ge__(self, other): + return self.value >= other.value @classmethod - def get_str(cls, reso: int) -> str: + def get_str(cls, reso: "Resolution") -> str: """ Return resolution str against resolution code. @@ -154,10 +165,10 @@ class Resolution: >>> Resolution.get_str(Resolution.RESO_SEC) 'second' """ - return cls._reso_str_map.get(reso, 'day') + return _reso_str_map[reso.value] @classmethod - def get_reso(cls, resostr: str) -> int: + def get_reso(cls, resostr: str) -> "Resolution": """ Return resolution str against resolution code. @@ -169,25 +180,27 @@ class Resolution: >>> Resolution.get_reso('second') == Resolution.RESO_SEC True """ - return cls._str_reso_map.get(resostr, cls.RESO_DAY) + return cls(_str_reso_map[resostr]) @classmethod - def get_str_from_freq(cls, freq: str) -> str: + def get_attrname_from_abbrev(cls, freq: str) -> str: """ Return resolution str against frequency str. Examples -------- - >>> Resolution.get_str_from_freq('H') + >>> Resolution.get_attrname_from_abbrev('H') 'hour' """ - return cls._freq_reso_map.get(freq, 'day') + return _abbrev_to_attrnames[freq] @classmethod - def get_reso_from_freq(cls, freq: str) -> int: + def get_reso_from_freq(cls, freq: str) -> "Resolution": """ Return resolution code against frequency str. + `freq` is given by the `offset.freqstr` for some DateOffset object. + Examples -------- >>> Resolution.get_reso_from_freq('H') @@ -196,16 +209,16 @@ class Resolution: >>> Resolution.get_reso_from_freq('H') == Resolution.RESO_HR True """ - return cls.get_reso(cls.get_str_from_freq(freq)) + return cls.get_reso(cls.get_attrname_from_abbrev(freq)) @classmethod - def get_stride_from_decimal(cls, value, freq): + def get_stride_from_decimal(cls, value: float, freq: str): """ Convert freq with decimal stride into a higher freq with integer stride Parameters ---------- - value : int or float + value : float freq : str Frequency string @@ -229,13 +242,13 @@ class Resolution: return int(value), freq else: start_reso = cls.get_reso_from_freq(freq) - if start_reso == 0: + if start_reso.value == 0: raise ValueError( "Could not convert to integer offset at any resolution" ) - next_value = cls._reso_mult_map[start_reso] * value - next_name = cls.reso_str_bump_map[freq] + next_value = _reso_mult_map[start_reso.value] * value + next_name = reso_str_bump_map[freq] return cls.get_stride_from_decimal(next_value, next_name) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index cf3cde155a3bb..b9f712e4d64fe 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1,6 +1,6 @@ from datetime import datetime, timedelta import operator -from typing import Any, Callable, Sequence, Tuple, Type, TypeVar, Union, cast +from typing import Any, Callable, Optional, Sequence, Tuple, Type, TypeVar, Union, cast import warnings import numpy as np @@ -804,7 +804,7 @@ def _validate_scalar(self, value, msg: str, cast_str: bool = False): return value def _validate_listlike( - self, value, opname: str, cast_str: bool = False, allow_object: bool = False, + self, value, opname: str, cast_str: bool = False, allow_object: bool = False ): if isinstance(value, type(self)): return value @@ -1103,14 +1103,22 @@ def inferred_freq(self): return None @property # NB: override with cache_readonly in immutable subclasses - def _resolution(self): - return Resolution.get_reso_from_freq(self.freqstr) + def _resolution(self) -> Optional[Resolution]: + try: + return Resolution.get_reso_from_freq(self.freqstr) + except KeyError: + return None @property # NB: override with cache_readonly in immutable subclasses def resolution(self) -> str: """ Returns day, hour, minute, second, millisecond or microsecond """ + if self._resolution is None: + if is_period_dtype(self.dtype): + # somewhere in the past it was decided we default to day + return "day" + # otherwise we fall through and will raise return Resolution.get_str(self._resolution) @classmethod diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 894a519cb693e..4e31477571a5f 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -538,8 +538,8 @@ def is_normalized(self): return conversion.is_date_array_normalized(self.asi8, self.tz) @property # NB: override with cache_readonly in immutable subclasses - def _resolution(self): - return libresolution.resolution(self.asi8, self.tz) + def _resolution(self) -> libresolution.Resolution: + return libresolution.get_resolution(self.asi8, self.tz) # ---------------------------------------------------------------- # Array-Like / EA-Interface Methods diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py index 1c51ad0c45238..51554854378ea 100644 --- a/pandas/tests/tseries/frequencies/test_freq_code.py +++ b/pandas/tests/tseries/frequencies/test_freq_code.py @@ -104,13 +104,13 @@ def test_get_to_timestamp_base(freqstr, exp_freqstr): ("N", "nanosecond"), ], ) -def test_get_str_from_freq(freqstr, expected): - assert _reso.get_str_from_freq(freqstr) == expected +def test_get_attrname_from_abbrev(freqstr, expected): + assert _reso.get_attrname_from_abbrev(freqstr) == expected @pytest.mark.parametrize("freq", ["A", "Q", "M", "D", "H", "T", "S", "L", "U", "N"]) def test_get_freq_roundtrip(freq): - result = _attrname_to_abbrevs[_reso.get_str_from_freq(freq)] + result = _attrname_to_abbrevs[_reso.get_attrname_from_abbrev(freq)] assert freq == result
I find this much clearer than just using an int. No measured performance impact.
https://api.github.com/repos/pandas-dev/pandas/pulls/34462
2020-05-29T17:41:57Z
2020-05-31T23:22:37Z
2020-05-31T23:22:37Z
2020-06-01T00:02:06Z
mask based multi-index assignment of column values described
diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst index 6db757e726792..6843dd1eadc81 100644 --- a/doc/source/user_guide/indexing.rst +++ b/doc/source/user_guide/indexing.rst @@ -1866,29 +1866,39 @@ A chained assignment can also crop up in setting in a mixed dtype frame. These setting rules apply to all of ``.loc/.iloc``. -This is the correct access method: +The following is the recommended access method using ``.loc`` for multiple items (using ``mask``) and a single item using a fixed index: .. ipython:: python - dfc = pd.DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) - dfc.loc[0, 'A'] = 11 - dfc + dfc = pd.DataFrame({'a': ['one', 'one', 'two', + 'three', 'two', 'one', 'six'], + 'c': np.arange(7)}) + dfd = dfc.copy() + # Setting multiple items using a mask + mask = dfd['a'].str.startswith('o') + dfd.loc[mask, 'c'] = 42 + dfd + + # Setting a single item + dfd = dfc.copy() + dfd.loc[2, 'a'] = 11 + dfd -This *can* work at times, but it is not guaranteed to, and therefore should be avoided: +The following *can* work at times, but it is not guaranteed to, and therefore should be avoided: .. ipython:: python :okwarning: - dfc = dfc.copy() - dfc['A'][0] = 111 - dfc + dfd = dfc.copy() + dfd['a'][2] = 111 + dfd -This will **not** work at all, and so should be avoided: +Last, the subsequent example will **not** work at all, and so should be avoided: :: >>> pd.set_option('mode.chained_assignment','raise') - >>> dfc.loc[0]['A'] = 1111 + >>> dfd.loc[0]['a'] = 1111 Traceback (most recent call last) ... SettingWithCopyException:
- [x] closes #34383 - [x] passes `black pandas` not sure what this means, will look it up. - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - ~~[ ] tests added / passed~~ this is an PR on documentation only, unit tests are not needed. - ~~[ ] whatsnew entry~~ I think I don't need this as this is a PR related to documentation only.
https://api.github.com/repos/pandas-dev/pandas/pulls/34461
2020-05-29T16:04:08Z
2020-06-02T22:57:44Z
2020-06-02T22:57:43Z
2020-06-02T22:57:49Z
CLN: Clean csv files in test data GH34427
diff --git a/doc/source/getting_started/comparison/comparison_with_sas.rst b/doc/source/getting_started/comparison/comparison_with_sas.rst index f12d97d1d0fde..85c6ea2c31969 100644 --- a/doc/source/getting_started/comparison/comparison_with_sas.rst +++ b/doc/source/getting_started/comparison/comparison_with_sas.rst @@ -115,7 +115,7 @@ Reading external data Like SAS, pandas provides utilities for reading in data from many formats. The ``tips`` dataset, found within the pandas -tests (`csv <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv>`_) +tests (`csv <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/io/data/csv/tips.csv>`_) will be used in many of the following examples. SAS provides ``PROC IMPORT`` to read csv data into a data set. @@ -131,7 +131,7 @@ The pandas method is :func:`read_csv`, which works similarly. .. ipython:: python url = ('https://raw.github.com/pandas-dev/' - 'pandas/master/pandas/tests/data/tips.csv') + 'pandas/master/pandas/tests/io/data/csv/tips.csv') tips = pd.read_csv(url) tips.head() diff --git a/doc/source/getting_started/comparison/comparison_with_sql.rst b/doc/source/getting_started/comparison/comparison_with_sql.rst index c46ec9b3f7090..aa7218c3e4fad 100644 --- a/doc/source/getting_started/comparison/comparison_with_sql.rst +++ b/doc/source/getting_started/comparison/comparison_with_sql.rst @@ -25,7 +25,7 @@ structure. .. ipython:: python url = ('https://raw.github.com/pandas-dev' - '/pandas/master/pandas/tests/data/tips.csv') + '/pandas/master/pandas/tests/io/data/csv/tips.csv') tips = pd.read_csv(url) tips.head() diff --git a/doc/source/getting_started/comparison/comparison_with_stata.rst b/doc/source/getting_started/comparison/comparison_with_stata.rst index decf12db77af2..06f9e45466243 100644 --- a/doc/source/getting_started/comparison/comparison_with_stata.rst +++ b/doc/source/getting_started/comparison/comparison_with_stata.rst @@ -112,7 +112,7 @@ Reading external data Like Stata, pandas provides utilities for reading in data from many formats. The ``tips`` data set, found within the pandas -tests (`csv <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/tips.csv>`_) +tests (`csv <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/io/data/csv/tips.csv>`_) will be used in many of the following examples. Stata provides ``import delimited`` to read csv data into a data set in memory. @@ -128,7 +128,7 @@ the data set if presented with a url. .. ipython:: python url = ('https://raw.github.com/pandas-dev' - '/pandas/master/pandas/tests/data/tips.csv') + '/pandas/master/pandas/tests/io/data/csv/tips.csv') tips = pd.read_csv(url) tips.head() diff --git a/doc/source/user_guide/visualization.rst b/doc/source/user_guide/visualization.rst index 814627043cfc8..5dca9d4c900dc 100644 --- a/doc/source/user_guide/visualization.rst +++ b/doc/source/user_guide/visualization.rst @@ -865,7 +865,7 @@ for more information. By coloring these curves differently for each class it is possible to visualize data clustering. Curves belonging to samples of the same class will usually be closer together and form larger structures. -**Note**: The "Iris" dataset is available `here <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/iris.csv>`__. +**Note**: The "Iris" dataset is available `here <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/io/data/csv/iris.csv>`__. .. ipython:: python @@ -1025,7 +1025,7 @@ be colored differently. See the R package `Radviz <https://cran.r-project.org/package=Radviz/>`__ for more information. -**Note**: The "Iris" dataset is available `here <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/data/iris.csv>`__. +**Note**: The "Iris" dataset is available `here <https://raw.github.com/pandas-dev/pandas/master/pandas/tests/io/data/csv/iris.csv>`__. .. ipython:: python diff --git a/pandas/conftest.py b/pandas/conftest.py index 1e7f1b769c856..e4cb3270b9acf 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -813,7 +813,7 @@ def iris(datapath): """ The iris dataset as a DataFrame. """ - return pd.read_csv(datapath("data", "iris.csv")) + return pd.read_csv(datapath("io", "data", "csv", "iris.csv")) # ---------------------------------------------------------------- diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 594b95d1937ea..3056977ec78ad 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -263,7 +263,7 @@ def andrews_curves( >>> df = pd.read_csv( ... 'https://raw.github.com/pandas-dev/' - ... 'pandas/master/pandas/tests/data/iris.csv' + ... 'pandas/master/pandas/tests/io/data/csv/iris.csv' ... ) >>> pd.plotting.andrews_curves(df, 'Name') """ @@ -387,7 +387,7 @@ def parallel_coordinates( >>> df = pd.read_csv( ... 'https://raw.github.com/pandas-dev/' - ... 'pandas/master/pandas/tests/data/iris.csv' + ... 'pandas/master/pandas/tests/io/data/csv/iris.csv' ... ) >>> pd.plotting.parallel_coordinates( ... df, 'Name', color=('#556270', '#4ECDC4', '#C7F464') diff --git a/pandas/tests/data/iris.csv b/pandas/tests/data/iris.csv deleted file mode 100644 index c19b9c3688515..0000000000000 --- a/pandas/tests/data/iris.csv +++ /dev/null @@ -1,151 +0,0 @@ -SepalLength,SepalWidth,PetalLength,PetalWidth,Name -5.1,3.5,1.4,0.2,Iris-setosa -4.9,3.0,1.4,0.2,Iris-setosa -4.7,3.2,1.3,0.2,Iris-setosa -4.6,3.1,1.5,0.2,Iris-setosa -5.0,3.6,1.4,0.2,Iris-setosa -5.4,3.9,1.7,0.4,Iris-setosa -4.6,3.4,1.4,0.3,Iris-setosa -5.0,3.4,1.5,0.2,Iris-setosa -4.4,2.9,1.4,0.2,Iris-setosa -4.9,3.1,1.5,0.1,Iris-setosa -5.4,3.7,1.5,0.2,Iris-setosa -4.8,3.4,1.6,0.2,Iris-setosa -4.8,3.0,1.4,0.1,Iris-setosa -4.3,3.0,1.1,0.1,Iris-setosa -5.8,4.0,1.2,0.2,Iris-setosa -5.7,4.4,1.5,0.4,Iris-setosa -5.4,3.9,1.3,0.4,Iris-setosa -5.1,3.5,1.4,0.3,Iris-setosa -5.7,3.8,1.7,0.3,Iris-setosa -5.1,3.8,1.5,0.3,Iris-setosa -5.4,3.4,1.7,0.2,Iris-setosa -5.1,3.7,1.5,0.4,Iris-setosa -4.6,3.6,1.0,0.2,Iris-setosa -5.1,3.3,1.7,0.5,Iris-setosa -4.8,3.4,1.9,0.2,Iris-setosa -5.0,3.0,1.6,0.2,Iris-setosa -5.0,3.4,1.6,0.4,Iris-setosa -5.2,3.5,1.5,0.2,Iris-setosa -5.2,3.4,1.4,0.2,Iris-setosa -4.7,3.2,1.6,0.2,Iris-setosa -4.8,3.1,1.6,0.2,Iris-setosa -5.4,3.4,1.5,0.4,Iris-setosa -5.2,4.1,1.5,0.1,Iris-setosa -5.5,4.2,1.4,0.2,Iris-setosa -4.9,3.1,1.5,0.1,Iris-setosa -5.0,3.2,1.2,0.2,Iris-setosa -5.5,3.5,1.3,0.2,Iris-setosa -4.9,3.1,1.5,0.1,Iris-setosa -4.4,3.0,1.3,0.2,Iris-setosa -5.1,3.4,1.5,0.2,Iris-setosa -5.0,3.5,1.3,0.3,Iris-setosa -4.5,2.3,1.3,0.3,Iris-setosa -4.4,3.2,1.3,0.2,Iris-setosa -5.0,3.5,1.6,0.6,Iris-setosa -5.1,3.8,1.9,0.4,Iris-setosa -4.8,3.0,1.4,0.3,Iris-setosa -5.1,3.8,1.6,0.2,Iris-setosa -4.6,3.2,1.4,0.2,Iris-setosa -5.3,3.7,1.5,0.2,Iris-setosa -5.0,3.3,1.4,0.2,Iris-setosa -7.0,3.2,4.7,1.4,Iris-versicolor -6.4,3.2,4.5,1.5,Iris-versicolor -6.9,3.1,4.9,1.5,Iris-versicolor -5.5,2.3,4.0,1.3,Iris-versicolor -6.5,2.8,4.6,1.5,Iris-versicolor -5.7,2.8,4.5,1.3,Iris-versicolor -6.3,3.3,4.7,1.6,Iris-versicolor -4.9,2.4,3.3,1.0,Iris-versicolor -6.6,2.9,4.6,1.3,Iris-versicolor -5.2,2.7,3.9,1.4,Iris-versicolor -5.0,2.0,3.5,1.0,Iris-versicolor -5.9,3.0,4.2,1.5,Iris-versicolor -6.0,2.2,4.0,1.0,Iris-versicolor -6.1,2.9,4.7,1.4,Iris-versicolor -5.6,2.9,3.6,1.3,Iris-versicolor -6.7,3.1,4.4,1.4,Iris-versicolor -5.6,3.0,4.5,1.5,Iris-versicolor -5.8,2.7,4.1,1.0,Iris-versicolor -6.2,2.2,4.5,1.5,Iris-versicolor -5.6,2.5,3.9,1.1,Iris-versicolor -5.9,3.2,4.8,1.8,Iris-versicolor -6.1,2.8,4.0,1.3,Iris-versicolor -6.3,2.5,4.9,1.5,Iris-versicolor -6.1,2.8,4.7,1.2,Iris-versicolor -6.4,2.9,4.3,1.3,Iris-versicolor -6.6,3.0,4.4,1.4,Iris-versicolor -6.8,2.8,4.8,1.4,Iris-versicolor -6.7,3.0,5.0,1.7,Iris-versicolor -6.0,2.9,4.5,1.5,Iris-versicolor -5.7,2.6,3.5,1.0,Iris-versicolor -5.5,2.4,3.8,1.1,Iris-versicolor -5.5,2.4,3.7,1.0,Iris-versicolor -5.8,2.7,3.9,1.2,Iris-versicolor -6.0,2.7,5.1,1.6,Iris-versicolor -5.4,3.0,4.5,1.5,Iris-versicolor -6.0,3.4,4.5,1.6,Iris-versicolor -6.7,3.1,4.7,1.5,Iris-versicolor -6.3,2.3,4.4,1.3,Iris-versicolor -5.6,3.0,4.1,1.3,Iris-versicolor -5.5,2.5,4.0,1.3,Iris-versicolor -5.5,2.6,4.4,1.2,Iris-versicolor -6.1,3.0,4.6,1.4,Iris-versicolor -5.8,2.6,4.0,1.2,Iris-versicolor -5.0,2.3,3.3,1.0,Iris-versicolor -5.6,2.7,4.2,1.3,Iris-versicolor -5.7,3.0,4.2,1.2,Iris-versicolor -5.7,2.9,4.2,1.3,Iris-versicolor -6.2,2.9,4.3,1.3,Iris-versicolor -5.1,2.5,3.0,1.1,Iris-versicolor -5.7,2.8,4.1,1.3,Iris-versicolor -6.3,3.3,6.0,2.5,Iris-virginica -5.8,2.7,5.1,1.9,Iris-virginica -7.1,3.0,5.9,2.1,Iris-virginica -6.3,2.9,5.6,1.8,Iris-virginica -6.5,3.0,5.8,2.2,Iris-virginica -7.6,3.0,6.6,2.1,Iris-virginica -4.9,2.5,4.5,1.7,Iris-virginica -7.3,2.9,6.3,1.8,Iris-virginica -6.7,2.5,5.8,1.8,Iris-virginica -7.2,3.6,6.1,2.5,Iris-virginica -6.5,3.2,5.1,2.0,Iris-virginica -6.4,2.7,5.3,1.9,Iris-virginica -6.8,3.0,5.5,2.1,Iris-virginica -5.7,2.5,5.0,2.0,Iris-virginica -5.8,2.8,5.1,2.4,Iris-virginica -6.4,3.2,5.3,2.3,Iris-virginica -6.5,3.0,5.5,1.8,Iris-virginica -7.7,3.8,6.7,2.2,Iris-virginica -7.7,2.6,6.9,2.3,Iris-virginica -6.0,2.2,5.0,1.5,Iris-virginica -6.9,3.2,5.7,2.3,Iris-virginica -5.6,2.8,4.9,2.0,Iris-virginica -7.7,2.8,6.7,2.0,Iris-virginica -6.3,2.7,4.9,1.8,Iris-virginica -6.7,3.3,5.7,2.1,Iris-virginica -7.2,3.2,6.0,1.8,Iris-virginica -6.2,2.8,4.8,1.8,Iris-virginica -6.1,3.0,4.9,1.8,Iris-virginica -6.4,2.8,5.6,2.1,Iris-virginica -7.2,3.0,5.8,1.6,Iris-virginica -7.4,2.8,6.1,1.9,Iris-virginica -7.9,3.8,6.4,2.0,Iris-virginica -6.4,2.8,5.6,2.2,Iris-virginica -6.3,2.8,5.1,1.5,Iris-virginica -6.1,2.6,5.6,1.4,Iris-virginica -7.7,3.0,6.1,2.3,Iris-virginica -6.3,3.4,5.6,2.4,Iris-virginica -6.4,3.1,5.5,1.8,Iris-virginica -6.0,3.0,4.8,1.8,Iris-virginica -6.9,3.1,5.4,2.1,Iris-virginica -6.7,3.1,5.6,2.4,Iris-virginica -6.9,3.1,5.1,2.3,Iris-virginica -5.8,2.7,5.1,1.9,Iris-virginica -6.8,3.2,5.9,2.3,Iris-virginica -6.7,3.3,5.7,2.5,Iris-virginica -6.7,3.0,5.2,2.3,Iris-virginica -6.3,2.5,5.0,1.9,Iris-virginica -6.5,3.0,5.2,2.0,Iris-virginica -6.2,3.4,5.4,2.3,Iris-virginica -5.9,3.0,5.1,1.8,Iris-virginica \ No newline at end of file diff --git a/pandas/tests/data/tips.csv b/pandas/tests/data/tips.csv deleted file mode 100644 index 856a65a69e647..0000000000000 --- a/pandas/tests/data/tips.csv +++ /dev/null @@ -1,245 +0,0 @@ -total_bill,tip,sex,smoker,day,time,size -16.99,1.01,Female,No,Sun,Dinner,2 -10.34,1.66,Male,No,Sun,Dinner,3 -21.01,3.5,Male,No,Sun,Dinner,3 -23.68,3.31,Male,No,Sun,Dinner,2 -24.59,3.61,Female,No,Sun,Dinner,4 -25.29,4.71,Male,No,Sun,Dinner,4 -8.77,2.0,Male,No,Sun,Dinner,2 -26.88,3.12,Male,No,Sun,Dinner,4 -15.04,1.96,Male,No,Sun,Dinner,2 -14.78,3.23,Male,No,Sun,Dinner,2 -10.27,1.71,Male,No,Sun,Dinner,2 -35.26,5.0,Female,No,Sun,Dinner,4 -15.42,1.57,Male,No,Sun,Dinner,2 -18.43,3.0,Male,No,Sun,Dinner,4 -14.83,3.02,Female,No,Sun,Dinner,2 -21.58,3.92,Male,No,Sun,Dinner,2 -10.33,1.67,Female,No,Sun,Dinner,3 -16.29,3.71,Male,No,Sun,Dinner,3 -16.97,3.5,Female,No,Sun,Dinner,3 -20.65,3.35,Male,No,Sat,Dinner,3 -17.92,4.08,Male,No,Sat,Dinner,2 -20.29,2.75,Female,No,Sat,Dinner,2 -15.77,2.23,Female,No,Sat,Dinner,2 -39.42,7.58,Male,No,Sat,Dinner,4 -19.82,3.18,Male,No,Sat,Dinner,2 -17.81,2.34,Male,No,Sat,Dinner,4 -13.37,2.0,Male,No,Sat,Dinner,2 -12.69,2.0,Male,No,Sat,Dinner,2 -21.7,4.3,Male,No,Sat,Dinner,2 -19.65,3.0,Female,No,Sat,Dinner,2 -9.55,1.45,Male,No,Sat,Dinner,2 -18.35,2.5,Male,No,Sat,Dinner,4 -15.06,3.0,Female,No,Sat,Dinner,2 -20.69,2.45,Female,No,Sat,Dinner,4 -17.78,3.27,Male,No,Sat,Dinner,2 -24.06,3.6,Male,No,Sat,Dinner,3 -16.31,2.0,Male,No,Sat,Dinner,3 -16.93,3.07,Female,No,Sat,Dinner,3 -18.69,2.31,Male,No,Sat,Dinner,3 -31.27,5.0,Male,No,Sat,Dinner,3 -16.04,2.24,Male,No,Sat,Dinner,3 -17.46,2.54,Male,No,Sun,Dinner,2 -13.94,3.06,Male,No,Sun,Dinner,2 -9.68,1.32,Male,No,Sun,Dinner,2 -30.4,5.6,Male,No,Sun,Dinner,4 -18.29,3.0,Male,No,Sun,Dinner,2 -22.23,5.0,Male,No,Sun,Dinner,2 -32.4,6.0,Male,No,Sun,Dinner,4 -28.55,2.05,Male,No,Sun,Dinner,3 -18.04,3.0,Male,No,Sun,Dinner,2 -12.54,2.5,Male,No,Sun,Dinner,2 -10.29,2.6,Female,No,Sun,Dinner,2 -34.81,5.2,Female,No,Sun,Dinner,4 -9.94,1.56,Male,No,Sun,Dinner,2 -25.56,4.34,Male,No,Sun,Dinner,4 -19.49,3.51,Male,No,Sun,Dinner,2 -38.01,3.0,Male,Yes,Sat,Dinner,4 -26.41,1.5,Female,No,Sat,Dinner,2 -11.24,1.76,Male,Yes,Sat,Dinner,2 -48.27,6.73,Male,No,Sat,Dinner,4 -20.29,3.21,Male,Yes,Sat,Dinner,2 -13.81,2.0,Male,Yes,Sat,Dinner,2 -11.02,1.98,Male,Yes,Sat,Dinner,2 -18.29,3.76,Male,Yes,Sat,Dinner,4 -17.59,2.64,Male,No,Sat,Dinner,3 -20.08,3.15,Male,No,Sat,Dinner,3 -16.45,2.47,Female,No,Sat,Dinner,2 -3.07,1.0,Female,Yes,Sat,Dinner,1 -20.23,2.01,Male,No,Sat,Dinner,2 -15.01,2.09,Male,Yes,Sat,Dinner,2 -12.02,1.97,Male,No,Sat,Dinner,2 -17.07,3.0,Female,No,Sat,Dinner,3 -26.86,3.14,Female,Yes,Sat,Dinner,2 -25.28,5.0,Female,Yes,Sat,Dinner,2 -14.73,2.2,Female,No,Sat,Dinner,2 -10.51,1.25,Male,No,Sat,Dinner,2 -17.92,3.08,Male,Yes,Sat,Dinner,2 -27.2,4.0,Male,No,Thur,Lunch,4 -22.76,3.0,Male,No,Thur,Lunch,2 -17.29,2.71,Male,No,Thur,Lunch,2 -19.44,3.0,Male,Yes,Thur,Lunch,2 -16.66,3.4,Male,No,Thur,Lunch,2 -10.07,1.83,Female,No,Thur,Lunch,1 -32.68,5.0,Male,Yes,Thur,Lunch,2 -15.98,2.03,Male,No,Thur,Lunch,2 -34.83,5.17,Female,No,Thur,Lunch,4 -13.03,2.0,Male,No,Thur,Lunch,2 -18.28,4.0,Male,No,Thur,Lunch,2 -24.71,5.85,Male,No,Thur,Lunch,2 -21.16,3.0,Male,No,Thur,Lunch,2 -28.97,3.0,Male,Yes,Fri,Dinner,2 -22.49,3.5,Male,No,Fri,Dinner,2 -5.75,1.0,Female,Yes,Fri,Dinner,2 -16.32,4.3,Female,Yes,Fri,Dinner,2 -22.75,3.25,Female,No,Fri,Dinner,2 -40.17,4.73,Male,Yes,Fri,Dinner,4 -27.28,4.0,Male,Yes,Fri,Dinner,2 -12.03,1.5,Male,Yes,Fri,Dinner,2 -21.01,3.0,Male,Yes,Fri,Dinner,2 -12.46,1.5,Male,No,Fri,Dinner,2 -11.35,2.5,Female,Yes,Fri,Dinner,2 -15.38,3.0,Female,Yes,Fri,Dinner,2 -44.3,2.5,Female,Yes,Sat,Dinner,3 -22.42,3.48,Female,Yes,Sat,Dinner,2 -20.92,4.08,Female,No,Sat,Dinner,2 -15.36,1.64,Male,Yes,Sat,Dinner,2 -20.49,4.06,Male,Yes,Sat,Dinner,2 -25.21,4.29,Male,Yes,Sat,Dinner,2 -18.24,3.76,Male,No,Sat,Dinner,2 -14.31,4.0,Female,Yes,Sat,Dinner,2 -14.0,3.0,Male,No,Sat,Dinner,2 -7.25,1.0,Female,No,Sat,Dinner,1 -38.07,4.0,Male,No,Sun,Dinner,3 -23.95,2.55,Male,No,Sun,Dinner,2 -25.71,4.0,Female,No,Sun,Dinner,3 -17.31,3.5,Female,No,Sun,Dinner,2 -29.93,5.07,Male,No,Sun,Dinner,4 -10.65,1.5,Female,No,Thur,Lunch,2 -12.43,1.8,Female,No,Thur,Lunch,2 -24.08,2.92,Female,No,Thur,Lunch,4 -11.69,2.31,Male,No,Thur,Lunch,2 -13.42,1.68,Female,No,Thur,Lunch,2 -14.26,2.5,Male,No,Thur,Lunch,2 -15.95,2.0,Male,No,Thur,Lunch,2 -12.48,2.52,Female,No,Thur,Lunch,2 -29.8,4.2,Female,No,Thur,Lunch,6 -8.52,1.48,Male,No,Thur,Lunch,2 -14.52,2.0,Female,No,Thur,Lunch,2 -11.38,2.0,Female,No,Thur,Lunch,2 -22.82,2.18,Male,No,Thur,Lunch,3 -19.08,1.5,Male,No,Thur,Lunch,2 -20.27,2.83,Female,No,Thur,Lunch,2 -11.17,1.5,Female,No,Thur,Lunch,2 -12.26,2.0,Female,No,Thur,Lunch,2 -18.26,3.25,Female,No,Thur,Lunch,2 -8.51,1.25,Female,No,Thur,Lunch,2 -10.33,2.0,Female,No,Thur,Lunch,2 -14.15,2.0,Female,No,Thur,Lunch,2 -16.0,2.0,Male,Yes,Thur,Lunch,2 -13.16,2.75,Female,No,Thur,Lunch,2 -17.47,3.5,Female,No,Thur,Lunch,2 -34.3,6.7,Male,No,Thur,Lunch,6 -41.19,5.0,Male,No,Thur,Lunch,5 -27.05,5.0,Female,No,Thur,Lunch,6 -16.43,2.3,Female,No,Thur,Lunch,2 -8.35,1.5,Female,No,Thur,Lunch,2 -18.64,1.36,Female,No,Thur,Lunch,3 -11.87,1.63,Female,No,Thur,Lunch,2 -9.78,1.73,Male,No,Thur,Lunch,2 -7.51,2.0,Male,No,Thur,Lunch,2 -14.07,2.5,Male,No,Sun,Dinner,2 -13.13,2.0,Male,No,Sun,Dinner,2 -17.26,2.74,Male,No,Sun,Dinner,3 -24.55,2.0,Male,No,Sun,Dinner,4 -19.77,2.0,Male,No,Sun,Dinner,4 -29.85,5.14,Female,No,Sun,Dinner,5 -48.17,5.0,Male,No,Sun,Dinner,6 -25.0,3.75,Female,No,Sun,Dinner,4 -13.39,2.61,Female,No,Sun,Dinner,2 -16.49,2.0,Male,No,Sun,Dinner,4 -21.5,3.5,Male,No,Sun,Dinner,4 -12.66,2.5,Male,No,Sun,Dinner,2 -16.21,2.0,Female,No,Sun,Dinner,3 -13.81,2.0,Male,No,Sun,Dinner,2 -17.51,3.0,Female,Yes,Sun,Dinner,2 -24.52,3.48,Male,No,Sun,Dinner,3 -20.76,2.24,Male,No,Sun,Dinner,2 -31.71,4.5,Male,No,Sun,Dinner,4 -10.59,1.61,Female,Yes,Sat,Dinner,2 -10.63,2.0,Female,Yes,Sat,Dinner,2 -50.81,10.0,Male,Yes,Sat,Dinner,3 -15.81,3.16,Male,Yes,Sat,Dinner,2 -7.25,5.15,Male,Yes,Sun,Dinner,2 -31.85,3.18,Male,Yes,Sun,Dinner,2 -16.82,4.0,Male,Yes,Sun,Dinner,2 -32.9,3.11,Male,Yes,Sun,Dinner,2 -17.89,2.0,Male,Yes,Sun,Dinner,2 -14.48,2.0,Male,Yes,Sun,Dinner,2 -9.6,4.0,Female,Yes,Sun,Dinner,2 -34.63,3.55,Male,Yes,Sun,Dinner,2 -34.65,3.68,Male,Yes,Sun,Dinner,4 -23.33,5.65,Male,Yes,Sun,Dinner,2 -45.35,3.5,Male,Yes,Sun,Dinner,3 -23.17,6.5,Male,Yes,Sun,Dinner,4 -40.55,3.0,Male,Yes,Sun,Dinner,2 -20.69,5.0,Male,No,Sun,Dinner,5 -20.9,3.5,Female,Yes,Sun,Dinner,3 -30.46,2.0,Male,Yes,Sun,Dinner,5 -18.15,3.5,Female,Yes,Sun,Dinner,3 -23.1,4.0,Male,Yes,Sun,Dinner,3 -15.69,1.5,Male,Yes,Sun,Dinner,2 -19.81,4.19,Female,Yes,Thur,Lunch,2 -28.44,2.56,Male,Yes,Thur,Lunch,2 -15.48,2.02,Male,Yes,Thur,Lunch,2 -16.58,4.0,Male,Yes,Thur,Lunch,2 -7.56,1.44,Male,No,Thur,Lunch,2 -10.34,2.0,Male,Yes,Thur,Lunch,2 -43.11,5.0,Female,Yes,Thur,Lunch,4 -13.0,2.0,Female,Yes,Thur,Lunch,2 -13.51,2.0,Male,Yes,Thur,Lunch,2 -18.71,4.0,Male,Yes,Thur,Lunch,3 -12.74,2.01,Female,Yes,Thur,Lunch,2 -13.0,2.0,Female,Yes,Thur,Lunch,2 -16.4,2.5,Female,Yes,Thur,Lunch,2 -20.53,4.0,Male,Yes,Thur,Lunch,4 -16.47,3.23,Female,Yes,Thur,Lunch,3 -26.59,3.41,Male,Yes,Sat,Dinner,3 -38.73,3.0,Male,Yes,Sat,Dinner,4 -24.27,2.03,Male,Yes,Sat,Dinner,2 -12.76,2.23,Female,Yes,Sat,Dinner,2 -30.06,2.0,Male,Yes,Sat,Dinner,3 -25.89,5.16,Male,Yes,Sat,Dinner,4 -48.33,9.0,Male,No,Sat,Dinner,4 -13.27,2.5,Female,Yes,Sat,Dinner,2 -28.17,6.5,Female,Yes,Sat,Dinner,3 -12.9,1.1,Female,Yes,Sat,Dinner,2 -28.15,3.0,Male,Yes,Sat,Dinner,5 -11.59,1.5,Male,Yes,Sat,Dinner,2 -7.74,1.44,Male,Yes,Sat,Dinner,2 -30.14,3.09,Female,Yes,Sat,Dinner,4 -12.16,2.2,Male,Yes,Fri,Lunch,2 -13.42,3.48,Female,Yes,Fri,Lunch,2 -8.58,1.92,Male,Yes,Fri,Lunch,1 -15.98,3.0,Female,No,Fri,Lunch,3 -13.42,1.58,Male,Yes,Fri,Lunch,2 -16.27,2.5,Female,Yes,Fri,Lunch,2 -10.09,2.0,Female,Yes,Fri,Lunch,2 -20.45,3.0,Male,No,Sat,Dinner,4 -13.28,2.72,Male,No,Sat,Dinner,2 -22.12,2.88,Female,Yes,Sat,Dinner,2 -24.01,2.0,Male,Yes,Sat,Dinner,4 -15.69,3.0,Male,Yes,Sat,Dinner,3 -11.61,3.39,Male,No,Sat,Dinner,2 -10.77,1.47,Male,No,Sat,Dinner,2 -15.53,3.0,Male,Yes,Sat,Dinner,2 -10.07,1.25,Male,No,Sat,Dinner,2 -12.6,1.0,Male,Yes,Sat,Dinner,2 -32.83,1.17,Male,Yes,Sat,Dinner,2 -35.83,4.67,Female,No,Sat,Dinner,3 -29.03,5.92,Male,No,Sat,Dinner,3 -27.18,2.0,Female,Yes,Sat,Dinner,2 -22.67,2.0,Male,Yes,Sat,Dinner,2 -17.82,1.75,Male,No,Sat,Dinner,2 -18.78,3.0,Female,No,Thur,Dinner,2 diff --git a/pandas/tests/io/parser/data/iris.csv b/pandas/tests/io/parser/data/iris.csv deleted file mode 100644 index c19b9c3688515..0000000000000 --- a/pandas/tests/io/parser/data/iris.csv +++ /dev/null @@ -1,151 +0,0 @@ -SepalLength,SepalWidth,PetalLength,PetalWidth,Name -5.1,3.5,1.4,0.2,Iris-setosa -4.9,3.0,1.4,0.2,Iris-setosa -4.7,3.2,1.3,0.2,Iris-setosa -4.6,3.1,1.5,0.2,Iris-setosa -5.0,3.6,1.4,0.2,Iris-setosa -5.4,3.9,1.7,0.4,Iris-setosa -4.6,3.4,1.4,0.3,Iris-setosa -5.0,3.4,1.5,0.2,Iris-setosa -4.4,2.9,1.4,0.2,Iris-setosa -4.9,3.1,1.5,0.1,Iris-setosa -5.4,3.7,1.5,0.2,Iris-setosa -4.8,3.4,1.6,0.2,Iris-setosa -4.8,3.0,1.4,0.1,Iris-setosa -4.3,3.0,1.1,0.1,Iris-setosa -5.8,4.0,1.2,0.2,Iris-setosa -5.7,4.4,1.5,0.4,Iris-setosa -5.4,3.9,1.3,0.4,Iris-setosa -5.1,3.5,1.4,0.3,Iris-setosa -5.7,3.8,1.7,0.3,Iris-setosa -5.1,3.8,1.5,0.3,Iris-setosa -5.4,3.4,1.7,0.2,Iris-setosa -5.1,3.7,1.5,0.4,Iris-setosa -4.6,3.6,1.0,0.2,Iris-setosa -5.1,3.3,1.7,0.5,Iris-setosa -4.8,3.4,1.9,0.2,Iris-setosa -5.0,3.0,1.6,0.2,Iris-setosa -5.0,3.4,1.6,0.4,Iris-setosa -5.2,3.5,1.5,0.2,Iris-setosa -5.2,3.4,1.4,0.2,Iris-setosa -4.7,3.2,1.6,0.2,Iris-setosa -4.8,3.1,1.6,0.2,Iris-setosa -5.4,3.4,1.5,0.4,Iris-setosa -5.2,4.1,1.5,0.1,Iris-setosa -5.5,4.2,1.4,0.2,Iris-setosa -4.9,3.1,1.5,0.1,Iris-setosa -5.0,3.2,1.2,0.2,Iris-setosa -5.5,3.5,1.3,0.2,Iris-setosa -4.9,3.1,1.5,0.1,Iris-setosa -4.4,3.0,1.3,0.2,Iris-setosa -5.1,3.4,1.5,0.2,Iris-setosa -5.0,3.5,1.3,0.3,Iris-setosa -4.5,2.3,1.3,0.3,Iris-setosa -4.4,3.2,1.3,0.2,Iris-setosa -5.0,3.5,1.6,0.6,Iris-setosa -5.1,3.8,1.9,0.4,Iris-setosa -4.8,3.0,1.4,0.3,Iris-setosa -5.1,3.8,1.6,0.2,Iris-setosa -4.6,3.2,1.4,0.2,Iris-setosa -5.3,3.7,1.5,0.2,Iris-setosa -5.0,3.3,1.4,0.2,Iris-setosa -7.0,3.2,4.7,1.4,Iris-versicolor -6.4,3.2,4.5,1.5,Iris-versicolor -6.9,3.1,4.9,1.5,Iris-versicolor -5.5,2.3,4.0,1.3,Iris-versicolor -6.5,2.8,4.6,1.5,Iris-versicolor -5.7,2.8,4.5,1.3,Iris-versicolor -6.3,3.3,4.7,1.6,Iris-versicolor -4.9,2.4,3.3,1.0,Iris-versicolor -6.6,2.9,4.6,1.3,Iris-versicolor -5.2,2.7,3.9,1.4,Iris-versicolor -5.0,2.0,3.5,1.0,Iris-versicolor -5.9,3.0,4.2,1.5,Iris-versicolor -6.0,2.2,4.0,1.0,Iris-versicolor -6.1,2.9,4.7,1.4,Iris-versicolor -5.6,2.9,3.6,1.3,Iris-versicolor -6.7,3.1,4.4,1.4,Iris-versicolor -5.6,3.0,4.5,1.5,Iris-versicolor -5.8,2.7,4.1,1.0,Iris-versicolor -6.2,2.2,4.5,1.5,Iris-versicolor -5.6,2.5,3.9,1.1,Iris-versicolor -5.9,3.2,4.8,1.8,Iris-versicolor -6.1,2.8,4.0,1.3,Iris-versicolor -6.3,2.5,4.9,1.5,Iris-versicolor -6.1,2.8,4.7,1.2,Iris-versicolor -6.4,2.9,4.3,1.3,Iris-versicolor -6.6,3.0,4.4,1.4,Iris-versicolor -6.8,2.8,4.8,1.4,Iris-versicolor -6.7,3.0,5.0,1.7,Iris-versicolor -6.0,2.9,4.5,1.5,Iris-versicolor -5.7,2.6,3.5,1.0,Iris-versicolor -5.5,2.4,3.8,1.1,Iris-versicolor -5.5,2.4,3.7,1.0,Iris-versicolor -5.8,2.7,3.9,1.2,Iris-versicolor -6.0,2.7,5.1,1.6,Iris-versicolor -5.4,3.0,4.5,1.5,Iris-versicolor -6.0,3.4,4.5,1.6,Iris-versicolor -6.7,3.1,4.7,1.5,Iris-versicolor -6.3,2.3,4.4,1.3,Iris-versicolor -5.6,3.0,4.1,1.3,Iris-versicolor -5.5,2.5,4.0,1.3,Iris-versicolor -5.5,2.6,4.4,1.2,Iris-versicolor -6.1,3.0,4.6,1.4,Iris-versicolor -5.8,2.6,4.0,1.2,Iris-versicolor -5.0,2.3,3.3,1.0,Iris-versicolor -5.6,2.7,4.2,1.3,Iris-versicolor -5.7,3.0,4.2,1.2,Iris-versicolor -5.7,2.9,4.2,1.3,Iris-versicolor -6.2,2.9,4.3,1.3,Iris-versicolor -5.1,2.5,3.0,1.1,Iris-versicolor -5.7,2.8,4.1,1.3,Iris-versicolor -6.3,3.3,6.0,2.5,Iris-virginica -5.8,2.7,5.1,1.9,Iris-virginica -7.1,3.0,5.9,2.1,Iris-virginica -6.3,2.9,5.6,1.8,Iris-virginica -6.5,3.0,5.8,2.2,Iris-virginica -7.6,3.0,6.6,2.1,Iris-virginica -4.9,2.5,4.5,1.7,Iris-virginica -7.3,2.9,6.3,1.8,Iris-virginica -6.7,2.5,5.8,1.8,Iris-virginica -7.2,3.6,6.1,2.5,Iris-virginica -6.5,3.2,5.1,2.0,Iris-virginica -6.4,2.7,5.3,1.9,Iris-virginica -6.8,3.0,5.5,2.1,Iris-virginica -5.7,2.5,5.0,2.0,Iris-virginica -5.8,2.8,5.1,2.4,Iris-virginica -6.4,3.2,5.3,2.3,Iris-virginica -6.5,3.0,5.5,1.8,Iris-virginica -7.7,3.8,6.7,2.2,Iris-virginica -7.7,2.6,6.9,2.3,Iris-virginica -6.0,2.2,5.0,1.5,Iris-virginica -6.9,3.2,5.7,2.3,Iris-virginica -5.6,2.8,4.9,2.0,Iris-virginica -7.7,2.8,6.7,2.0,Iris-virginica -6.3,2.7,4.9,1.8,Iris-virginica -6.7,3.3,5.7,2.1,Iris-virginica -7.2,3.2,6.0,1.8,Iris-virginica -6.2,2.8,4.8,1.8,Iris-virginica -6.1,3.0,4.9,1.8,Iris-virginica -6.4,2.8,5.6,2.1,Iris-virginica -7.2,3.0,5.8,1.6,Iris-virginica -7.4,2.8,6.1,1.9,Iris-virginica -7.9,3.8,6.4,2.0,Iris-virginica -6.4,2.8,5.6,2.2,Iris-virginica -6.3,2.8,5.1,1.5,Iris-virginica -6.1,2.6,5.6,1.4,Iris-virginica -7.7,3.0,6.1,2.3,Iris-virginica -6.3,3.4,5.6,2.4,Iris-virginica -6.4,3.1,5.5,1.8,Iris-virginica -6.0,3.0,4.8,1.8,Iris-virginica -6.9,3.1,5.4,2.1,Iris-virginica -6.7,3.1,5.6,2.4,Iris-virginica -6.9,3.1,5.1,2.3,Iris-virginica -5.8,2.7,5.1,1.9,Iris-virginica -6.8,3.2,5.9,2.3,Iris-virginica -6.7,3.3,5.7,2.5,Iris-virginica -6.7,3.0,5.2,2.3,Iris-virginica -6.3,2.5,5.0,1.9,Iris-virginica -6.5,3.0,5.2,2.0,Iris-virginica -6.2,3.4,5.4,2.3,Iris-virginica -5.9,3.0,5.1,1.8,Iris-virginica \ No newline at end of file diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index b27b028694d20..6f1d4daeb39cb 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -207,8 +207,8 @@ def test_read_expands_user_home_dir( @pytest.mark.parametrize( "reader, module, path", [ - (pd.read_csv, "os", ("data", "iris.csv")), - (pd.read_table, "os", ("data", "iris.csv")), + (pd.read_csv, "os", ("io", "data", "csv", "iris.csv")), + (pd.read_table, "os", ("io", "data", "csv", "iris.csv")), ( pd.read_fwf, "os", diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index bd53785e89bfe..7d4716e1b7d0c 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -278,7 +278,7 @@ def _get_exec(self): else: return self.conn.cursor() - @pytest.fixture(params=[("data", "iris.csv")]) + @pytest.fixture(params=[("io", "data", "csv", "iris.csv")]) def load_iris_data(self, datapath, request): import io diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index 8860e6fe272ce..d73a789b876f4 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -58,7 +58,7 @@ def test_datapath_missing(datapath): def test_datapath(datapath): - args = ("data", "iris.csv") + args = ("io", "data", "csv", "iris.csv") result = datapath(*args) expected = os.path.join(os.path.dirname(os.path.dirname(__file__)), *args)
- [x] closes #34427 - [x] tests passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry I deleted the `iris.csv` and `tips.csv` files which are unused duplicates (i.e. those in `pandas/tests/io/data/csv`).
https://api.github.com/repos/pandas-dev/pandas/pulls/34458
2020-05-29T12:30:26Z
2020-06-05T23:04:24Z
2020-06-05T23:04:24Z
2020-06-09T11:51:08Z
TST/REF: refactor the arithmetic tests for IntegerArray
diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 18f1dac3c13b2..a6c47f3192175 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -1,302 +1,355 @@ +import operator + import numpy as np import pytest import pandas as pd import pandas._testing as tm -from pandas.api.types import is_float, is_float_dtype, is_scalar -from pandas.core.arrays import IntegerArray, integer_array -from pandas.tests.extension.base import BaseOpsUtil - - -class TestArithmeticOps(BaseOpsUtil): - def _check_divmod_op(self, s, op, other, exc=None): - super()._check_divmod_op(s, op, other, None) - - def _check_op(self, s, op_name, other, exc=None): - op = self.get_op_from_name(op_name) - result = op(s, other) - - # compute expected - mask = s.isna() - - # if s is a DataFrame, squeeze to a Series - # for comparison - if isinstance(s, pd.DataFrame): - result = result.squeeze() - s = s.squeeze() - mask = mask.squeeze() - - # other array is an Integer - if isinstance(other, IntegerArray): - omask = getattr(other, "mask", None) - mask = getattr(other, "data", other) - if omask is not None: - mask |= omask - - # 1 ** na is na, so need to unmask those - if op_name == "__pow__": - mask = np.where(~s.isna() & (s == 1), False, mask) - - elif op_name == "__rpow__": - other_is_one = other == 1 - if isinstance(other_is_one, pd.Series): - other_is_one = other_is_one.fillna(False) - mask = np.where(other_is_one, False, mask) - - # float result type or float op - if ( - is_float_dtype(other) - or is_float(other) - or op_name in ["__rtruediv__", "__truediv__", "__rdiv__", "__div__"] - ): - rs = s.astype("float") - expected = op(rs, other) - self._check_op_float(result, expected, mask, s, op_name, other) - - # integer result type +from pandas.core.arrays import ExtensionArray, integer_array +import pandas.core.ops as ops + + +# TODO need to use existing utility function or move this somewhere central +def get_op_from_name(op_name): + short_opname = op_name.strip("_") + try: + op = getattr(operator, short_opname) + except AttributeError: + # Assume it is the reverse operator + rop = getattr(operator, short_opname[1:]) + op = lambda x, y: rop(y, x) + + return op + + +# Basic test for the arithmetic array ops +# ----------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "opname, exp", + [("add", [1, 3, None, None, 9]), ("mul", [0, 2, None, None, 20])], + ids=["add", "mul"], +) +def test_add_mul(dtype, opname, exp): + a = pd.array([0, 1, None, 3, 4], dtype=dtype) + b = pd.array([1, 2, 3, None, 5], dtype=dtype) + + # array / array + expected = pd.array(exp, dtype=dtype) + + op = getattr(operator, opname) + result = op(a, b) + tm.assert_extension_array_equal(result, expected) + + op = getattr(ops, "r" + opname) + result = op(a, b) + tm.assert_extension_array_equal(result, expected) + + +def test_sub(dtype): + a = pd.array([1, 2, 3, None, 5], dtype=dtype) + b = pd.array([0, 1, None, 3, 4], dtype=dtype) + + result = a - b + expected = pd.array([1, 1, None, None, 1], dtype=dtype) + tm.assert_extension_array_equal(result, expected) + + +def test_div(dtype): + # for now division gives a float numpy array + a = pd.array([1, 2, 3, None, 5], dtype=dtype) + b = pd.array([0, 1, None, 3, 4], dtype=dtype) + + result = a / b + expected = np.array([np.inf, 2, np.nan, np.nan, 1.25], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + +@pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)]) +def test_divide_by_zero(zero, negative): + # https://github.com/pandas-dev/pandas/issues/27398 + a = pd.array([0, 1, -1, None], dtype="Int64") + result = a / zero + expected = np.array([np.nan, np.inf, -np.inf, np.nan]) + if negative: + expected *= -1 + tm.assert_numpy_array_equal(result, expected) + + +def test_floordiv(dtype): + a = pd.array([1, 2, 3, None, 5], dtype=dtype) + b = pd.array([0, 1, None, 3, 4], dtype=dtype) + + result = a // b + # Series op sets 1//0 to np.inf, which IntegerArray does not do (yet) + expected = pd.array([0, 2, None, None, 1], dtype=dtype) + tm.assert_extension_array_equal(result, expected) + + +def test_mod(dtype): + a = pd.array([1, 2, 3, None, 5], dtype=dtype) + b = pd.array([0, 1, None, 3, 4], dtype=dtype) + + result = a % b + expected = pd.array([0, 0, None, None, 1], dtype=dtype) + tm.assert_extension_array_equal(result, expected) + + +def test_pow_scalar(): + a = pd.array([-1, 0, 1, None, 2], dtype="Int64") + result = a ** 0 + expected = pd.array([1, 1, 1, 1, 1], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = a ** 1 + expected = pd.array([-1, 0, 1, None, 2], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = a ** pd.NA + expected = pd.array([None, None, 1, None, None], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = a ** np.nan + expected = np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + # reversed + a = a[1:] # Can't raise integers to negative powers. + + result = 0 ** a + expected = pd.array([1, 0, None, 0], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = 1 ** a + expected = pd.array([1, 1, 1, 1], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = pd.NA ** a + expected = pd.array([1, None, None, None], dtype="Int64") + tm.assert_extension_array_equal(result, expected) + + result = np.nan ** a + expected = np.array([1, np.nan, np.nan, np.nan], dtype="float64") + tm.assert_numpy_array_equal(result, expected) + + +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]) + result = a ** b + expected = integer_array([1, 0, None, 1, 1, 1, 1, None, None]) + tm.assert_extension_array_equal(result, expected) + + +def test_rpow_one_to_na(): + # https://github.com/pandas-dev/pandas/issues/22022 + # https://github.com/pandas-dev/pandas/issues/29997 + arr = integer_array([np.nan, np.nan]) + result = np.array([1.0, 2.0]) ** arr + expected = np.array([1.0, np.nan]) + tm.assert_numpy_array_equal(result, expected) + + +# Test equivalence of scalars, numpy arrays with array ops +# ----------------------------------------------------------------------------- + + +def test_array_scalar_like_equivalence(data, all_arithmetic_operators): + op = get_op_from_name(all_arithmetic_operators) + + scalar = 2 + scalar_array = pd.array([2] * len(data), dtype=data.dtype) + + # TODO also add len-1 array (np.array([2], dtype=data.dtype.numpy_dtype)) + for scalar in [2, data.dtype.type(2)]: + result = op(data, scalar) + expected = op(data, scalar_array) + if isinstance(expected, ExtensionArray): + tm.assert_extension_array_equal(result, expected) else: - rs = pd.Series(s.values._data, name=s.name) - expected = op(rs, other) - self._check_op_integer(result, expected, mask, s, op_name, other) - - def _check_op_float(self, result, expected, mask, s, op_name, other): - # check comparisons that are resulting in float dtypes - - expected[mask] = np.nan - if "floordiv" in op_name: - # Series op sets 1//0 to np.inf, which IntegerArray does not do (yet) - mask2 = np.isinf(expected) & np.isnan(result) - expected[mask2] = np.nan - tm.assert_series_equal(result, expected) - - def _check_op_integer(self, result, expected, mask, s, op_name, other): - # check comparisons that are resulting in integer dtypes - - # to compare properly, we convert the expected - # to float, mask to nans and convert infs - # if we have uints then we process as uints - # then convert to float - # and we ultimately want to create a IntArray - # for comparisons - - fill_value = 0 - - # mod/rmod turn floating 0 into NaN while - # integer works as expected (no nan) - if op_name in ["__mod__", "__rmod__"]: - if is_scalar(other): - if other == 0: - expected[s.values == 0] = 0 - else: - expected = expected.fillna(0) - else: - expected[ - (s.values == 0).fillna(False) - & ((expected == 0).fillna(False) | expected.isna()) - ] = 0 - try: - expected[ - ((expected == np.inf) | (expected == -np.inf)).fillna(False) - ] = fill_value - original = expected - expected = expected.astype(s.dtype) - - except ValueError: - - expected = expected.astype(float) - expected[ - ((expected == np.inf) | (expected == -np.inf)).fillna(False) - ] = fill_value - original = expected - expected = expected.astype(s.dtype) - - expected[mask] = pd.NA - - # assert that the expected astype is ok - # (skip for unsigned as they have wrap around) - if not s.dtype.is_unsigned_integer: - original = pd.Series(original) - - # we need to fill with 0's to emulate what an astype('int') does - # (truncation) for certain ops - if op_name in ["__rtruediv__", "__rdiv__"]: - mask |= original.isna() - original = original.fillna(0).astype("int") - - original = original.astype("float") - original[mask] = np.nan - tm.assert_series_equal(original, expected.astype("float")) - - # assert our expected result - tm.assert_series_equal(result, expected) - - def test_arith_integer_array(self, data, all_arithmetic_operators): - # we operate with a rhs of an integer array - - op = all_arithmetic_operators + # TODO div still gives float ndarray -> remove this once we have Float EA + tm.assert_numpy_array_equal(result, expected) - s = pd.Series(data) - rhs = pd.Series([1] * len(data), dtype=data.dtype) - rhs.iloc[-1] = np.nan - self._check_op(s, op, rhs) +def test_array_NA(data, all_arithmetic_operators): + if "truediv" in all_arithmetic_operators: + pytest.skip("division with pd.NA raises") + op = get_op_from_name(all_arithmetic_operators) - def test_arith_series_with_scalar(self, data, all_arithmetic_operators): - # scalar - op = all_arithmetic_operators - s = pd.Series(data) - self._check_op(s, op, 1, exc=TypeError) + scalar = pd.NA + scalar_array = pd.array([pd.NA] * len(data), dtype=data.dtype) - def test_arith_frame_with_scalar(self, data, all_arithmetic_operators): - # frame & scalar - op = all_arithmetic_operators - df = pd.DataFrame({"A": data}) - self._check_op(df, op, 1, exc=TypeError) + result = op(data, scalar) + expected = op(data, scalar_array) + tm.assert_extension_array_equal(result, expected) - def test_arith_series_with_array(self, data, all_arithmetic_operators): - # ndarray & other series - op = all_arithmetic_operators - s = pd.Series(data) - other = np.ones(len(s), dtype=s.dtype.type) - self._check_op(s, op, other, exc=TypeError) - def test_arith_coerce_scalar(self, data, all_arithmetic_operators): +def test_numpy_array_equivalence(data, all_arithmetic_operators): + op = get_op_from_name(all_arithmetic_operators) - op = all_arithmetic_operators - s = pd.Series(data) + numpy_array = np.array([2] * len(data), dtype=data.dtype.numpy_dtype) + pd_array = pd.array(numpy_array, dtype=data.dtype) + + result = op(data, numpy_array) + expected = op(data, pd_array) + if isinstance(expected, ExtensionArray): + tm.assert_extension_array_equal(result, expected) + else: + # TODO div still gives float ndarray -> remove this once we have Float EA + tm.assert_numpy_array_equal(result, expected) - other = 0.01 - self._check_op(s, op, other) - @pytest.mark.parametrize("other", [1.0, np.array(1.0)]) - def test_arithmetic_conversion(self, all_arithmetic_operators, other): - # if we have a float operand we should have a float result - # if that is equal to an integer - op = self.get_op_from_name(all_arithmetic_operators) +@pytest.mark.parametrize("other", [0, 0.5]) +def test_numpy_zero_dim_ndarray(other): + arr = integer_array([1, None, 2]) + result = arr + np.array(other) + expected = arr + other + tm.assert_equal(result, expected) - s = pd.Series([1, 2, 3], dtype="Int64") - result = op(s, other) - assert result.dtype is np.dtype("float") - def test_arith_len_mismatch(self, all_arithmetic_operators): - # operating with a list-like with non-matching length raises - op = self.get_op_from_name(all_arithmetic_operators) - other = np.array([1.0]) +# Test equivalence with Series and DataFrame ops +# ----------------------------------------------------------------------------- - s = pd.Series([1, 2, 3], dtype="Int64") - with pytest.raises(ValueError, match="Lengths must match"): - op(s, other) - @pytest.mark.parametrize("other", [0, 0.5]) - def test_arith_zero_dim_ndarray(self, other): - arr = integer_array([1, None, 2]) - result = arr + np.array(other) - expected = arr + other - tm.assert_equal(result, expected) +def test_frame(data, all_arithmetic_operators): + op = get_op_from_name(all_arithmetic_operators) - def test_error(self, data, all_arithmetic_operators): - # invalid ops + # DataFrame with scalar + df = pd.DataFrame({"A": data}) + scalar = 2 - op = all_arithmetic_operators - s = pd.Series(data) - ops = getattr(s, op) - opa = getattr(data, op) + result = op(df, scalar) + expected = pd.DataFrame({"A": op(data, scalar)}) + tm.assert_frame_equal(result, expected) + + +def test_series(data, all_arithmetic_operators): + op = get_op_from_name(all_arithmetic_operators) + + s = pd.Series(data) + + # Series with scalar + scalar = 2 + result = op(s, scalar) + expected = pd.Series(op(data, scalar)) + tm.assert_series_equal(result, expected) + + # Series with np.ndarray + other = np.ones(len(data), dtype=data.dtype.type) + result = op(s, other) + expected = pd.Series(op(data, other)) + tm.assert_series_equal(result, expected) - # invalid scalars + # Series with pd.array + other = pd.array(np.ones(len(data)), dtype=data.dtype) + result = op(s, other) + expected = pd.Series(op(data, other)) + tm.assert_series_equal(result, expected) + + # Series with Series + other = pd.Series(np.ones(len(data)), dtype=data.dtype) + result = op(s, other) + expected = pd.Series(op(data, other.array)) + tm.assert_series_equal(result, expected) + + +# Test generic charachteristics / errors +# ----------------------------------------------------------------------------- + + +def test_error_invalid_values(data, all_arithmetic_operators): + + op = all_arithmetic_operators + s = pd.Series(data) + ops = getattr(s, op) + + # invalid scalars + msg = ( + r"(:?can only perform ops with numeric values)" + r"|(:?IntegerArray cannot perform the operation mod)" + ) + with pytest.raises(TypeError, match=msg): + ops("foo") + with pytest.raises(TypeError, match=msg): + ops(pd.Timestamp("20180101")) + + # invalid array-likes + with pytest.raises(TypeError, match=msg): + ops(pd.Series("foo", index=s.index)) + + if op != "__rpow__": + # TODO(extension) + # rpow with a datetimelike coerces the integer array incorrectly msg = ( - r"(:?can only perform ops with numeric values)" - r"|(:?IntegerArray cannot perform the operation mod)" + "can only perform ops with numeric values|" + "cannot perform .* with this index type: DatetimeArray|" + "Addition/subtraction of integers and integer-arrays " + "with DatetimeArray is no longer supported. *" ) with pytest.raises(TypeError, match=msg): - ops("foo") - with pytest.raises(TypeError, match=msg): - ops(pd.Timestamp("20180101")) + ops(pd.Series(pd.date_range("20180101", periods=len(s)))) - # invalid array-likes - with pytest.raises(TypeError, match=msg): - ops(pd.Series("foo", index=s.index)) - - if op != "__rpow__": - # TODO(extension) - # rpow with a datetimelike coerces the integer array incorrectly - msg = ( - "can only perform ops with numeric values|" - "cannot perform .* with this index type: DatetimeArray|" - "Addition/subtraction of integers and integer-arrays " - "with DatetimeArray is no longer supported. *" - ) - with pytest.raises(TypeError, match=msg): - ops(pd.Series(pd.date_range("20180101", periods=len(s)))) - - # 2d - result = opa(pd.DataFrame({"A": s})) - assert result is NotImplemented - - msg = r"can only perform ops with 1-d structures" - with pytest.raises(NotImplementedError, match=msg): - opa(np.arange(len(s)).reshape(-1, len(s))) - - @pytest.mark.parametrize("zero, negative", [(0, False), (0.0, False), (-0.0, True)]) - def test_divide_by_zero(self, zero, negative): - # https://github.com/pandas-dev/pandas/issues/27398 - a = pd.array([0, 1, -1, None], dtype="Int64") - result = a / zero - expected = np.array([np.nan, np.inf, -np.inf, np.nan]) - if negative: - expected *= -1 - tm.assert_numpy_array_equal(result, expected) - def test_pow_scalar(self): - a = pd.array([-1, 0, 1, None, 2], dtype="Int64") - result = a ** 0 - expected = pd.array([1, 1, 1, 1, 1], dtype="Int64") - tm.assert_extension_array_equal(result, expected) +def test_error_invalid_object(data, all_arithmetic_operators): - result = a ** 1 - expected = pd.array([-1, 0, 1, None, 2], dtype="Int64") - tm.assert_extension_array_equal(result, expected) + op = all_arithmetic_operators + opa = getattr(data, op) - result = a ** pd.NA - expected = pd.array([None, None, 1, None, None], dtype="Int64") - tm.assert_extension_array_equal(result, expected) + # 2d -> return NotImplemented + result = opa(pd.DataFrame({"A": data})) + assert result is NotImplemented - result = a ** np.nan - expected = np.array([np.nan, np.nan, 1, np.nan, np.nan], dtype="float64") - tm.assert_numpy_array_equal(result, expected) + msg = r"can only perform ops with 1-d structures" + with pytest.raises(NotImplementedError, match=msg): + opa(np.arange(len(data)).reshape(-1, len(data))) - # reversed - a = a[1:] # Can't raise integers to negative powers. - result = 0 ** a - expected = pd.array([1, 0, None, 0], dtype="Int64") - tm.assert_extension_array_equal(result, expected) +def test_error_len_mismatch(all_arithmetic_operators): + # operating with a list-like with non-matching length raises + op = get_op_from_name(all_arithmetic_operators) - result = 1 ** a - expected = pd.array([1, 1, 1, 1], dtype="Int64") - tm.assert_extension_array_equal(result, expected) + data = pd.array([1, 2, 3], dtype="Int64") - result = pd.NA ** a - expected = pd.array([1, None, None, None], dtype="Int64") - tm.assert_extension_array_equal(result, expected) + for other in [[1, 2], np.array([1.0, 2.0])]: + with pytest.raises(ValueError, match="Lengths must match"): + op(data, other) - result = np.nan ** a - expected = np.array([1, np.nan, np.nan, np.nan], dtype="float64") - tm.assert_numpy_array_equal(result, expected) + s = pd.Series(data) + with pytest.raises(ValueError, match="Lengths must match"): + op(s, other) - def test_pow_array(self): - a = integer_array([0, 0, 0, 1, 1, 1, None, None, None]) - b = integer_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]) - tm.assert_extension_array_equal(result, expected) - def test_rpow_one_to_na(self): - # https://github.com/pandas-dev/pandas/issues/22022 - # https://github.com/pandas-dev/pandas/issues/29997 - arr = integer_array([np.nan, np.nan]) - result = np.array([1.0, 2.0]) ** arr - expected = np.array([1.0, np.nan]) - tm.assert_numpy_array_equal(result, expected) +# Various +# ----------------------------------------------------------------------------- + + +# TODO test unsigned overflow + + +def test_arith_coerce_scalar(data, all_arithmetic_operators): + op = get_op_from_name(all_arithmetic_operators) + s = pd.Series(data) + other = 0.01 + + result = op(s, other) + expected = op(s.astype(float), other) + # rfloordiv results in nan instead of inf + if all_arithmetic_operators == "__rfloordiv__": + expected[(expected == np.inf) | (expected == -np.inf)] = np.nan + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("other", [1.0, np.array(1.0)]) +def test_arithmetic_conversion(all_arithmetic_operators, other): + # if we have a float operand we should have a float result + # if that is equal to an integer + op = get_op_from_name(all_arithmetic_operators) + + s = pd.Series([1, 2, 3], dtype="Int64") + result = op(s, other) + assert result.dtype is np.dtype("float") def test_cross_type_arithmetic():
This is an attempt to make the arithmetic tests for the masked arrays more understandable and maintainable (doing it here for IntegerArray as a start, but the idea would be to do the same for BooleanArray, and later FloatingArray as well, and at that point also share some of those tests). The problem with the current `arrays/integer/test_arithmetic.py` is that is quite complex to see what is going on (which I experienced when making a version for FloatingArray in https://github.com/pandas-dev/pandas/pull/34307): for example, there is a huge `_check_op` method that has all the logic to created the expected result, but so this also has all the special cases of all ops combined, making it very difficult to see what is going on or to know what is now exactly tested for a certain op. The reason for this structure is that those tests originally came from the base extension tests in `tests/extension/`, where the tests needed to be very generic. However, we already moved out those tests for IntgerArray, since they were all customized (nothing was still being inherited from the base class), but so we also don't need to maintain the original class structure then. The logic how I constructed the new tests: - I first test each `op` with an explicitly constructed expected result. Here, we test the IntegerArray-specific special cases (like things as `1 ** pd.NA`, or division resulting in a float numpy array, ..). Explicitly writing it down makes it a lot easier to read and to see what is tested (no complex `if op == ...: ..,` constructs, and no complex correcting of expected results based on ndarray) - Those first tests are all with EAs. In a next set of tests, I added tests for array+scalar ops, array+ndarray ops, ... But here, I just rely on creating the expected result with the EA itself (since EA+EA ops were already tested before) - Similar tests for frame+scalar, series+scalar, series+array with the EA dtypes -> rely on the actual EA op for the expected result instead of having `_check_op` handle that as well. cc @dsaxton @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/34454
2020-05-29T11:53:24Z
2020-06-06T08:29:20Z
2020-06-06T08:29:20Z
2020-06-06T08:29:54Z
[ENH] Allow pad, backfill and cumcount in groupby.transform
diff --git a/doc/source/reference/frame.rst b/doc/source/reference/frame.rst index 12b9f67ddb846..e3dfb552651a0 100644 --- a/doc/source/reference/frame.rst +++ b/doc/source/reference/frame.rst @@ -47,8 +47,6 @@ Conversion DataFrame.convert_dtypes DataFrame.infer_objects DataFrame.copy - DataFrame.isna - DataFrame.notna DataFrame.bool Indexing, iteration @@ -211,10 +209,18 @@ Missing data handling .. autosummary:: :toctree: api/ + DataFrame.backfill + DataFrame.bfill DataFrame.dropna + DataFrame.ffill DataFrame.fillna - DataFrame.replace DataFrame.interpolate + DataFrame.isna + DataFrame.isnull + DataFrame.notna + DataFrame.notnull + DataFrame.pad + DataFrame.replace Reshaping, sorting, transposing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/reference/groupby.rst b/doc/source/reference/groupby.rst index ca444dac9d77d..5f6bef2579d27 100644 --- a/doc/source/reference/groupby.rst +++ b/doc/source/reference/groupby.rst @@ -50,6 +50,7 @@ Computations / descriptive stats GroupBy.all GroupBy.any GroupBy.bfill + GroupBy.backfill GroupBy.count GroupBy.cumcount GroupBy.cummax @@ -67,6 +68,7 @@ Computations / descriptive stats GroupBy.ngroup GroupBy.nth GroupBy.ohlc + GroupBy.pad GroupBy.prod GroupBy.rank GroupBy.pct_change @@ -88,10 +90,12 @@ application to columns of a specific data type. DataFrameGroupBy.all DataFrameGroupBy.any + DataFrameGroupBy.backfill DataFrameGroupBy.bfill DataFrameGroupBy.corr DataFrameGroupBy.count DataFrameGroupBy.cov + DataFrameGroupBy.cumcount DataFrameGroupBy.cummax DataFrameGroupBy.cummin DataFrameGroupBy.cumprod @@ -106,6 +110,7 @@ application to columns of a specific data type. DataFrameGroupBy.idxmin DataFrameGroupBy.mad DataFrameGroupBy.nunique + DataFrameGroupBy.pad DataFrameGroupBy.pct_change DataFrameGroupBy.plot DataFrameGroupBy.quantile diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index 797ade9594c7d..3b595ba5ab206 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -214,11 +214,18 @@ Missing data handling .. autosummary:: :toctree: api/ - Series.isna - Series.notna + Series.backfill + Series.bfill Series.dropna + Series.ffill Series.fillna Series.interpolate + Series.isna + Series.isnull + Series.notna + Series.notnull + Series.pad + Series.replace Reshaping, sorting ------------------ diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 88bf0e005a221..59e7c466dab96 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -288,6 +288,7 @@ Other enhancements - :meth:`HDFStore.put` now accepts `track_times` parameter. Parameter is passed to ``create_table`` method of ``PyTables`` (:issue:`32682`). - Make :class:`pandas.core.window.Rolling` and :class:`pandas.core.window.Expanding` iterable(:issue:`11704`) - Make ``option_context`` a :class:`contextlib.ContextDecorator`, which allows it to be used as a decorator over an entire function (:issue:`34253`). +- :meth:`groupby.transform` now allows ``func`` to be ``pad``, ``backfill`` and ``cumcount`` (:issue:`31269`). .. --------------------------------------------------------------------------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0260f30b9e7e2..ee7dfd4c25a89 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6193,6 +6193,8 @@ def ffill( method="ffill", axis=axis, inplace=inplace, limit=limit, downcast=downcast ) + pad = ffill + def bfill( self: FrameOrSeries, axis=None, @@ -6212,6 +6214,8 @@ def bfill( method="bfill", axis=axis, inplace=inplace, limit=limit, downcast=downcast ) + backfill = bfill + @doc(klass=_shared_doc_kwargs["klass"]) def replace( self, diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index ea4b6f4e65341..e47cfddeeaad7 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -483,6 +483,8 @@ def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs): elif func in base.cythonized_kernels: # cythonized transform or canned "agg+broadcast" return getattr(self, func)(*args, **kwargs) + elif func in base.transformation_kernels: + return getattr(self, func)(*args, **kwargs) # If func is a reduction, we need to broadcast the # result to the whole group. Compute func result @@ -1464,6 +1466,8 @@ def transform(self, func, *args, engine="cython", engine_kwargs=None, **kwargs): elif func in base.cythonized_kernels: # cythonized transformation or canned "reduction+broadcast" return getattr(self, func)(*args, **kwargs) + elif func in base.transformation_kernels: + return getattr(self, func)(*args, **kwargs) # GH 30918 # Use _transform_fast only when we know func is an aggregation diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index b3347b3c64e6c..e7bc3801a08a7 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -323,15 +323,22 @@ def test_transform_transformation_func(transformation_func): { "A": ["foo", "foo", "foo", "foo", "bar", "bar", "baz"], "B": [1, 2, np.nan, 3, 3, np.nan, 4], - } + }, + index=pd.date_range("2020-01-01", "2020-01-07"), ) - if transformation_func in ["pad", "backfill", "tshift", "cumcount"]: - # These transformation functions are not yet covered in this test - pytest.xfail("See GH 31269") + if transformation_func == "cumcount": + test_op = lambda x: x.transform("cumcount") + mock_op = lambda x: Series(range(len(x)), x.index) elif transformation_func == "fillna": test_op = lambda x: x.transform("fillna", value=0) mock_op = lambda x: x.fillna(value=0) + elif transformation_func == "tshift": + msg = ( + "Current behavior of groupby.tshift is inconsistent with other " + "transformations. See GH34452 for more details" + ) + pytest.xfail(msg) else: test_op = lambda x: x.transform(transformation_func) mock_op = lambda x: getattr(x, transformation_func)() @@ -340,7 +347,10 @@ def test_transform_transformation_func(transformation_func): groups = [df[["B"]].iloc[:4], df[["B"]].iloc[4:6], df[["B"]].iloc[6:]] expected = concat([mock_op(g) for g in groups]) - tm.assert_frame_equal(result, expected) + if transformation_func == "cumcount": + tm.assert_series_equal(result, expected) + else: + tm.assert_frame_equal(result, expected) def test_transform_select_columns(df):
- [x] closes #31269 - [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/34453
2020-05-29T10:32:25Z
2020-06-03T23:28:12Z
2020-06-03T23:28:11Z
2020-06-04T04:06:48Z
Fix MultiIndex .loc "Too Many Indexers" with None as return value
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5ef1f9dea5091..9c00bc5ea7434 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -811,6 +811,7 @@ Indexing - Bug in :meth:`DataFrame.truncate` and :meth:`Series.truncate` where index was assumed to be monotone increasing (:issue:`33756`) - Indexing with a list of strings representing datetimes failed on :class:`DatetimeIndex` or :class:`PeriodIndex`(:issue:`11278`) - Bug in :meth:`Series.at` when used with a :class:`MultiIndex` would raise an exception on valid inputs (:issue:`26989`) +- Bug in :meth:`Series.loc` when used with a :class:`MultiIndex` would raise an IndexingError when accessing a None value (:issue:`34318`) Missing ^^^^^^^ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 3a146bb0438c5..ee0e9d32c4601 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -766,9 +766,11 @@ def _getitem_lowerdim(self, tup: Tuple): # ...but iloc should handle the tuple as simple integer-location # instead of checking it as multiindex representation (GH 13797) if isinstance(ax0, ABCMultiIndex) and self.name != "iloc": - result = self._handle_lowerdim_multi_index_axis0(tup) - if result is not None: + try: + result = self._handle_lowerdim_multi_index_axis0(tup) return result + except IndexingError: + pass if len(tup) > self.ndim: raise IndexingError("Too many indexers. handle elsewhere") @@ -816,9 +818,11 @@ def _getitem_nested_tuple(self, tup: Tuple): if self.name != "loc": # This should never be reached, but lets be explicit about it raise ValueError("Too many indices") - result = self._handle_lowerdim_multi_index_axis0(tup) - if result is not None: + try: + result = self._handle_lowerdim_multi_index_axis0(tup) return result + except IndexingError: + pass # this is a series with a multi-index specified a tuple of # selectors @@ -1065,7 +1069,7 @@ def _handle_lowerdim_multi_index_axis0(self, tup: Tuple): if len(tup) <= self.obj.index.nlevels and len(tup) > self.ndim: raise ek - return None + raise IndexingError("No label returned") def _getitem_axis(self, key, axis: int): key = item_from_zerodim(key) diff --git a/pandas/tests/series/indexing/test_multiindex.py b/pandas/tests/series/indexing/test_multiindex.py new file mode 100644 index 0000000000000..e98a32d62b767 --- /dev/null +++ b/pandas/tests/series/indexing/test_multiindex.py @@ -0,0 +1,22 @@ +""" test get/set & misc """ + + +import pandas as pd +from pandas import MultiIndex, Series + + +def test_access_none_value_in_multiindex(): + # GH34318: test that you can access a None value using .loc through a Multiindex + + s = Series([None], pd.MultiIndex.from_arrays([["Level1"], ["Level2"]])) + result = s.loc[("Level1", "Level2")] + assert result is None + + midx = MultiIndex.from_product([["Level1"], ["Level2_a", "Level2_b"]]) + s = Series([None] * len(midx), dtype=object, index=midx) + result = s.loc[("Level1", "Level2_a")] + assert result is None + + s = Series([1] * len(midx), dtype=object, index=midx) + result = s.loc[("Level1", "Level2_a")] + assert result == 1
- [x] closes #34318 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Three changes in indexing.py : - function _handle_lowerdim_multi_index_axis0 default return value was None, now it raises an Exception. - function _getitem_lowerdim checks for a raised exception instead of a value None. - function _getitem_nested_tuple checks for a raised exception instead of a value None(had to be changed because it also uses _handle_lowerdim_multi_index_axis0)
https://api.github.com/repos/pandas-dev/pandas/pulls/34450
2020-05-29T02:21:59Z
2020-06-03T18:02:23Z
2020-06-03T18:02:23Z
2020-06-03T18:02:27Z
BUG: Period.to_timestamp not matching PeriodArray.to_timestamp
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index b2b7eb000a2f3..bc190825214c1 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1702,10 +1702,7 @@ cdef class _Period: @property def end_time(self) -> Timestamp: - # freq.n can't be negative or 0 - # ordinal = (self + self.freq.n).start_time.value - 1 - ordinal = (self + self.freq).start_time.value - 1 - return Timestamp(ordinal) + return self.to_timestamp(how="end") def to_timestamp(self, freq=None, how='start', tz=None) -> Timestamp: """ @@ -1727,18 +1724,22 @@ cdef class _Period: ------- Timestamp """ - if freq is not None: - freq = self._maybe_convert_freq(freq) how = validate_end_alias(how) end = how == 'E' if end: + if freq == "B" or self.freq == "B": + # roll forward to ensure we land on B date + adjust = Timedelta(1, "D") - Timedelta(1, "ns") + return self.to_timestamp(how="start") + adjust endpoint = (self + self.freq).to_timestamp(how='start') return endpoint - Timedelta(1, 'ns') if freq is None: base, mult = get_freq_code(self.freq) freq = get_to_timestamp_base(base) + else: + freq = self._maybe_convert_freq(freq) base, mult = get_freq_code(freq) val = self.asfreq(freq, how) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 4601e7fa5389e..3d4b42de01810 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -430,7 +430,7 @@ def to_timestamp(self, freq=None, how="start"): end = how == "E" if end: - if freq == "B": + if freq == "B" or self.freq == "B": # roll forward to ensure we land on B date adjust = Timedelta(1, "D") - Timedelta(1, "ns") return self.to_timestamp(how="start") + adjust diff --git a/pandas/tests/indexes/period/test_scalar_compat.py b/pandas/tests/indexes/period/test_scalar_compat.py index 0f92b7a4e168b..e9d17e7e20778 100644 --- a/pandas/tests/indexes/period/test_scalar_compat.py +++ b/pandas/tests/indexes/period/test_scalar_compat.py @@ -17,3 +17,12 @@ def test_end_time(self): expected_index = date_range("2016-01-01", end="2016-05-31", freq="M") expected_index += Timedelta(1, "D") - Timedelta(1, "ns") tm.assert_index_equal(index.end_time, expected_index) + + def test_end_time_business_friday(self): + # GH#34449 + pi = period_range("1990-01-05", freq="B", periods=1) + result = pi.end_time + + dti = date_range("1990-01-05", freq="D", periods=1)._with_freq(None) + expected = dti + Timedelta(days=1, nanoseconds=-1) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index e81f2ee55eebd..41909b4b1a9bb 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -589,6 +589,8 @@ def test_to_timestamp(self): from_lst = ["A", "Q", "M", "W", "B", "D", "H", "Min", "S"] def _ex(p): + if p.freq == "B": + return p.start_time + Timedelta(days=1, nanoseconds=-1) return Timestamp((p + p.freq).start_time.value - 1) for i, fcode in enumerate(from_lst): @@ -632,6 +634,13 @@ def _ex(p): result = p.to_timestamp("5S", how="start") assert result == expected + def test_to_timestamp_business_end(self): + per = pd.Period("1990-01-05", "B") # Friday + result = per.to_timestamp("B", how="E") + + expected = pd.Timestamp("1990-01-06") - pd.Timedelta(nanoseconds=1) + assert result == expected + # -------------------------------------------------------------- # Rendering: __repr__, strftime, etc @@ -786,6 +795,14 @@ def _ex(*args): xp = _ex(2012, 1, 2, 1) assert xp == p.end_time + def test_end_time_business_friday(self): + # GH#34449 + per = Period("1990-01-05", "B") + result = per.end_time + + expected = pd.Timestamp("1990-01-06") - pd.Timedelta(nanoseconds=1) + assert result == expected + def test_anchor_week_end_time(self): def _ex(*args): return Timestamp(Timestamp(datetime(*args)).value - 1)
- [ ] closes #xxxx - [x] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry With this change, I _think_ we can move to share some methods between Period and PeriodArray.
https://api.github.com/repos/pandas-dev/pandas/pulls/34449
2020-05-29T01:39:17Z
2020-06-01T15:40:17Z
2020-06-01T15:40:17Z
2020-06-01T16:34:25Z
BUG: ensure_timedelta64ns overflows
diff --git a/doc/source/reference/general_utility_functions.rst b/doc/source/reference/general_utility_functions.rst index 72a84217323ab..c1759110b94ad 100644 --- a/doc/source/reference/general_utility_functions.rst +++ b/doc/source/reference/general_utility_functions.rst @@ -43,6 +43,7 @@ Exceptions and warnings errors.NullFrequencyError errors.NumbaUtilError errors.OutOfBoundsDatetime + errors.OutOfBoundsTimedelta errors.ParserError errors.ParserWarning errors.PerformanceWarning diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index 0ae4cc97d07e3..7723140e3eab1 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -7,6 +7,7 @@ "nat_strings", "is_null_datetimelike", "OutOfBoundsDatetime", + "OutOfBoundsTimedelta", "IncompatibleFrequency", "Period", "Resolution", @@ -26,7 +27,7 @@ ] from . import dtypes -from .conversion import localize_pydatetime +from .conversion import OutOfBoundsTimedelta, localize_pydatetime from .dtypes import Resolution from .nattype import NaT, NaTType, iNaT, is_null_datetimelike, nat_strings from .np_datetime import OutOfBoundsDatetime diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 31d2d0e9572f5..85da7a60a029a 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -51,6 +51,15 @@ DT64NS_DTYPE = np.dtype('M8[ns]') TD64NS_DTYPE = np.dtype('m8[ns]') +class OutOfBoundsTimedelta(ValueError): + """ + Raised when encountering a timedelta value that cannot be represented + as a timedelta64[ns]. + """ + # Timedelta analogue to OutOfBoundsDatetime + pass + + # ---------------------------------------------------------------------- # Unit Conversion Helpers @@ -228,11 +237,34 @@ def ensure_timedelta64ns(arr: ndarray, copy: bool=True): Returns ------- - result : ndarray with dtype timedelta64[ns] - + ndarray[timedelta64[ns]] """ - return arr.astype(TD64NS_DTYPE, copy=copy) - # TODO: check for overflows when going from a lower-resolution to nanos + assert arr.dtype.kind == "m", arr.dtype + + if arr.dtype == TD64NS_DTYPE: + return arr.copy() if copy else arr + + # Re-use the datetime64 machinery to do an overflow-safe `astype` + dtype = arr.dtype.str.replace("m8", "M8") + dummy = arr.view(dtype) + try: + dt64_result = ensure_datetime64ns(dummy, copy) + except OutOfBoundsDatetime as err: + # Re-write the exception in terms of timedelta64 instead of dt64 + + # Find the value that we are going to report as causing an overflow + tdmin = arr.min() + tdmax = arr.max() + if np.abs(tdmin) >= np.abs(tdmax): + bad_val = tdmin + else: + bad_val = tdmax + + raise OutOfBoundsTimedelta( + f"Out of bounds for nanosecond {arr.dtype.name} {bad_val}" + ) + + return dt64_result.view(TD64NS_DTYPE) # ---------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d8779dae7c384..6a4b3318d3aa7 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2302,7 +2302,8 @@ class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): def __init__(self, values, placement, ndim=None): if values.dtype != TD64NS_DTYPE: - values = conversion.ensure_timedelta64ns(values) + # e.g. non-nano or int64 + values = TimedeltaArray._from_sequence(values)._data if isinstance(values, TimedeltaArray): values = values._data assert isinstance(values, np.ndarray), type(values) diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index e3427d93f3d84..6ac3004d29996 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -6,7 +6,7 @@ from pandas._config.config import OptionError -from pandas._libs.tslibs import OutOfBoundsDatetime +from pandas._libs.tslibs import OutOfBoundsDatetime, OutOfBoundsTimedelta class NullFrequencyError(ValueError): diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index 036037032031a..eca444c9ceb34 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -32,6 +32,7 @@ def test_namespace(): "is_null_datetimelike", "nat_strings", "OutOfBoundsDatetime", + "OutOfBoundsTimedelta", "Period", "IncompatibleFrequency", "Resolution", diff --git a/pandas/tests/tslibs/test_conversion.py b/pandas/tests/tslibs/test_conversion.py index b35940c6bb95b..4f184b78f34a1 100644 --- a/pandas/tests/tslibs/test_conversion.py +++ b/pandas/tests/tslibs/test_conversion.py @@ -4,7 +4,13 @@ import pytest from pytz import UTC -from pandas._libs.tslibs import conversion, iNaT, timezones, tzconversion +from pandas._libs.tslibs import ( + OutOfBoundsTimedelta, + conversion, + iNaT, + timezones, + tzconversion, +) from pandas import Timestamp, date_range import pandas._testing as tm @@ -89,6 +95,13 @@ def test_ensure_datetime64ns_bigendian(): tm.assert_numpy_array_equal(result, expected) +def test_ensure_timedelta64ns_overflows(): + arr = np.arange(10).astype("m8[Y]") * 100 + msg = r"Out of bounds for nanosecond timedelta64\[Y\] 900" + with pytest.raises(OutOfBoundsTimedelta, match=msg): + conversion.ensure_timedelta64ns(arr) + + class SubDatetime(datetime): pass
- [ ] closes #xxxx - [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/34448
2020-05-29T00:50:28Z
2020-07-10T22:19:55Z
2020-07-10T22:19:55Z
2020-07-10T23:36:58Z
REF: move offset_to_period_map from liboffsets
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 30a1490fdf862..d3baeba72e81e 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -30,7 +30,7 @@ from pandas._libs.tslibs.util cimport is_integer_object, is_datetime64_object from pandas._libs.tslibs.base cimport ABCTimestamp from pandas._libs.tslibs.ccalendar import ( - MONTHS, DAYS, MONTH_ALIASES, MONTH_TO_CAL_NUM, weekday_to_int, int_to_weekday, + MONTH_ALIASES, MONTH_TO_CAL_NUM, weekday_to_int, int_to_weekday, ) from pandas._libs.tslibs.ccalendar cimport get_days_in_month, dayofweek from pandas._libs.tslibs.conversion cimport ( @@ -45,53 +45,6 @@ from pandas._libs.tslibs.tzconversion cimport tz_convert_single from .timedeltas cimport delta_to_nanoseconds -# --------------------------------------------------------------------- -# Constants - -_offset_to_period_map = { - 'WEEKDAY': 'D', - 'EOM': 'M', - 'BM': 'M', - 'BQS': 'Q', - 'QS': 'Q', - 'BQ': 'Q', - 'BA': 'A', - 'AS': 'A', - 'BAS': 'A', - 'MS': 'M', - 'D': 'D', - 'C': 'C', - 'B': 'B', - 'T': 'T', - 'S': 'S', - 'L': 'L', - 'U': 'U', - 'N': 'N', - 'H': 'H', - 'Q': 'Q', - 'A': 'A', - 'W': 'W', - 'M': 'M', - 'Y': 'A', - 'BY': 'A', - 'YS': 'A', - 'BYS': 'A'} - -need_suffix = ['QS', 'BQ', 'BQS', 'YS', 'AS', 'BY', 'BA', 'BYS', 'BAS'] - -for __prefix in need_suffix: - for _m in MONTHS: - key = f'{__prefix}-{_m}' - _offset_to_period_map[key] = _offset_to_period_map[__prefix] - -for __prefix in ['A', 'Q']: - for _m in MONTHS: - _alias = f'{__prefix}-{_m}' - _offset_to_period_map[_alias] = _alias - -for _d in DAYS: - _offset_to_period_map[f'W-{_d}'] = f'W-{_d}' - # --------------------------------------------------------------------- # Misc Helpers diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 47ae66ac4f91b..7516d9748c18f 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -5,13 +5,18 @@ from pandas._libs.algos import unique_deltas from pandas._libs.tslibs import Timestamp -from pandas._libs.tslibs.ccalendar import MONTH_ALIASES, MONTH_NUMBERS, int_to_weekday +from pandas._libs.tslibs.ccalendar import ( + DAYS, + MONTH_ALIASES, + MONTH_NUMBERS, + MONTHS, + int_to_weekday, +) from pandas._libs.tslibs.fields import build_field_sarray from pandas._libs.tslibs.offsets import ( # noqa:F401 DateOffset, Day, _get_offset, - _offset_to_period_map, to_offset, ) from pandas._libs.tslibs.parsing import get_rule_month @@ -39,6 +44,51 @@ # --------------------------------------------------------------------- # Offset names ("time rules") and related functions +_offset_to_period_map = { + "WEEKDAY": "D", + "EOM": "M", + "BM": "M", + "BQS": "Q", + "QS": "Q", + "BQ": "Q", + "BA": "A", + "AS": "A", + "BAS": "A", + "MS": "M", + "D": "D", + "C": "C", + "B": "B", + "T": "T", + "S": "S", + "L": "L", + "U": "U", + "N": "N", + "H": "H", + "Q": "Q", + "A": "A", + "W": "W", + "M": "M", + "Y": "A", + "BY": "A", + "YS": "A", + "BYS": "A", +} + +_need_suffix = ["QS", "BQ", "BQS", "YS", "AS", "BY", "BA", "BYS", "BAS"] + +for _prefix in _need_suffix: + for _m in MONTHS: + key = f"{_prefix}-{_m}" + _offset_to_period_map[key] = _offset_to_period_map[_prefix] + +for _prefix in ["A", "Q"]: + for _m in MONTHS: + _alias = f"{_prefix}-{_m}" + _offset_to_period_map[_alias] = _alias + +for _d in DAYS: + _offset_to_period_map[f"W-{_d}"] = f"W-{_d}" + def get_period_alias(offset_str: str) -> Optional[str]: """
its only used in tseries.frequencies, so this puts it back there
https://api.github.com/repos/pandas-dev/pandas/pulls/34447
2020-05-28T23:43:06Z
2020-05-29T01:00:40Z
2020-05-29T01:00:40Z
2020-05-29T01:10:38Z
CLN: liboffsets de-duplicate pickle code
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index a27b0903e9d75..b804ed883e693 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -63,7 +63,7 @@ cdef datetime _as_datetime(datetime obj): return obj -cpdef bint is_normalized(datetime dt): +cdef bint _is_normalized(datetime dt): if dt.hour != 0 or dt.minute != 0 or dt.second != 0 or dt.microsecond != 0: # Regardless of whether dt is datetime vs Timestamp return False @@ -233,7 +233,7 @@ cpdef int get_firstbday(int year, int month) nogil: return first -def _get_calendar(weekmask, holidays, calendar): +cdef _get_calendar(weekmask, holidays, calendar): """Generate busdaycalendar""" if isinstance(calendar, np.busdaycalendar): if not holidays: @@ -252,7 +252,7 @@ def _get_calendar(weekmask, holidays, calendar): holidays = holidays + calendar.holidays().tolist() except AttributeError: pass - holidays = [to_dt64D(dt) for dt in holidays] + holidays = [_to_dt64D(dt) for dt in holidays] holidays = tuple(sorted(holidays)) kwargs = {'weekmask': weekmask} @@ -263,7 +263,7 @@ def _get_calendar(weekmask, holidays, calendar): return busdaycalendar, holidays -def to_dt64D(dt): +cdef _to_dt64D(dt): # Currently # > np.datetime64(dt.datetime(2013,5,1),dtype='datetime64[D]') # numpy.datetime64('2013-05-01T02:00:00.000000+0200') @@ -286,7 +286,7 @@ def to_dt64D(dt): # Validation -def _validate_business_time(t_input): +cdef _validate_business_time(t_input): if isinstance(t_input, str): try: t = time.strptime(t_input, '%H:%M') @@ -311,7 +311,7 @@ _relativedelta_kwds = {"years", "months", "weeks", "days", "year", "month", "minutes", "seconds", "microseconds"} -def _determine_offset(kwds): +cdef _determine_offset(kwds): # timedelta is used for sub-daily plural offsets and all singular # offsets relativedelta is used for plural offsets of daily length or # more nanosecond(s) are handled by apply_wraps @@ -357,7 +357,7 @@ cdef class BaseOffset: """ _typ = "dateoffset" _day_opt = None - _attributes = frozenset(['n', 'normalize']) + _attributes = tuple(["n", "normalize"]) _use_relativedelta = False _adjust_dst = True _deprecations = frozenset(["isAnchored", "onOffset"]) @@ -400,7 +400,6 @@ cdef class BaseOffset: Returns a tuple containing all of the attributes needed to evaluate equality between two DateOffset objects. """ - # NB: non-cython subclasses override property with cache_readonly d = getattr(self, "__dict__", {}) all_paras = d.copy() all_paras["n"] = self.n @@ -614,7 +613,7 @@ cdef class BaseOffset: return get_day_of_month(other, self._day_opt) def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False # Default (slow) method for determining if some date is a member of the @@ -658,63 +657,22 @@ cdef class BaseOffset: def __setstate__(self, state): """Reconstruct an instance from a pickled state""" - if isinstance(self, MonthOffset): - # We can't just override MonthOffset.__setstate__ because of the - # combination of MRO resolution and cython not handling - # multiple inheritance nicely for cdef classes. - state.pop("_use_relativedelta", False) - state.pop("offset", None) - state.pop("_offset", None) - state.pop("kwds", {}) - - if 'offset' in state: - # Older (<0.22.0) versions have offset attribute instead of _offset - if '_offset' in state: # pragma: no cover - raise AssertionError('Unexpected key `_offset`') - state['_offset'] = state.pop('offset') - state['kwds']['offset'] = state['_offset'] - - if '_offset' in state and not isinstance(state['_offset'], timedelta): - # relativedelta, we need to populate using its kwds - offset = state['_offset'] - odict = offset.__dict__ - kwds = {key: odict[key] for key in odict if odict[key]} - state.update(kwds) - self.n = state.pop("n") self.normalize = state.pop("normalize") self._cache = state.pop("_cache", {}) - - if not len(state): - # FIXME: kludge because some classes no longer have a __dict__, - # so we need to short-circuit before raising on the next line - return - - self.__dict__.update(state) - - if 'weekmask' in state and 'holidays' in state: - weekmask = state.pop("weekmask") - holidays = state.pop("holidays") - calendar, holidays = _get_calendar(weekmask=weekmask, - holidays=holidays, - calendar=None) - self.calendar = calendar - self.holidays = holidays + # At this point we expect state to be empty def __getstate__(self): """Return a pickleable state""" - state = getattr(self, "__dict__", {}).copy() + state = {} state["n"] = self.n state["normalize"] = self.normalize # we don't want to actually pickle the calendar object # as its a np.busyday; we recreate on deserialization - if 'calendar' in state: - del state['calendar'] - try: - state['kwds'].pop('calendar') - except KeyError: - pass + state.pop("calendar", None) + if "kwds" in state: + state["kwds"].pop("calendar", None) return state @@ -752,6 +710,17 @@ cdef class SingleConstructorOffset(BaseOffset): raise ValueError(f"Bad freq suffix {suffix}") return cls() + def __reduce__(self): + # This __reduce__ implementation is for all BaseOffset subclasses + # except for RelativeDeltaOffset + # np.busdaycalendar objects do not pickle nicely, but we can reconstruct + # from attributes that do get pickled. + tup = tuple( + getattr(self, attr) if attr != "calendar" else None + for attr in self._attributes + ) + return type(self), tup + # --------------------------------------------------------------------- # Tick Offsets @@ -761,7 +730,7 @@ cdef class Tick(SingleConstructorOffset): __array_priority__ = 1000 _adjust_dst = False _prefix = "undefined" - _attributes = frozenset(["n", "normalize"]) + _attributes = tuple(["n", "normalize"]) def __init__(self, n=1, normalize=False): n = self._validate_n(n) @@ -883,9 +852,6 @@ cdef class Tick(SingleConstructorOffset): # -------------------------------------------------------------------- # Pickle Methods - def __reduce__(self): - return (type(self), (self.n,)) - def __setstate__(self, state): self.n = state["n"] self.normalize = False @@ -955,7 +921,7 @@ cdef class RelativeDeltaOffset(BaseOffset): """ DateOffset subclass backed by a dateutil relativedelta object. """ - _attributes = frozenset(["n", "normalize"] + list(_relativedelta_kwds)) + _attributes = tuple(["n", "normalize"] + list(_relativedelta_kwds)) _adjust_dst = False def __init__(self, n=1, normalize=False, **kwds): @@ -968,6 +934,38 @@ cdef class RelativeDeltaOffset(BaseOffset): val = kwds[key] object.__setattr__(self, key, val) + def __getstate__(self): + """Return a pickleable state""" + # RelativeDeltaOffset (technically DateOffset) is the only non-cdef + # class, so the only one with __dict__ + state = self.__dict__.copy() + state["n"] = self.n + state["normalize"] = self.normalize + return state + + def __setstate__(self, state): + """Reconstruct an instance from a pickled state""" + + if "offset" in state: + # Older (<0.22.0) versions have offset attribute instead of _offset + if "_offset" in state: # pragma: no cover + raise AssertionError("Unexpected key `_offset`") + state["_offset"] = state.pop("offset") + state["kwds"]["offset"] = state["_offset"] + + if "_offset" in state and not isinstance(state["_offset"], timedelta): + # relativedelta, we need to populate using its kwds + offset = state["_offset"] + odict = offset.__dict__ + kwds = {key: odict[key] for key in odict if odict[key]} + state.update(kwds) + + self.n = state.pop("n") + self.normalize = state.pop("normalize") + self._cache = state.pop("_cache", {}) + + self.__dict__.update(state) + @apply_wraps def apply(self, other): if self._use_relativedelta: @@ -1060,7 +1058,7 @@ cdef class RelativeDeltaOffset(BaseOffset): ) def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False # TODO: see GH#1395 return True @@ -1234,6 +1232,7 @@ cdef class BusinessMixin(SingleConstructorOffset): if "_offset" in state: self._offset = state.pop("_offset") elif "offset" in state: + # Older (<0.22.0) versions have offset attribute instead of _offset self._offset = state.pop("offset") if self._prefix.startswith("C"): @@ -1256,7 +1255,7 @@ cdef class BusinessDay(BusinessMixin): """ _prefix = "B" - _attributes = frozenset(["n", "normalize", "offset"]) + _attributes = tuple(["n", "normalize", "offset"]) cpdef __setstate__(self, state): self.n = state.pop("n") @@ -1266,10 +1265,6 @@ cdef class BusinessDay(BusinessMixin): elif "offset" in state: self._offset = state.pop("offset") - def __reduce__(self): - tup = (self.n, self.normalize, self.offset) - return type(self), tup - @property def _params(self): # FIXME: using cache_readonly breaks a pytables test @@ -1371,7 +1366,7 @@ cdef class BusinessDay(BusinessMixin): return result def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False return dt.weekday() < 5 @@ -1383,7 +1378,7 @@ cdef class BusinessHour(BusinessMixin): _prefix = "BH" _anchor = 0 - _attributes = frozenset(["n", "normalize", "start", "end", "offset"]) + _attributes = tuple(["n", "normalize", "start", "end", "offset"]) _adjust_dst = False cdef readonly: @@ -1450,9 +1445,6 @@ cdef class BusinessHour(BusinessMixin): state.pop("next_bday", None) BusinessMixin.__setstate__(self, state) - def __reduce__(self): - return type(self), (self.n, self.normalize, self.start, self.end, self.offset) - def _repr_attrs(self) -> str: out = super()._repr_attrs() hours = ",".join( @@ -1505,7 +1497,6 @@ cdef class BusinessHour(BusinessMixin): nb_offset = -1 if self._prefix.startswith("C"): # CustomBusinessHour - from pandas.tseries.offsets import CustomBusinessDay return CustomBusinessDay( n=nb_offset, weekmask=self.weekmask, @@ -1662,7 +1653,6 @@ cdef class BusinessHour(BusinessMixin): if bd != 0: if self._prefix.startswith("C"): # GH#30593 this is a Custom offset - from pandas.tseries.offsets import CustomBusinessDay skip_bd = CustomBusinessDay( n=bd, weekmask=self.weekmask, @@ -1722,7 +1712,7 @@ cdef class BusinessHour(BusinessMixin): raise ApplyTypeError("Only know how to combine business hour with datetime") def is_on_offset(self, dt): - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False if dt.tzinfo is not None: @@ -1737,7 +1727,7 @@ cdef class BusinessHour(BusinessMixin): """ Slight speedups using calculated values. """ - # if self.normalize and not is_normalized(dt): + # if self.normalize and not _is_normalized(dt): # return False # Valid BH can be on the different BusinessDay during midnight # Distinguish by the time spent from previous opening time @@ -1786,7 +1776,7 @@ cdef class WeekOfMonthMixin(SingleConstructorOffset): return shift_day(shifted, to_day - shifted.day) def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False return dt.day == self._get_offset_day(dt) @@ -1806,7 +1796,7 @@ cdef class YearOffset(SingleConstructorOffset): """ DateOffset that just needs a month. """ - _attributes = frozenset(["n", "normalize", "month"]) + _attributes = tuple(["n", "normalize", "month"]) # _default_month: int # FIXME: python annotation here breaks things @@ -1828,9 +1818,6 @@ cdef class YearOffset(SingleConstructorOffset): self.normalize = state.pop("normalize") self._cache = {} - def __reduce__(self): - return type(self), (self.n, self.normalize, self.month) - @classmethod def _from_name(cls, suffix=None): kwargs = {} @@ -1844,7 +1831,7 @@ cdef class YearOffset(SingleConstructorOffset): return f"{self._prefix}-{month}" def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False return dt.month == self.month and dt.day == self._get_offset_day(dt) @@ -1943,7 +1930,7 @@ cdef class YearBegin(YearOffset): # Quarter-Based Offset Classes cdef class QuarterOffset(SingleConstructorOffset): - _attributes = frozenset(["n", "normalize", "startingMonth"]) + _attributes = tuple(["n", "normalize", "startingMonth"]) # TODO: Consider combining QuarterOffset and YearOffset __init__ at some # point. Also apply_index, is_on_offset, rule_code if # startingMonth vs month attr names are resolved @@ -1967,9 +1954,6 @@ cdef class QuarterOffset(SingleConstructorOffset): self.n = state.pop("n") self.normalize = state.pop("normalize") - def __reduce__(self): - return type(self), (self.n, self.normalize, self.startingMonth) - @classmethod def _from_name(cls, suffix=None): kwargs = {} @@ -1989,7 +1973,7 @@ cdef class QuarterOffset(SingleConstructorOffset): return self.n == 1 and self.startingMonth is not None def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False mod_month = (dt.month - self.startingMonth) % 3 return mod_month == 0 and dt.day == self._get_offset_day(dt) @@ -2106,7 +2090,7 @@ cdef class QuarterBegin(QuarterOffset): cdef class MonthOffset(SingleConstructorOffset): def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False return dt.day == self._get_offset_day(dt) @@ -2121,6 +2105,14 @@ cdef class MonthOffset(SingleConstructorOffset): shifted = shift_months(dtindex.asi8, self.n, self._day_opt) return type(dtindex)._simple_new(shifted, dtype=dtindex.dtype) + cpdef __setstate__(self, state): + state.pop("_use_relativedelta", False) + state.pop("offset", None) + state.pop("_offset", None) + state.pop("kwds", {}) + + BaseOffset.__setstate__(self, state) + cdef class MonthEnd(MonthOffset): """ @@ -2182,7 +2174,7 @@ cdef class BusinessMonthBegin(MonthOffset): cdef class SemiMonthOffset(SingleConstructorOffset): _default_day_of_month = 15 _min_day_of_month = 2 - _attributes = frozenset(["n", "normalize", "day_of_month"]) + _attributes = tuple(["n", "normalize", "day_of_month"]) cdef readonly: int day_of_month @@ -2201,9 +2193,6 @@ cdef class SemiMonthOffset(SingleConstructorOffset): f"got {self.day_of_month}" ) - def __reduce__(self): - return type(self), (self.n, self.normalize, self.day_of_month) - cpdef __setstate__(self, state): self.n = state.pop("n") self.normalize = state.pop("normalize") @@ -2310,7 +2299,7 @@ cdef class SemiMonthEnd(SemiMonthOffset): _min_day_of_month = 1 def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False days_in_month = get_days_in_month(dt.year, dt.month) return dt.day in (self.day_of_month, days_in_month) @@ -2370,7 +2359,7 @@ cdef class SemiMonthBegin(SemiMonthOffset): _prefix = "SMS" def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False return dt.day in (1, self.day_of_month) @@ -2428,7 +2417,7 @@ cdef class Week(SingleConstructorOffset): _inc = timedelta(weeks=1) _prefix = "W" - _attributes = frozenset(["n", "normalize", "weekday"]) + _attributes = tuple(["n", "normalize", "weekday"]) cdef readonly: object weekday # int or None @@ -2441,9 +2430,6 @@ cdef class Week(SingleConstructorOffset): if self.weekday < 0 or self.weekday > 6: raise ValueError(f"Day must be 0<=day<=6, got {self.weekday}") - def __reduce__(self): - return type(self), (self.n, self.normalize, self.weekday) - cpdef __setstate__(self, state): self.n = state.pop("n") self.normalize = state.pop("normalize") @@ -2529,7 +2515,7 @@ cdef class Week(SingleConstructorOffset): return base + off + Timedelta(1, "ns") - Timedelta(1, "D") def is_on_offset(self, dt) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False elif self.weekday is None: return True @@ -2575,7 +2561,7 @@ cdef class WeekOfMonth(WeekOfMonthMixin): """ _prefix = "WOM" - _attributes = frozenset(["n", "normalize", "week", "weekday"]) + _attributes = tuple(["n", "normalize", "week", "weekday"]) def __init__(self, n=1, normalize=False, week=0, weekday=0): WeekOfMonthMixin.__init__(self, n, normalize, weekday) @@ -2590,9 +2576,6 @@ cdef class WeekOfMonth(WeekOfMonthMixin): self.weekday = state.pop("weekday") self.week = state.pop("week") - def __reduce__(self): - return type(self), (self.n, self.normalize, self.week, self.weekday) - def _get_offset_day(self, other: datetime) -> int: """ Find the day in the same month as other that has the same @@ -2643,7 +2626,7 @@ cdef class LastWeekOfMonth(WeekOfMonthMixin): """ _prefix = "LWOM" - _attributes = frozenset(["n", "normalize", "weekday"]) + _attributes = tuple(["n", "normalize", "weekday"]) def __init__(self, n=1, normalize=False, weekday=0): WeekOfMonthMixin.__init__(self, n, normalize, weekday) @@ -2652,9 +2635,6 @@ cdef class LastWeekOfMonth(WeekOfMonthMixin): if self.n == 0: raise ValueError("N cannot be 0") - def __reduce__(self): - return type(self), (self.n, self.normalize, self.weekday) - cpdef __setstate__(self, state): self.n = state.pop("n") self.normalize = state.pop("normalize") @@ -2793,14 +2773,10 @@ cdef class FY5253(FY5253Mixin): """ _prefix = "RE" - _attributes = frozenset(["weekday", "startingMonth", "variation"]) - - def __reduce__(self): - tup = (self.n, self.normalize, self.weekday, self.startingMonth, self.variation) - return type(self), tup + _attributes = tuple(["n", "normalize", "weekday", "startingMonth", "variation"]) def is_on_offset(self, dt: datetime) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False dt = datetime(dt.year, dt.month, dt.day) year_end = self.get_year_end(dt) @@ -2975,8 +2951,15 @@ cdef class FY5253Quarter(FY5253Mixin): """ _prefix = "REQ" - _attributes = frozenset( - ["weekday", "startingMonth", "qtr_with_extra_week", "variation"] + _attributes = tuple( + [ + "n", + "normalize", + "weekday", + "startingMonth", + "qtr_with_extra_week", + "variation", + ] ) cdef readonly: @@ -3000,17 +2983,6 @@ cdef class FY5253Quarter(FY5253Mixin): FY5253Mixin.__setstate__(self, state) self.qtr_with_extra_week = state.pop("qtr_with_extra_week") - def __reduce__(self): - tup = ( - self.n, - self.normalize, - self.weekday, - self.startingMonth, - self.qtr_with_extra_week, - self.variation, - ) - return type(self), tup - @cache_readonly def _offset(self): return FY5253( @@ -3122,7 +3094,7 @@ cdef class FY5253Quarter(FY5253Mixin): return weeks_in_year == 53 def is_on_offset(self, dt: datetime) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False if self._offset.is_on_offset(dt): return True @@ -3158,9 +3130,6 @@ cdef class Easter(SingleConstructorOffset): Right now uses the revised method which is valid in years 1583-4099. """ - def __reduce__(self): - return type(self), (self.n, self.normalize) - cpdef __setstate__(self, state): self.n = state.pop("n") self.normalize = state.pop("normalize") @@ -3195,7 +3164,7 @@ cdef class Easter(SingleConstructorOffset): return new def is_on_offset(self, dt: datetime) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False return date(dt.year, dt.month, dt.day) == easter(dt.year) @@ -3223,16 +3192,10 @@ cdef class CustomBusinessDay(BusinessDay): """ _prefix = "C" - _attributes = frozenset( + _attributes = tuple( ["n", "normalize", "weekmask", "holidays", "calendar", "offset"] ) - def __reduce__(self): - # np.holidaycalendar cant be pickled, so pass None there and - # it will be re-constructed within __init__ - tup = (self.n, self.normalize, self.weekmask, self.holidays, None, self.offset) - return type(self), tup - def __init__( self, n=1, @@ -3280,13 +3243,13 @@ cdef class CustomBusinessDay(BusinessDay): "datetime, datetime64 or timedelta." ) - def apply_index(self, i): + def apply_index(self, dtindex): raise NotImplementedError def is_on_offset(self, dt: datetime) -> bool: - if self.normalize and not is_normalized(dt): + if self.normalize and not _is_normalized(dt): return False - day64 = to_dt64D(dt) + day64 = _to_dt64D(dt) return np.is_busday(day64, busdaycal=self.calendar) @@ -3297,7 +3260,7 @@ cdef class CustomBusinessHour(BusinessHour): _prefix = "CBH" _anchor = 0 - _attributes = frozenset( + _attributes = tuple( ["n", "normalize", "weekmask", "holidays", "calendar", "start", "end", "offset"] ) @@ -3315,22 +3278,6 @@ cdef class CustomBusinessHour(BusinessHour): BusinessHour.__init__(self, n, normalize, start=start, end=end, offset=offset) self._init_custom(weekmask, holidays, calendar) - def __reduce__(self): - # None for self.calendar bc np.busdaycalendar doesnt pickle nicely - return ( - type(self), - ( - self.n, - self.normalize, - self.weekmask, - self.holidays, - None, - self.start, - self.end, - self.offset, - ), - ) - cdef class _CustomBusinessMonth(BusinessMixin): """ @@ -3355,7 +3302,7 @@ cdef class _CustomBusinessMonth(BusinessMixin): Time offset to apply. """ - _attributes = frozenset( + _attributes = tuple( ["n", "normalize", "weekmask", "holidays", "calendar", "offset"] ) @@ -3371,13 +3318,6 @@ cdef class _CustomBusinessMonth(BusinessMixin): BusinessMixin.__init__(self, n, normalize, offset) self._init_custom(weekmask, holidays, calendar) - def __reduce__(self): - # None for self.calendar bc np.busdaycalendar doesnt pickle nicely - return ( - type(self), - (self.n, self.normalize, self.weekmask, self.holidays, None, self.offset), - ) - @cache_readonly def cbday_roll(self): """ diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 9d191ba8e6681..fb888bcba1608 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1509,8 +1509,6 @@ cdef class _Period: int64_t ordinal object freq - _typ = 'period' - def __cinit__(self, ordinal, freq): self.ordinal = ordinal self.freq = freq
privatize/cdef functions that are now only used in liboffsets
https://api.github.com/repos/pandas-dev/pandas/pulls/34446
2020-05-28T23:40:59Z
2020-05-29T12:24:23Z
2020-05-29T12:24:23Z
2020-05-29T14:45:18Z
CLN: simplify to_offset
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 30a1490fdf862..855fc014bfe7e 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -3532,16 +3532,6 @@ prefix_mapping = { ] } -_name_to_offset_map = { - "days": Day(1), - "hours": Hour(1), - "minutes": Minute(1), - "seconds": Second(1), - "milliseconds": Milli(1), - "microseconds": Micro(1), - "nanoseconds": Nano(1), -} - # hack to handle WOM-1MON opattern = re.compile( r"([+\-]?\d*|[+\-]?\d*\.\d*)\s*([A-Za-z]+([\-][\dA-Za-z\-]+)?)" @@ -3695,26 +3685,12 @@ cpdef to_offset(freq): delta = _get_offset(name) * stride elif isinstance(freq, timedelta): - from .timedeltas import Timedelta - - delta = None - freq = Timedelta(freq) - try: - for name in freq.components._fields: - offset = _name_to_offset_map[name] - stride = getattr(freq.components, name) - if stride != 0: - offset = stride * offset - if delta is None: - delta = offset - else: - delta = delta + offset - except ValueError as err: - raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err + return delta_to_tick(freq) - else: + elif isinstance(freq, str): delta = None stride_sign = None + try: split = re.split(opattern, freq) if split[-1] != "" and not split[-1].isspace(): @@ -3744,6 +3720,8 @@ cpdef to_offset(freq): delta = delta + offset except (ValueError, TypeError) as err: raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err + else: + delta = None if delta is None: raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) diff --git a/pandas/tests/tseries/frequencies/test_to_offset.py b/pandas/tests/tseries/frequencies/test_to_offset.py index beaefe9109e91..d3510eaa5c749 100644 --- a/pandas/tests/tseries/frequencies/test_to_offset.py +++ b/pandas/tests/tseries/frequencies/test_to_offset.py @@ -137,6 +137,7 @@ def test_to_offset_leading_plus(freqstr, expected): (dict(hours=1), offsets.Hour(1)), (dict(hours=1), frequencies.to_offset("60min")), (dict(microseconds=1), offsets.Micro(1)), + (dict(microseconds=0), offsets.Nano(0)), ], ) def test_to_offset_pd_timedelta(kwargs, expected): @@ -146,15 +147,6 @@ def test_to_offset_pd_timedelta(kwargs, expected): assert result == expected -def test_to_offset_pd_timedelta_invalid(): - # see gh-9064 - msg = "Invalid frequency: 0 days 00:00:00" - td = Timedelta(microseconds=0) - - with pytest.raises(ValueError, match=msg): - frequencies.to_offset(td) - - @pytest.mark.parametrize( "shortcut,expected", [
https://api.github.com/repos/pandas-dev/pandas/pulls/34444
2020-05-28T22:33:51Z
2020-05-29T00:58:45Z
2020-05-29T00:58:45Z
2020-05-29T01:09:34Z
TST #28981 comparison operation for interval dtypes
diff --git a/pandas/tests/arithmetic/test_interval.py b/pandas/tests/arithmetic/test_interval.py index 66526204a6208..50b5fe8e6f6b9 100644 --- a/pandas/tests/arithmetic/test_interval.py +++ b/pandas/tests/arithmetic/test_interval.py @@ -284,3 +284,11 @@ def test_index_series_compat(self, op, constructor, expected_type, assert_func): result = op(index, other) expected = expected_type(self.elementwise_comparison(op, index, other)) assert_func(result, expected) + + @pytest.mark.parametrize("scalars", ["a", False, 1, 1.0, None]) + def test_comparison_operations(self, scalars): + # GH #28981 + expected = Series([False, False]) + s = pd.Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype="interval") + result = s == scalars + tm.assert_series_equal(result, expected)
As a complement of #28980, one test was modified to take into account this issue: - [ x ] closes #28981 - [ 1 ] test modified - [ x ] passes `black pandas` - [ x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/34443
2020-05-28T21:41:00Z
2020-06-03T18:04:41Z
2020-06-03T18:04:40Z
2020-06-07T09:03:01Z
CLN: clearer lookups for period accessors
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index ec6f8de159dae..e722ca6f5a56c 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1331,15 +1331,15 @@ cdef int pdays_in_month(int64_t ordinal, int freq): @cython.wraparound(False) @cython.boundscheck(False) -def get_period_field_arr(int code, const int64_t[:] arr, int freq): +def get_period_field_arr(str field, const int64_t[:] arr, int freq): cdef: Py_ssize_t i, sz int64_t[:] out accessor f - func = _get_accessor_func(code) + func = _get_accessor_func(field) if func is NULL: - raise ValueError(f"Unrecognized period code: {code}") + raise ValueError(f"Unrecognized field name: {field}") sz = len(arr) out = np.empty(sz, dtype=np.int64) @@ -1353,30 +1353,30 @@ def get_period_field_arr(int code, const int64_t[:] arr, int freq): return out.base # .base to access underlying np.ndarray -cdef accessor _get_accessor_func(int code): - if code == 0: +cdef accessor _get_accessor_func(str field): + if field == "year": return <accessor>pyear - elif code == 1: + elif field == "qyear": return <accessor>pqyear - elif code == 2: + elif field == "quarter": return <accessor>pquarter - elif code == 3: + elif field == "month": return <accessor>pmonth - elif code == 4: + elif field == "day": return <accessor>pday - elif code == 5: + elif field == "hour": return <accessor>phour - elif code == 6: + elif field == "minute": return <accessor>pminute - elif code == 7: + elif field == "second": return <accessor>psecond - elif code == 8: + elif field == "week": return <accessor>pweek - elif code == 9: + elif field == "day_of_year": return <accessor>pday_of_year - elif code == 10: + elif field == "weekday": return <accessor>pweekday - elif code == 11: + elif field == "days_in_month": return <accessor>pdays_in_month return NULL @@ -1429,12 +1429,8 @@ def extract_freq(ndarray[object] values): for i in range(n): value = values[i] - try: - # now Timestamp / NaT has freq attr - if is_period_object(value): - return value.freq - except AttributeError: - pass + if is_period_object(value): + return value.freq raise ValueError('freq not specified and cannot be inferred') diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 8b2925b2c0827..4601e7fa5389e 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -49,10 +49,10 @@ from pandas.tseries.offsets import DateOffset -def _field_accessor(name: str, alias: int, docstring=None): +def _field_accessor(name: str, docstring=None): def f(self): - base, mult = libfrequencies.get_freq_code(self.freq) - result = get_period_field_arr(alias, self.asi8, base) + base, _ = libfrequencies.get_freq_code(self.freq) + result = get_period_field_arr(name, self.asi8, base) return result f.__name__ = name @@ -324,80 +324,69 @@ def __arrow_array__(self, type=None): year = _field_accessor( "year", - 0, """ The year of the period. """, ) month = _field_accessor( "month", - 3, """ The month as January=1, December=12. """, ) day = _field_accessor( "day", - 4, """ The days of the period. """, ) hour = _field_accessor( "hour", - 5, """ The hour of the period. """, ) minute = _field_accessor( "minute", - 6, """ The minute of the period. """, ) second = _field_accessor( "second", - 7, """ The second of the period. """, ) weekofyear = _field_accessor( "week", - 8, """ The week ordinal of the year. """, ) week = weekofyear dayofweek = _field_accessor( - "dayofweek", - 10, + "weekday", """ The day of the week with Monday=0, Sunday=6. """, ) weekday = dayofweek dayofyear = day_of_year = _field_accessor( - "dayofyear", - 9, + "day_of_year", """ The ordinal day of the year. """, ) quarter = _field_accessor( "quarter", - 2, """ The quarter of the date. """, ) - qyear = _field_accessor("qyear", 1) + qyear = _field_accessor("qyear") days_in_month = _field_accessor( "days_in_month", - 11, """ The number of days in the month. """,
https://api.github.com/repos/pandas-dev/pandas/pulls/34442
2020-05-28T21:20:28Z
2020-05-28T22:19:37Z
2020-05-28T22:19:36Z
2020-05-28T22:20:24Z