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
sort_index not sorting when multi-index made by different categorical types
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 4049ef46f3006..43e4070b9b163 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -239,6 +239,28 @@ def test_level_get_group(observed): tm.assert_frame_equal(result, expected) +def test_sorting_with_different_categoricals(): + # GH 24271 + df = DataFrame( + { + "group": ["A"] * 6 + ["B"] * 6, + "dose": ["high", "med", "low"] * 4, + "outcomes": np.arange(12.0), + } + ) + + df.dose = Categorical(df.dose, categories=["low", "med", "high"], ordered=True) + + result = df.groupby("group")["dose"].value_counts() + result = result.sort_index(level=0, sort_remaining=True) + index = ["low", "med", "high", "low", "med", "high"] + index = Categorical(index, categories=["low", "med", "high"], ordered=True) + index = [["A", "A", "A", "B", "B", "B"], CategoricalIndex(index)] + index = MultiIndex.from_arrays(index, names=["group", None]) + expected = Series([2] * 6, index=index, name="dose") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("ordered", [True, False]) def test_apply(ordered): # GH 10138
- [ ] closes #24271 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39986
2021-02-23T06:45:55Z
2021-03-15T00:32:13Z
2021-03-15T00:32:13Z
2021-03-15T00:32:17Z
Backport PR #39973 on branch 1.2.x (DOC: fix a mis-formatted external link)
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst index 77791b4b7e491..7236f93c36356 100644 --- a/doc/source/user_guide/cookbook.rst +++ b/doc/source/user_guide/cookbook.rst @@ -1410,7 +1410,7 @@ Often it's useful to obtain the lower (or upper) triangular form of a correlatio corr_mat.where(mask) -The ``method`` argument within ``DataFrame.corr`` can accept a callable in addition to the named correlation types. Here we compute the ``distance correlation <https://en.wikipedia.org/wiki/Distance_correlation>``__ matrix for a ``DataFrame`` object. +The ``method`` argument within ``DataFrame.corr`` can accept a callable in addition to the named correlation types. Here we compute the `distance correlation <https://en.wikipedia.org/wiki/Distance_correlation>`__ matrix for a ``DataFrame`` object. .. ipython:: python
Backport PR #39973: DOC: fix a mis-formatted external link
https://api.github.com/repos/pandas-dev/pandas/pulls/39982
2021-02-22T23:54:41Z
2021-02-23T01:03:17Z
2021-02-23T01:03:17Z
2021-02-23T01:03:17Z
Backport PR #39974 on branch 1.2.x (update pyperclip link)
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index a8020f4bb4e4f..9a90819a5dda4 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -59,7 +59,7 @@ EXCEPT_MSG = """ Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit - https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error + https://pyperclip.readthedocs.io/en/latest/#not-implemented-error """ ENCODING = "utf-8"
Backport PR #39974: update pyperclip link
https://api.github.com/repos/pandas-dev/pandas/pulls/39981
2021-02-22T23:52:01Z
2021-02-23T01:02:57Z
2021-02-23T01:02:57Z
2021-02-23T01:02:57Z
TST: collect indexing tests by method
diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py deleted file mode 100644 index 464b24e45abf4..0000000000000 --- a/pandas/tests/frame/indexing/test_categorical.py +++ /dev/null @@ -1,293 +0,0 @@ -import numpy as np -import pytest - -from pandas.core.dtypes.dtypes import CategoricalDtype - -import pandas as pd -from pandas import ( - Categorical, - DataFrame, - Index, - Series, -) -import pandas._testing as tm - -msg1 = "Cannot setitem on a Categorical with a new category, set the categories first" -msg2 = "Cannot set a Categorical with another, without identical categories" - - -class TestDataFrameIndexingCategorical: - def test_assignment(self): - # assignment - df = DataFrame( - {"value": np.array(np.random.randint(0, 10000, 100), dtype="int32")} - ) - labels = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) - - df = df.sort_values(by=["value"], ascending=True) - s = pd.cut(df.value, range(0, 10500, 500), right=False, labels=labels) - d = s.values - df["D"] = d - str(df) - - result = df.dtypes - expected = Series( - [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], - index=["value", "D"], - ) - tm.assert_series_equal(result, expected) - - df["E"] = s - str(df) - - result = df.dtypes - expected = Series( - [ - np.dtype("int32"), - CategoricalDtype(categories=labels, ordered=False), - CategoricalDtype(categories=labels, ordered=False), - ], - index=["value", "D", "E"], - ) - tm.assert_series_equal(result, expected) - - result1 = df["D"] - result2 = df["E"] - tm.assert_categorical_equal(result1._mgr._block.values, d) - - # sorting - s.name = "E" - tm.assert_series_equal(result2.sort_index(), s.sort_index()) - - cat = Categorical([1, 2, 3, 10], categories=[1, 2, 3, 4, 10]) - df = DataFrame(Series(cat)) - - @pytest.fixture - def orig(self): - cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) - idx = Index(["h", "i", "j", "k", "l", "m", "n"]) - values = [1, 1, 1, 1, 1, 1, 1] - orig = DataFrame({"cats": cats, "values": values}, index=idx) - return orig - - @pytest.fixture - def exp_single_row(self): - # The expected values if we change a single row - cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) - idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values1 = [1, 1, 2, 1, 1, 1, 1] - exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1) - return exp_single_row - - @pytest.fixture - def exp_multi_row(self): - # assign multiple rows (mixed values) (-> array) -> exp_multi_row - # changed multiple rows - cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) - idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values2 = [1, 1, 2, 2, 1, 1, 1] - exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) - return exp_multi_row - - @pytest.fixture - def exp_parts_cats_col(self): - # changed part of the cats column - cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) - idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values3 = [1, 1, 1, 1, 1, 1, 1] - exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3) - return exp_parts_cats_col - - @pytest.fixture - def exp_single_cats_value(self): - # changed single value in cats col - cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) - idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) - values4 = [1, 1, 1, 1, 1, 1, 1] - exp_single_cats_value = DataFrame( - {"cats": cats4, "values": values4}, index=idx4 - ) - return exp_single_cats_value - - @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) - def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer): - # - assign multiple rows (mixed values) -> exp_multi_row - df = orig.copy() - - key = slice(2, 4) - if indexer is tm.loc: - key = slice("j", "k") - - indexer(df)[key, :] = [["b", 2], ["b", 2]] - tm.assert_frame_equal(df, exp_multi_row) - - df = orig.copy() - with pytest.raises(ValueError, match=msg1): - indexer(df)[key, :] = [["c", 2], ["c", 2]] - - @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc, tm.at, tm.iat]) - def test_loc_iloc_at_iat_setitem_single_value_in_categories( - self, orig, exp_single_cats_value, indexer - ): - # - assign a single value -> exp_single_cats_value - df = orig.copy() - - key = (2, 0) - if indexer in [tm.loc, tm.at]: - key = (df.index[2], df.columns[0]) - - # "b" is among the categories for df["cat"}] - indexer(df)[key] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - # "c" is not among the categories for df["cat"] - with pytest.raises(ValueError, match=msg1): - indexer(df)[key] = "c" - - @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) - def test_loc_iloc_setitem_mask_single_value_in_categories( - self, orig, exp_single_cats_value, indexer - ): - # mask with single True - df = orig.copy() - - mask = df.index == "j" - key = 0 - if indexer is tm.loc: - key = df.columns[key] - - indexer(df)[mask, key] = "b" - tm.assert_frame_equal(df, exp_single_cats_value) - - @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) - def test_iloc_setitem_full_row_non_categorical_rhs( - self, orig, exp_single_row, indexer - ): - # - assign a complete row (mixed values) -> exp_single_row - df = orig.copy() - - key = 2 - if indexer is tm.loc: - key = df.index[2] - - # not categorical dtype, but "b" _is_ among the categories for df["cat"] - indexer(df)[key, :] = ["b", 2] - tm.assert_frame_equal(df, exp_single_row) - - # "c" is not among the categories for df["cat"] - with pytest.raises(ValueError, match=msg1): - indexer(df)[key, :] = ["c", 2] - - @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) - def test_loc_iloc_setitem_partial_col_categorical_rhs( - self, orig, exp_parts_cats_col, indexer - ): - # assign a part of a column with dtype == categorical -> - # exp_parts_cats_col - df = orig.copy() - - key = (slice(2, 4), 0) - if indexer is tm.loc: - key = (slice("j", "k"), df.columns[0]) - - # same categories as we currently have in df["cats"] - compat = Categorical(["b", "b"], categories=["a", "b"]) - indexer(df)[key] = compat - tm.assert_frame_equal(df, exp_parts_cats_col) - - # categories do not match df["cat"]'s, but "b" is among them - semi_compat = Categorical(list("bb"), categories=list("abc")) - with pytest.raises(ValueError, match=msg2): - # different categories but holdable values - # -> not sure if this should fail or pass - indexer(df)[key] = semi_compat - - # categories do not match df["cat"]'s, and "c" is not among them - incompat = Categorical(list("cc"), categories=list("abc")) - with pytest.raises(ValueError, match=msg2): - # different values - indexer(df)[key] = incompat - - @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) - def test_loc_iloc_setitem_non_categorical_rhs( - self, orig, exp_parts_cats_col, indexer - ): - # assign a part of a column with dtype != categorical -> exp_parts_cats_col - df = orig.copy() - - key = (slice(2, 4), 0) - if indexer is tm.loc: - key = (slice("j", "k"), df.columns[0]) - - # "b" is among the categories for df["cat"] - indexer(df)[key] = ["b", "b"] - tm.assert_frame_equal(df, exp_parts_cats_col) - - # "c" not part of the categories - with pytest.raises(ValueError, match=msg1): - indexer(df)[key] = ["c", "c"] - - def test_setitem_mask_categorical(self, exp_multi_row): - # fancy indexing - - catsf = Categorical( - ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] - ) - idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) - valuesf = [1, 1, 3, 3, 1, 1, 1] - df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) - - exp_fancy = exp_multi_row.copy() - return_value = exp_fancy["cats"].cat.set_categories( - ["a", "b", "c"], inplace=True - ) - assert return_value is None - - mask = df["cats"] == "c" - df[mask] = ["b", 2] - # category c is kept in .categories - tm.assert_frame_equal(df, exp_fancy) - - def test_loc_setitem_categorical_values_partial_column_slice(self): - # Assigning a Category to parts of a int/... column uses the values of - # the Categorical - df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) - exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")}) - df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"]) - df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"]) - tm.assert_frame_equal(df, exp) - - def test_loc_setitem_single_row_categorical(self): - # GH 25495 - df = DataFrame({"Alpha": ["a"], "Numeric": [0]}) - categories = Categorical(df["Alpha"], categories=["a", "b", "c"]) - df.loc[:, "Alpha"] = categories - - result = df["Alpha"] - expected = Series(categories, index=df.index, name="Alpha") - tm.assert_series_equal(result, expected) - - def test_loc_indexing_preserves_index_category_dtype(self): - # GH 15166 - df = DataFrame( - data=np.arange(2, 22, 2), - index=pd.MultiIndex( - levels=[pd.CategoricalIndex(["a", "b"]), range(10)], - codes=[[0] * 5 + [1] * 5, range(10)], - names=["Index1", "Index2"], - ), - ) - - expected = pd.CategoricalIndex( - ["a", "b"], - categories=["a", "b"], - ordered=False, - name="Index1", - dtype="category", - ) - - result = df.index.levels[0] - tm.assert_index_equal(result, expected) - - result = df.loc[["a"]].index.levels[0] - tm.assert_index_equal(result, expected) diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py index 7c48c412fd694..290ba67c7d05b 100644 --- a/pandas/tests/frame/indexing/test_getitem.py +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pytest @@ -81,6 +83,67 @@ def test_getitem_list_missing_key(self): with pytest.raises(KeyError, match=r"\['y'\] not in index"): df[["x", "y", "z"]] + def test_getitem_list_duplicates(self): + # GH#1943 + df = DataFrame(np.random.randn(4, 4), columns=list("AABC")) + df.columns.name = "foo" + + result = df[["B", "C"]] + assert result.columns.name == "foo" + + expected = df.iloc[:, 2:] + tm.assert_frame_equal(result, expected) + + def test_getitem_dupe_cols(self): + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) + msg = "\"None of [Index(['baf'], dtype='object')] are in the [columns]\"" + with pytest.raises(KeyError, match=re.escape(msg)): + df[["baf"]] + + @pytest.mark.parametrize( + "idx_type", + [ + list, + iter, + Index, + set, + lambda l: dict(zip(l, range(len(l)))), + lambda l: dict(zip(l, range(len(l)))).keys(), + ], + ids=["list", "iter", "Index", "set", "dict", "dict_keys"], + ) + @pytest.mark.parametrize("levels", [1, 2]) + def test_getitem_listlike(self, idx_type, levels, float_frame): + # GH#21294 + + if levels == 1: + frame, missing = float_frame, "food" + else: + # MultiIndex columns + frame = DataFrame( + np.random.randn(8, 3), + columns=Index( + [("foo", "bar"), ("baz", "qux"), ("peek", "aboo")], + name=("sth", "sth2"), + ), + ) + missing = ("good", "food") + + keys = [frame.columns[1], frame.columns[0]] + idx = idx_type(keys) + idx_check = list(idx_type(keys)) + + result = frame[idx] + + expected = frame.loc[:, idx_check] + expected.columns.names = frame.columns.names + + tm.assert_frame_equal(result, expected) + + idx = idx_type(keys + [missing]) + with pytest.raises(KeyError, match="not in index"): + frame[idx] + class TestGetitemCallable: def test_getitem_callable(self, float_frame): @@ -258,6 +321,13 @@ def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols): result.dtypes str(result) + def test_getitem_empty_frame_with_boolean(self): + # Test for issue GH#11859 + + df = DataFrame() + df2 = df[df > 0] + tm.assert_frame_equal(df, df2) + class TestGetitemSlice: def test_getitem_slice_float64(self, frame_or_series): diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 9b6bdbf3a9d60..366ccf2fc9219 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1,7 +1,5 @@ from datetime import ( - date, datetime, - time, timedelta, ) import re @@ -15,6 +13,7 @@ import pandas as pd from pandas import ( + Categorical, DataFrame, DatetimeIndex, Index, @@ -27,9 +26,6 @@ ) import pandas._testing as tm import pandas.core.common as com -from pandas.core.indexing import IndexingError - -from pandas.tseries.offsets import BDay # We pass through a TypeError raised by numpy _slice_msg = "slice indices must be integers or None or have an __index__ method" @@ -53,6 +49,8 @@ def test_getitem(self, float_frame): with pytest.raises(KeyError, match="random"): float_frame["random"] + def test_getitem2(self, float_frame): + df = float_frame.copy() df["$10"] = np.random.randn(len(df)) @@ -65,56 +63,6 @@ def test_getitem(self, float_frame): res = df["@awesome_domain"] tm.assert_numpy_array_equal(ad, res.values) - def test_getitem_dupe_cols(self): - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) - msg = "\"None of [Index(['baf'], dtype='object')] are in the [columns]\"" - with pytest.raises(KeyError, match=re.escape(msg)): - df[["baf"]] - - @pytest.mark.parametrize( - "idx_type", - [ - list, - iter, - Index, - set, - lambda l: dict(zip(l, range(len(l)))), - lambda l: dict(zip(l, range(len(l)))).keys(), - ], - ids=["list", "iter", "Index", "set", "dict", "dict_keys"], - ) - @pytest.mark.parametrize("levels", [1, 2]) - def test_getitem_listlike(self, idx_type, levels, float_frame): - # GH 21294 - - if levels == 1: - frame, missing = float_frame, "food" - else: - # MultiIndex columns - frame = DataFrame( - np.random.randn(8, 3), - columns=Index( - [("foo", "bar"), ("baz", "qux"), ("peek", "aboo")], - name=("sth", "sth2"), - ), - ) - missing = ("good", "food") - - keys = [frame.columns[1], frame.columns[0]] - idx = idx_type(keys) - idx_check = list(idx_type(keys)) - - result = frame[idx] - - expected = frame.loc[:, idx_check] - expected.columns.names = frame.columns.names - - tm.assert_frame_equal(result, expected) - - idx = idx_type(keys + [missing]) - with pytest.raises(KeyError, match="not in index"): - frame[idx] - def test_setitem_list(self, float_frame): float_frame["E"] = "foo" @@ -135,6 +83,8 @@ def test_setitem_list(self, float_frame): with pytest.raises(ValueError, match=msg): data["A"] = newcolumndata + def test_setitem_list2(self): + df = DataFrame(0, index=range(3), columns=["tt1", "tt2"], dtype=np.int_) df.loc[1, ["tt1", "tt2"]] = [1, 2] @@ -235,17 +185,6 @@ def test_setitem_multi_index(self): df[("joe", "last")] = df[("jolie", "first")].loc[i, j] tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")]) - def test_setitem_other_callable(self): - # GH 13299 - def inc(x): - return x + 1 - - df = DataFrame([[-1, 1], [1, -1]]) - df[df > 0] = inc - - expected = DataFrame([[-1, inc], [inc, -1]]) - tm.assert_frame_equal(df, expected) - @pytest.mark.parametrize( "cols, values, expected", [ @@ -490,21 +429,6 @@ def test_setitem(self, float_frame): df.loc[0] = np.nan tm.assert_frame_equal(df, expected) - def test_setitem_tuple(self, float_frame): - float_frame["A", "B"] = float_frame["A"] - assert ("A", "B") in float_frame.columns - - result = float_frame["A", "B"] - expected = float_frame["A"] - tm.assert_series_equal(result, expected, check_names=False) - - def test_setitem_always_copy(self, float_frame): - s = float_frame["A"].copy() - float_frame["E"] = s - - float_frame["E"][5:10] = np.nan - assert notna(s[5:10]).all() - def test_setitem_boolean(self, float_frame): df = float_frame.copy() values = float_frame.values @@ -612,15 +536,6 @@ def test_setitem_boolean_column(self, float_frame): tm.assert_frame_equal(float_frame, expected) - def test_frame_setitem_timestamp(self): - # GH#2155 - columns = date_range(start="1/1/2012", end="2/1/2012", freq=BDay()) - data = DataFrame(columns=columns, index=range(10)) - t = datetime(2012, 11, 1) - ts = Timestamp(t) - data[ts] = np.nan # works, mostly a smoke-test - assert np.isnan(data[ts]).all() - def test_setitem_corner(self, float_frame): # corner case df = DataFrame({"B": [1.0, 2.0, 3.0], "C": ["a", "b", "c"]}, index=np.arange(3)) @@ -698,22 +613,6 @@ def test_setitem_ambig(self): assert len(dm.columns) == 3 assert dm[2].dtype == np.object_ - def test_setitem_clear_caches(self): - # see gh-304 - df = DataFrame( - {"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3] - ) - df.insert(2, "z", np.nan) - - # cache it - foo = df["z"] - df.loc[df.index[2:], "z"] = 42 - - expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z") - - assert df["z"] is not foo - tm.assert_series_equal(df["z"], expected) - def test_setitem_None(self, float_frame): # GH #766 float_frame[None] = float_frame["A"] @@ -726,7 +625,7 @@ def test_setitem_None(self, float_frame): tm.assert_series_equal(float_frame[None], float_frame["A"], check_names=False) repr(float_frame) - def test_setitem_empty(self): + def test_loc_setitem_boolean_mask_allfalse(self): # GH 9596 df = DataFrame( {"a": ["1", "2", "3"], "b": ["11", "22", "33"], "c": ["111", "222", "333"]} @@ -736,39 +635,6 @@ def test_setitem_empty(self): result.loc[result.b.isna(), "a"] = result.a tm.assert_frame_equal(result, df) - @pytest.mark.parametrize("dtype", ["float", "int64"]) - @pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}]) - def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): - # see gh-10126 - kwargs["dtype"] = dtype - df = DataFrame(**kwargs) - - df2 = df.copy() - df[df > df2] = 47 - tm.assert_frame_equal(df, df2) - - def test_setitem_with_empty_listlike(self): - # GH #17101 - index = Index([], name="idx") - result = DataFrame(columns=["A"], index=index) - result["A"] = [] - expected = DataFrame(columns=["A"], index=index) - tm.assert_index_equal(result.index, expected.index) - - def test_setitem_scalars_no_index(self): - # GH16823 / 17894 - df = DataFrame() - df["foo"] = 1 - expected = DataFrame(columns=["foo"]).astype(np.int64) - tm.assert_frame_equal(df, expected) - - def test_getitem_empty_frame_with_boolean(self): - # Test for issue #11859 - - df = DataFrame() - df2 = df[df > 0] - tm.assert_frame_equal(df, df2) - def test_getitem_fancy_slice_integers_step(self): df = DataFrame(np.random.randn(10, 5)) @@ -926,14 +792,6 @@ def test_getitem_fancy_ints(self, float_frame): expected = float_frame.loc[:, float_frame.columns[[2, 0, 1]]] tm.assert_frame_equal(result, expected) - def test_iloc_getitem_setitem_fancy_exceptions(self, float_frame): - with pytest.raises(IndexingError, match="Too many indexers"): - float_frame.iloc[:, :, :] - - with pytest.raises(IndexError, match="too many indices for array"): - # GH#32257 we let numpy do validation, get their exception - float_frame.iloc[:, :, :] = 1 - def test_getitem_setitem_boolean_misaligned(self, float_frame): # boolean index misaligned labels mask = float_frame["A"][::-1] > 1 @@ -1244,17 +1102,6 @@ def test_getitem_setitem_ix_bool_keyerror(self): with pytest.raises(KeyError, match=msg): df.loc[True] = 0 - def test_getitem_list_duplicates(self): - # #1943 - df = DataFrame(np.random.randn(4, 4), columns=list("AABC")) - df.columns.name = "foo" - - result = df[["B", "C"]] - assert result.columns.name == "foo" - - expected = df.iloc[:, 2:] - tm.assert_frame_equal(result, expected) - # TODO: rename? remove? def test_single_element_ix_dont_upcast(self, float_frame): float_frame["E"] = 1 @@ -1384,39 +1231,6 @@ def test_set_dataframe_column_ns_dtype(self): x = DataFrame([datetime.now(), datetime.now()]) assert x[0].dtype == np.dtype("M8[ns]") - def test_iloc_getitem_float_duplicates(self): - df = DataFrame( - np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list("abc") - ) - expect = df.iloc[1:] - tm.assert_frame_equal(df.loc[0.2], expect) - - expect = df.iloc[1:, 0] - tm.assert_series_equal(df.loc[0.2, "a"], expect) - - df.index = [1, 0.2, 0.2] - expect = df.iloc[1:] - tm.assert_frame_equal(df.loc[0.2], expect) - - expect = df.iloc[1:, 0] - tm.assert_series_equal(df.loc[0.2, "a"], expect) - - df = DataFrame( - np.random.randn(4, 3), index=[1, 0.2, 0.2, 1], columns=list("abc") - ) - expect = df.iloc[1:-1] - tm.assert_frame_equal(df.loc[0.2], expect) - - expect = df.iloc[1:-1, 0] - tm.assert_series_equal(df.loc[0.2, "a"], expect) - - df.index = [0.1, 0.2, 2, 0.2] - expect = df.iloc[[1, -1]] - tm.assert_frame_equal(df.loc[0.2], expect) - - expect = df.iloc[[1, -1], 0] - tm.assert_series_equal(df.loc[0.2, "a"], expect) - def test_setitem_with_unaligned_tz_aware_datetime_column(self): # GH 12981 # Assignment of unaligned offset-aware datetime series. @@ -1430,18 +1244,6 @@ def test_setitem_with_unaligned_tz_aware_datetime_column(self): df.loc[[0, 1, 2], "dates"] = column[[1, 0, 2]] tm.assert_series_equal(df["dates"], column) - def test_loc_setitem_datetime_coercion(self): - # gh-1048 - df = DataFrame({"c": [Timestamp("2010-10-01")] * 3}) - df.loc[0:1, "c"] = np.datetime64("2008-08-08") - assert Timestamp("2008-08-08") == df.loc[0, "c"] - assert Timestamp("2008-08-08") == df.loc[1, "c"] - df.loc[2, "c"] = date(2005, 5, 5) - with tm.assert_produces_warning(FutureWarning): - # Comparing Timestamp to date obj is deprecated - assert Timestamp("2005-05-05") == df.loc[2, "c"] - assert Timestamp("2005-05-05").date() == df.loc[2, "c"] - def test_loc_setitem_datetimelike_with_inference(self): # GH 7592 # assignment of timedeltas with NaT @@ -1464,48 +1266,6 @@ def test_loc_setitem_datetimelike_with_inference(self): ) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("idxer", ["var", ["var"]]) - def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture): - # GH 11365 - tz = tz_naive_fixture - idx = date_range(start="2015-07-12", periods=3, freq="H", tz=tz) - expected = DataFrame(1.2, index=idx, columns=["var"]) - result = DataFrame(index=idx, columns=["var"]) - result.loc[:, idxer] = expected - tm.assert_frame_equal(result, expected) - - def test_loc_setitem_time_key(self): - index = date_range("2012-01-01", "2012-01-05", freq="30min") - df = DataFrame(np.random.randn(len(index), 5), index=index) - akey = time(12, 0, 0) - bkey = slice(time(13, 0, 0), time(14, 0, 0)) - ainds = [24, 72, 120, 168] - binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172] - - result = df.copy() - result.loc[akey] = 0 - result = result.loc[akey] - expected = df.loc[akey].copy() - expected.loc[:] = 0 - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.loc[akey] = 0 - result.loc[akey] = df.iloc[ainds] - tm.assert_frame_equal(result, df) - - result = df.copy() - result.loc[bkey] = 0 - result = result.loc[bkey] - expected = df.loc[bkey].copy() - expected.loc[:] = 0 - tm.assert_frame_equal(result, expected) - - result = df.copy() - result.loc[bkey] = 0 - result.loc[bkey] = df.iloc[binds] - tm.assert_frame_equal(result, df) - def test_loc_getitem_index_namedtuple(self): from collections import namedtuple @@ -1533,29 +1293,6 @@ def test_loc_getitem_index_single_double_tuples(self, tpl): expected = DataFrame(index=idx) tm.assert_frame_equal(result, expected) - def test_setitem_boolean_indexing(self): - idx = list(range(3)) - cols = ["A", "B", "C"] - df1 = DataFrame( - index=idx, - columns=cols, - data=np.array( - [[0.0, 0.5, 1.0], [1.5, 2.0, 2.5], [3.0, 3.5, 4.0]], dtype=float - ), - ) - df2 = DataFrame(index=idx, columns=cols, data=np.ones((len(idx), len(cols)))) - - expected = DataFrame( - index=idx, - columns=cols, - data=np.array([[0.0, 0.5, 1.0], [1.5, 2.0, -1], [-1, -1, -1]], dtype=float), - ) - - df1[df1 > 2.0 * df2] = -1 - tm.assert_frame_equal(df1, expected) - with pytest.raises(ValueError, match="Item wrong length"): - df1[df1.index[:-1] > 2] = -1 - def test_getitem_boolean_indexing_mixed(self): df = DataFrame( { @@ -1664,21 +1401,6 @@ def test_getitem_interval_index_partial_indexing(self): res = df.loc[:, 0.5] tm.assert_series_equal(res, expected) - @pytest.mark.parametrize("indexer", ["A", ["A"], ("A", slice(None))]) - def test_setitem_unsorted_multiindex_columns(self, indexer): - # GH#38601 - mi = MultiIndex.from_tuples([("A", 4), ("B", "3"), ("A", "2")]) - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi) - obj = df.copy() - obj.loc[:, indexer] = np.zeros((2, 2), dtype=int) - expected = DataFrame([[0, 2, 0], [0, 5, 0]], columns=mi) - tm.assert_frame_equal(obj, expected) - - df = df.sort_index(1) - df.loc[:, indexer] = np.zeros((2, 2), dtype=int) - expected = expected.sort_index(1) - tm.assert_frame_equal(df, expected) - class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame): @@ -1687,9 +1409,11 @@ def test_setitem(self, uint64_frame): idx = df["A"].rename("foo") # setitem + assert "C" not in df.columns df["C"] = idx tm.assert_series_equal(df["C"], Series(idx, name="C")) + assert "D" not in df.columns df["D"] = "foo" df["D"] = idx tm.assert_series_equal(df["D"], Series(idx, name="D")) @@ -1748,3 +1472,174 @@ def test_object_casting_indexing_wraps_datetimelike(): assert blk.dtype == "m8[ns]" # we got the right block val = blk.iget((0, 0)) assert isinstance(val, pd.Timedelta) + + +msg1 = "Cannot setitem on a Categorical with a new category, set the categories first" +msg2 = "Cannot set a Categorical with another, without identical categories" + + +class TestLocILocDataFrameCategorical: + @pytest.fixture + def orig(self): + cats = Categorical(["a", "a", "a", "a", "a", "a", "a"], categories=["a", "b"]) + idx = Index(["h", "i", "j", "k", "l", "m", "n"]) + values = [1, 1, 1, 1, 1, 1, 1] + orig = DataFrame({"cats": cats, "values": values}, index=idx) + return orig + + @pytest.fixture + def exp_single_row(self): + # The expected values if we change a single row + cats1 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) + idx1 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values1 = [1, 1, 2, 1, 1, 1, 1] + exp_single_row = DataFrame({"cats": cats1, "values": values1}, index=idx1) + return exp_single_row + + @pytest.fixture + def exp_multi_row(self): + # assign multiple rows (mixed values) (-> array) -> exp_multi_row + # changed multiple rows + cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) + idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values2 = [1, 1, 2, 2, 1, 1, 1] + exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) + return exp_multi_row + + @pytest.fixture + def exp_parts_cats_col(self): + # changed part of the cats column + cats3 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) + idx3 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values3 = [1, 1, 1, 1, 1, 1, 1] + exp_parts_cats_col = DataFrame({"cats": cats3, "values": values3}, index=idx3) + return exp_parts_cats_col + + @pytest.fixture + def exp_single_cats_value(self): + # changed single value in cats col + cats4 = Categorical(["a", "a", "b", "a", "a", "a", "a"], categories=["a", "b"]) + idx4 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values4 = [1, 1, 1, 1, 1, 1, 1] + exp_single_cats_value = DataFrame( + {"cats": cats4, "values": values4}, index=idx4 + ) + return exp_single_cats_value + + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_list_of_lists(self, orig, exp_multi_row, indexer): + # - assign multiple rows (mixed values) -> exp_multi_row + df = orig.copy() + + key = slice(2, 4) + if indexer is tm.loc: + key = slice("j", "k") + + indexer(df)[key, :] = [["b", 2], ["b", 2]] + tm.assert_frame_equal(df, exp_multi_row) + + df = orig.copy() + with pytest.raises(ValueError, match=msg1): + indexer(df)[key, :] = [["c", 2], ["c", 2]] + + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc, tm.at, tm.iat]) + def test_loc_iloc_at_iat_setitem_single_value_in_categories( + self, orig, exp_single_cats_value, indexer + ): + # - assign a single value -> exp_single_cats_value + df = orig.copy() + + key = (2, 0) + if indexer in [tm.loc, tm.at]: + key = (df.index[2], df.columns[0]) + + # "b" is among the categories for df["cat"}] + indexer(df)[key] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + # "c" is not among the categories for df["cat"] + with pytest.raises(ValueError, match=msg1): + indexer(df)[key] = "c" + + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_mask_single_value_in_categories( + self, orig, exp_single_cats_value, indexer + ): + # mask with single True + df = orig.copy() + + mask = df.index == "j" + key = 0 + if indexer is tm.loc: + key = df.columns[key] + + indexer(df)[mask, key] = "b" + tm.assert_frame_equal(df, exp_single_cats_value) + + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_full_row_non_categorical_rhs( + self, orig, exp_single_row, indexer + ): + # - assign a complete row (mixed values) -> exp_single_row + df = orig.copy() + + key = 2 + if indexer is tm.loc: + key = df.index[2] + + # not categorical dtype, but "b" _is_ among the categories for df["cat"] + indexer(df)[key, :] = ["b", 2] + tm.assert_frame_equal(df, exp_single_row) + + # "c" is not among the categories for df["cat"] + with pytest.raises(ValueError, match=msg1): + indexer(df)[key, :] = ["c", 2] + + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_partial_col_categorical_rhs( + self, orig, exp_parts_cats_col, indexer + ): + # assign a part of a column with dtype == categorical -> + # exp_parts_cats_col + df = orig.copy() + + key = (slice(2, 4), 0) + if indexer is tm.loc: + key = (slice("j", "k"), df.columns[0]) + + # same categories as we currently have in df["cats"] + compat = Categorical(["b", "b"], categories=["a", "b"]) + indexer(df)[key] = compat + tm.assert_frame_equal(df, exp_parts_cats_col) + + # categories do not match df["cat"]'s, but "b" is among them + semi_compat = Categorical(list("bb"), categories=list("abc")) + with pytest.raises(ValueError, match=msg2): + # different categories but holdable values + # -> not sure if this should fail or pass + indexer(df)[key] = semi_compat + + # categories do not match df["cat"]'s, and "c" is not among them + incompat = Categorical(list("cc"), categories=list("abc")) + with pytest.raises(ValueError, match=msg2): + # different values + indexer(df)[key] = incompat + + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) + def test_loc_iloc_setitem_non_categorical_rhs( + self, orig, exp_parts_cats_col, indexer + ): + # assign a part of a column with dtype != categorical -> exp_parts_cats_col + df = orig.copy() + + key = (slice(2, 4), 0) + if indexer is tm.loc: + key = (slice("j", "k"), df.columns[0]) + + # "b" is among the categories for df["cat"] + indexer(df)[key] = ["b", "b"] + tm.assert_frame_equal(df, exp_parts_cats_col) + + # "c" not part of the categories + with pytest.raises(ValueError, match=msg1): + indexer(df)[key] = ["c", "c"] diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 6a9d4e6b5ab3c..7e3de9a5ae67c 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -1,3 +1,5 @@ +from datetime import datetime + import numpy as np import pytest @@ -8,6 +10,7 @@ is_object_dtype, ) from pandas.core.dtypes.dtypes import ( + CategoricalDtype, DatetimeTZDtype, IntervalDtype, PeriodDtype, @@ -33,6 +36,8 @@ import pandas._testing as tm from pandas.core.arrays import SparseArray +from pandas.tseries.offsets import BDay + class TestDataFrameSetItem: @pytest.mark.parametrize("dtype", ["int32", "int64", "float32", "float64"]) @@ -454,6 +459,14 @@ def test_setitem_categorical(self): ) tm.assert_frame_equal(df, expected) + def test_setitem_with_empty_listlike(self): + # GH#17101 + index = Index([], name="idx") + result = DataFrame(columns=["A"], index=index) + result["A"] = [] + expected = DataFrame(columns=["A"], index=index) + tm.assert_index_equal(result.index, expected.index) + class TestSetitemTZAwareValues: @pytest.fixture @@ -534,6 +547,79 @@ def test_setitem_empty_df_duplicate_columns(self): ) tm.assert_frame_equal(df, expected) + def test_setitem_with_expansion_categorical_dtype(self): + # assignment + df = DataFrame( + {"value": np.array(np.random.randint(0, 10000, 100), dtype="int32")} + ) + labels = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + + df = df.sort_values(by=["value"], ascending=True) + ser = cut(df.value, range(0, 10500, 500), right=False, labels=labels) + cat = ser.values + + # setting with a Categorical + df["D"] = cat + str(df) + + result = df.dtypes + expected = Series( + [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], + index=["value", "D"], + ) + tm.assert_series_equal(result, expected) + + # setting with a Series + df["E"] = ser + str(df) + + result = df.dtypes + expected = Series( + [ + np.dtype("int32"), + CategoricalDtype(categories=labels, ordered=False), + CategoricalDtype(categories=labels, ordered=False), + ], + index=["value", "D", "E"], + ) + tm.assert_series_equal(result, expected) + + result1 = df["D"] + result2 = df["E"] + tm.assert_categorical_equal(result1._mgr._block.values, cat) + + # sorting + ser.name = "E" + tm.assert_series_equal(result2.sort_index(), ser.sort_index()) + + def test_setitem_scalars_no_index(self): + # GH#16823 / GH#17894 + df = DataFrame() + df["foo"] = 1 + expected = DataFrame(columns=["foo"]).astype(np.int64) + tm.assert_frame_equal(df, expected) + + def test_setitem_newcol_tuple_key(self, float_frame): + assert ( + "A", + "B", + ) not in float_frame.columns + float_frame["A", "B"] = float_frame["A"] + assert ("A", "B") in float_frame.columns + + result = float_frame["A", "B"] + expected = float_frame["A"] + tm.assert_series_equal(result, expected, check_names=False) + + def test_frame_setitem_newcol_timestamp(self): + # GH#2155 + columns = date_range(start="1/1/2012", end="2/1/2012", freq=BDay()) + data = DataFrame(columns=columns, index=range(10)) + t = datetime(2012, 11, 1) + ts = Timestamp(t) + data[ts] = np.nan # works, mostly a smoke-test + assert np.isnan(data[ts]).all() + class TestDataFrameSetItemSlicing: def test_setitem_slice_position(self): @@ -555,6 +641,17 @@ def test_setitem_callable(self): exp = DataFrame({"A": [11, 12, 13, 14], "B": [5, 6, 7, 8]}) tm.assert_frame_equal(df, exp) + def test_setitem_other_callable(self): + # GH#13299 + def inc(x): + return x + 1 + + df = DataFrame([[-1, 1], [1, -1]]) + df[df > 0] = inc + + expected = DataFrame([[-1, inc], [inc, -1]]) + tm.assert_frame_equal(df, expected) + class TestDataFrameSetItemBooleanMask: @pytest.mark.parametrize( @@ -584,3 +681,89 @@ def test_setitem_boolean_mask_aligning(self, indexer): mask = df["a"] >= 3 indexer(df)[mask] = indexer(df)[mask].sort_values("a") tm.assert_frame_equal(df, expected) + + def test_setitem_mask_categorical(self): + # assign multiple rows (mixed values) (-> array) -> exp_multi_row + # changed multiple rows + cats2 = Categorical(["a", "a", "b", "b", "a", "a", "a"], categories=["a", "b"]) + idx2 = Index(["h", "i", "j", "k", "l", "m", "n"]) + values2 = [1, 1, 2, 2, 1, 1, 1] + exp_multi_row = DataFrame({"cats": cats2, "values": values2}, index=idx2) + + catsf = Categorical( + ["a", "a", "c", "c", "a", "a", "a"], categories=["a", "b", "c"] + ) + idxf = Index(["h", "i", "j", "k", "l", "m", "n"]) + valuesf = [1, 1, 3, 3, 1, 1, 1] + df = DataFrame({"cats": catsf, "values": valuesf}, index=idxf) + + exp_fancy = exp_multi_row.copy() + return_value = exp_fancy["cats"].cat.set_categories( + ["a", "b", "c"], inplace=True + ) + assert return_value is None + + mask = df["cats"] == "c" + df[mask] = ["b", 2] + # category c is kept in .categories + tm.assert_frame_equal(df, exp_fancy) + + @pytest.mark.parametrize("dtype", ["float", "int64"]) + @pytest.mark.parametrize("kwargs", [{}, {"index": [1]}, {"columns": ["A"]}]) + def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): + # see GH#10126 + kwargs["dtype"] = dtype + df = DataFrame(**kwargs) + + df2 = df.copy() + df[df > df2] = 47 + tm.assert_frame_equal(df, df2) + + def test_setitem_boolean_indexing(self): + idx = list(range(3)) + cols = ["A", "B", "C"] + df1 = DataFrame( + index=idx, + columns=cols, + data=np.array( + [[0.0, 0.5, 1.0], [1.5, 2.0, 2.5], [3.0, 3.5, 4.0]], dtype=float + ), + ) + df2 = DataFrame(index=idx, columns=cols, data=np.ones((len(idx), len(cols)))) + + expected = DataFrame( + index=idx, + columns=cols, + data=np.array([[0.0, 0.5, 1.0], [1.5, 2.0, -1], [-1, -1, -1]], dtype=float), + ) + + df1[df1 > 2.0 * df2] = -1 + tm.assert_frame_equal(df1, expected) + with pytest.raises(ValueError, match="Item wrong length"): + df1[df1.index[:-1] > 2] = -1 + + +class TestDataFrameSetitemCopyViewSemantics: + def test_setitem_always_copy(self, float_frame): + assert "E" not in float_frame.columns + s = float_frame["A"].copy() + float_frame["E"] = s + + float_frame["E"][5:10] = np.nan + assert notna(s[5:10]).all() + + def test_setitem_clear_caches(self): + # see GH#304 + df = DataFrame( + {"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3] + ) + df.insert(2, "z", np.nan) + + # cache it + foo = df["z"] + df.loc[df.index[2:], "z"] = 42 + + expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z") + + assert df["z"] is not foo + tm.assert_series_equal(df["z"], expected) diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 3b3ea1227ba99..2c0b88159c8f2 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -973,6 +973,39 @@ def test_iloc_setitem_dictionary_value(self): expected = DataFrame({"x": [1, 9], "y": [2.0, 99.0]}) tm.assert_frame_equal(df, expected) + def test_iloc_getitem_float_duplicates(self): + df = DataFrame( + np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list("abc") + ) + expect = df.iloc[1:] + tm.assert_frame_equal(df.loc[0.2], expect) + + expect = df.iloc[1:, 0] + tm.assert_series_equal(df.loc[0.2, "a"], expect) + + df.index = [1, 0.2, 0.2] + expect = df.iloc[1:] + tm.assert_frame_equal(df.loc[0.2], expect) + + expect = df.iloc[1:, 0] + tm.assert_series_equal(df.loc[0.2, "a"], expect) + + df = DataFrame( + np.random.randn(4, 3), index=[1, 0.2, 0.2, 1], columns=list("abc") + ) + expect = df.iloc[1:-1] + tm.assert_frame_equal(df.loc[0.2], expect) + + expect = df.iloc[1:-1, 0] + tm.assert_series_equal(df.loc[0.2, "a"], expect) + + df.index = [0.1, 0.2, 2, 0.2] + expect = df.iloc[[1, -1]] + tm.assert_frame_equal(df.loc[0.2], expect) + + expect = df.iloc[[1, -1], 0] + tm.assert_series_equal(df.loc[0.2, "a"], expect) + class TestILocErrors: # NB: this test should work for _any_ Series we can pass as @@ -996,6 +1029,14 @@ def test_iloc_float_raises(self, series_with_simple_index, frame_or_series): with pytest.raises(IndexError, match=_slice_iloc_msg): obj.iloc[3.0] = 0 + def test_iloc_getitem_setitem_fancy_exceptions(self, float_frame): + with pytest.raises(IndexingError, match="Too many indexers"): + float_frame.iloc[:, :, :] + + with pytest.raises(IndexError, match="too many indices for array"): + # GH#32257 we let numpy do validation, get their exception + float_frame.iloc[:, :, :] = 1 + class TestILocSetItemDuplicateColumns: def test_iloc_setitem_scalar_duplicate_columns(self): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 829bba5f2930d..fd22b684aba07 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1,5 +1,6 @@ """ test label based indexing with loc """ from datetime import ( + date, datetime, time, timedelta, @@ -1141,6 +1142,94 @@ def test_loc_setitem_listlike_with_timedelta64index(self, indexer, expected): tm.assert_frame_equal(expected, df) + def test_loc_setitem_categorical_values_partial_column_slice(self): + # Assigning a Category to parts of a int/... column uses the values of + # the Categorical + df = DataFrame({"a": [1, 1, 1, 1, 1], "b": list("aaaaa")}) + exp = DataFrame({"a": [1, "b", "b", 1, 1], "b": list("aabba")}) + df.loc[1:2, "a"] = Categorical(["b", "b"], categories=["a", "b"]) + df.loc[2:3, "b"] = Categorical(["b", "b"], categories=["a", "b"]) + tm.assert_frame_equal(df, exp) + + def test_loc_setitem_single_row_categorical(self): + # GH#25495 + df = DataFrame({"Alpha": ["a"], "Numeric": [0]}) + categories = Categorical(df["Alpha"], categories=["a", "b", "c"]) + df.loc[:, "Alpha"] = categories + + result = df["Alpha"] + expected = Series(categories, index=df.index, name="Alpha") + tm.assert_series_equal(result, expected) + + def test_loc_setitem_datetime_coercion(self): + # GH#1048 + df = DataFrame({"c": [Timestamp("2010-10-01")] * 3}) + df.loc[0:1, "c"] = np.datetime64("2008-08-08") + assert Timestamp("2008-08-08") == df.loc[0, "c"] + assert Timestamp("2008-08-08") == df.loc[1, "c"] + df.loc[2, "c"] = date(2005, 5, 5) + with tm.assert_produces_warning(FutureWarning): + # Comparing Timestamp to date obj is deprecated + assert Timestamp("2005-05-05") == df.loc[2, "c"] + assert Timestamp("2005-05-05").date() == df.loc[2, "c"] + + @pytest.mark.parametrize("idxer", ["var", ["var"]]) + def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture): + # GH#11365 + tz = tz_naive_fixture + idx = date_range(start="2015-07-12", periods=3, freq="H", tz=tz) + expected = DataFrame(1.2, index=idx, columns=["var"]) + result = DataFrame(index=idx, columns=["var"]) + result.loc[:, idxer] = expected + tm.assert_frame_equal(result, expected) + + def test_loc_setitem_time_key(self): + index = date_range("2012-01-01", "2012-01-05", freq="30min") + df = DataFrame(np.random.randn(len(index), 5), index=index) + akey = time(12, 0, 0) + bkey = slice(time(13, 0, 0), time(14, 0, 0)) + ainds = [24, 72, 120, 168] + binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172] + + result = df.copy() + result.loc[akey] = 0 + result = result.loc[akey] + expected = df.loc[akey].copy() + expected.loc[:] = 0 + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.loc[akey] = 0 + result.loc[akey] = df.iloc[ainds] + tm.assert_frame_equal(result, df) + + result = df.copy() + result.loc[bkey] = 0 + result = result.loc[bkey] + expected = df.loc[bkey].copy() + expected.loc[:] = 0 + tm.assert_frame_equal(result, expected) + + result = df.copy() + result.loc[bkey] = 0 + result.loc[bkey] = df.iloc[binds] + tm.assert_frame_equal(result, df) + + @pytest.mark.parametrize("key", ["A", ["A"], ("A", slice(None))]) + def test_loc_setitem_unsorted_multiindex_columns(self, key): + # GH#38601 + mi = MultiIndex.from_tuples([("A", 4), ("B", "3"), ("A", "2")]) + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=mi) + obj = df.copy() + obj.loc[:, key] = np.zeros((2, 2), dtype=int) + expected = DataFrame([[0, 2, 0], [0, 5, 0]], columns=mi) + tm.assert_frame_equal(obj, expected) + + df = df.sort_index(1) + df.loc[:, key] = np.zeros((2, 2), dtype=int) + expected = expected.sort_index(1) + tm.assert_frame_equal(df, expected) + class TestLocWithMultiIndex: @pytest.mark.parametrize( @@ -1270,6 +1359,31 @@ def test_loc_getitem_sorted_index_level_with_duplicates(self): result = df.loc[("foo", "bar")] tm.assert_frame_equal(result, expected) + def test_loc_getitem_preserves_index_level_category_dtype(self): + # GH#15166 + df = DataFrame( + data=np.arange(2, 22, 2), + index=MultiIndex( + levels=[CategoricalIndex(["a", "b"]), range(10)], + codes=[[0] * 5 + [1] * 5, range(10)], + names=["Index1", "Index2"], + ), + ) + + expected = CategoricalIndex( + ["a", "b"], + categories=["a", "b"], + ordered=False, + name="Index1", + dtype="category", + ) + + result = df.index.levels[0] + tm.assert_index_equal(result, expected) + + result = df.loc[["a"]].index.levels[0] + tm.assert_index_equal(result, expected) + class TestLocSetitemWithExpansion: @pytest.mark.slow
https://api.github.com/repos/pandas-dev/pandas/pulls/39980
2021-02-22T23:19:40Z
2021-02-23T13:25:48Z
2021-02-23T13:25:48Z
2021-02-23T15:18:26Z
Backport PR #39944 on branch 1.2.x (Fix regression for setitem not aligning rhs with boolean indexer)
diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index 5ed8fd84472c4..d305024909703 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -16,7 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) -- +- Fixed regression in :meth:`DataFrame.__setitem__` not aligning :class:`DataFrame` on right-hand side for boolean indexer (:issue:`39931`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c5324165ef68e..d1855774e5692 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3179,6 +3179,9 @@ def _setitem_array(self, key, value): key = check_bool_indexer(self.index, key) indexer = key.nonzero()[0] self._check_setitem_copy() + if isinstance(value, DataFrame): + # GH#39931 reindex since iloc does not align + value = value.reindex(self.index.take(indexer)) self.iloc[indexer] = value else: if isinstance(value, DataFrame): diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index cedef4784e4a1..d40fc388fefbd 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -404,3 +404,12 @@ def test_setitem_boolean_mask(self, mask_type, float_frame): expected = df.copy() expected.values[np.array(mask)] = np.nan tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("indexer", [lambda x: x, lambda x: x.loc]) + def test_setitem_boolean_mask_aligning(self, indexer): + # GH#39931 + df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]}) + expected = df.copy() + mask = df["a"] >= 3 + indexer(df)[mask] = indexer(df)[mask].sort_values("a") + tm.assert_frame_equal(df, expected)
Backport PR #39944: Fix regression for setitem not aligning rhs with boolean indexer
https://api.github.com/repos/pandas-dev/pandas/pulls/39979
2021-02-22T22:59:46Z
2021-02-23T11:00:57Z
2021-02-23T11:00:56Z
2021-02-23T11:00:57Z
DOC: fix template substitution in pad/bfill docstrings
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 1b7c02cd7a05b..eb4c5c07af2c4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6490,6 +6490,7 @@ def fillna( return result.__finalize__(self, method="fillna") @final + @doc(klass=_shared_doc_kwargs["klass"]) def ffill( self: FrameOrSeries, axis=None, @@ -6512,6 +6513,7 @@ def ffill( pad = ffill @final + @doc(klass=_shared_doc_kwargs["klass"]) def bfill( self: FrameOrSeries, axis=None,
- [ ] closes #39640 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry #39640 Added doc tag above ffill() to substitute klass
https://api.github.com/repos/pandas-dev/pandas/pulls/39978
2021-02-22T21:23:47Z
2021-02-24T13:36:09Z
2021-02-24T13:36:08Z
2021-02-24T15:08:24Z
TST: collect tests by method
diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 35e958ff3a2b1..8c11f659e8454 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -648,3 +648,32 @@ def test_astype_bytes(self): # GH#39474 result = DataFrame(["foo", "bar", "baz"]).astype(bytes) assert result.dtypes[0] == np.dtype("S3") + + +class TestAstypeCategorical: + def test_astype_from_categorical3(self): + df = DataFrame({"cats": [1, 2, 3, 4, 5, 6], "vals": [1, 2, 3, 4, 5, 6]}) + cats = Categorical([1, 2, 3, 4, 5, 6]) + exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) + df["cats"] = df["cats"].astype("category") + tm.assert_frame_equal(exp_df, df) + + def test_astype_from_categorical4(self): + df = DataFrame( + {"cats": ["a", "b", "b", "a", "a", "d"], "vals": [1, 2, 3, 4, 5, 6]} + ) + cats = Categorical(["a", "b", "b", "a", "a", "d"]) + exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) + df["cats"] = df["cats"].astype("category") + tm.assert_frame_equal(exp_df, df) + + def test_categorical_astype_to_int(self, any_int_or_nullable_int_dtype): + # GH#39402 + + df = DataFrame(data={"col1": pd.array([2.0, 1.0, 3.0])}) + df.col1 = df.col1.astype("category") + df.col1 = df.col1.astype(any_int_or_nullable_int_dtype) + expected = DataFrame( + {"col1": pd.array([2, 1, 3], dtype=any_int_or_nullable_int_dtype)} + ) + tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index a3785518c860d..4e068690c41e5 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -351,6 +351,48 @@ def test_astype_bytes(self): class TestAstypeCategorical: + def test_astype_categorical_to_other(self): + cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + ser = Series(np.random.RandomState(0).randint(0, 10000, 100)).sort_values() + ser = cut(ser, range(0, 10500, 500), right=False, labels=cat) + + expected = ser + tm.assert_series_equal(ser.astype("category"), expected) + tm.assert_series_equal(ser.astype(CategoricalDtype()), expected) + msg = r"Cannot cast object dtype to float64" + with pytest.raises(ValueError, match=msg): + ser.astype("float64") + + cat = Series(Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])) + exp = Series(["a", "b", "b", "a", "a", "c", "c", "c"]) + tm.assert_series_equal(cat.astype("str"), exp) + s2 = Series(Categorical(["1", "2", "3", "4"])) + exp2 = Series([1, 2, 3, 4]).astype("int") + tm.assert_series_equal(s2.astype("int"), exp2) + + # object don't sort correctly, so just compare that we have the same + # values + def cmp(a, b): + tm.assert_almost_equal(np.sort(np.unique(a)), np.sort(np.unique(b))) + + expected = Series(np.array(ser.values), name="value_group") + cmp(ser.astype("object"), expected) + cmp(ser.astype(np.object_), expected) + + # array conversion + tm.assert_almost_equal(np.array(ser), np.array(ser.values)) + + tm.assert_series_equal(ser.astype("category"), ser) + tm.assert_series_equal(ser.astype(CategoricalDtype()), ser) + + roundtrip_expected = ser.cat.set_categories( + ser.cat.categories.sort_values() + ).cat.remove_unused_categories() + result = ser.astype("object").astype("category") + tm.assert_series_equal(result, roundtrip_expected) + result = ser.astype("object").astype(CategoricalDtype()) + tm.assert_series_equal(result, roundtrip_expected) + def test_astype_categorical_invalid_conversions(self): # invalid conversion (these are NOT a dtype) cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) @@ -427,3 +469,22 @@ def test_astype_categories_raises(self): s = Series(["a", "b", "a"]) with pytest.raises(TypeError, match="got an unexpected"): s.astype("category", categories=["a", "b"], ordered=True) + + @pytest.mark.parametrize("items", [["a", "b", "c", "a"], [1, 2, 3, 1]]) + def test_astype_from_categorical(self, items): + ser = Series(items) + exp = Series(Categorical(items)) + res = ser.astype("category") + tm.assert_series_equal(res, exp) + + def test_astype_from_categorical_with_keywords(self): + # with keywords + lst = ["a", "b", "c", "a"] + ser = Series(lst) + exp = Series(Categorical(lst, ordered=True)) + res = ser.astype(CategoricalDtype(None, ordered=True)) + tm.assert_series_equal(res, exp) + + exp = Series(Categorical(lst, categories=list("abcdef"), ordered=True)) + res = ser.astype(CategoricalDtype(list("abcdef"), ordered=True)) + tm.assert_series_equal(res, exp) diff --git a/pandas/tests/series/methods/test_dtypes.py b/pandas/tests/series/methods/test_dtypes.py new file mode 100644 index 0000000000000..abc0e5d13aaf7 --- /dev/null +++ b/pandas/tests/series/methods/test_dtypes.py @@ -0,0 +1,8 @@ +import numpy as np + + +class TestSeriesDtypes: + def test_dtype(self, datetime_series): + + assert datetime_series.dtype == np.dtype("float64") + assert datetime_series.dtypes == np.dtype("float64") diff --git a/pandas/tests/series/methods/test_reindex.py b/pandas/tests/series/methods/test_reindex.py index ecf122679f7ca..8e54cbeb313c4 100644 --- a/pandas/tests/series/methods/test_reindex.py +++ b/pandas/tests/series/methods/test_reindex.py @@ -237,6 +237,17 @@ def test_reindex_categorical(): tm.assert_series_equal(result, expected) +def test_reindex_astype_order_consistency(): + # GH#17444 + ser = Series([1, 2, 3], index=[2, 0, 1]) + new_index = [0, 1, 2] + temp_dtype = "category" + new_dtype = str + result = ser.reindex(new_index).astype(temp_dtype).astype(new_dtype) + expected = ser.astype(temp_dtype).reindex(new_index).astype(new_dtype) + tm.assert_series_equal(result, expected) + + def test_reindex_fill_value(): # ----------------------------------------------------------- # floats diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 6cd2a1dd180c1..c2d0bf5975059 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -403,6 +403,15 @@ def test_constructor_categorical_with_coercion(self): result = x.person_name.loc[0] assert result == expected + def test_constructor_series_to_categorical(self): + # see GH#16524: test conversion of Series to Categorical + series = Series(["a", "b", "c"]) + + result = Series(series, dtype="category") + expected = Series(["a", "b", "c"], dtype="category") + + tm.assert_series_equal(result, expected) + def test_constructor_categorical_dtype(self): result = Series( ["a", "b"], dtype=CategoricalDtype(["a", "b", "c"], ordered=True) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py deleted file mode 100644 index 9121a5a5b6b82..0000000000000 --- a/pandas/tests/series/test_dtypes.py +++ /dev/null @@ -1,129 +0,0 @@ -import numpy as np -import pytest - -from pandas.core.dtypes.dtypes import CategoricalDtype - -import pandas as pd -from pandas import ( - Categorical, - DataFrame, - Series, -) -import pandas._testing as tm - - -class TestSeriesDtypes: - def test_dtype(self, datetime_series): - - assert datetime_series.dtype == np.dtype("float64") - assert datetime_series.dtypes == np.dtype("float64") - - def test_astype_from_categorical(self): - items = ["a", "b", "c", "a"] - s = Series(items) - exp = Series(Categorical(items)) - res = s.astype("category") - tm.assert_series_equal(res, exp) - - items = [1, 2, 3, 1] - s = Series(items) - exp = Series(Categorical(items)) - res = s.astype("category") - tm.assert_series_equal(res, exp) - - df = DataFrame({"cats": [1, 2, 3, 4, 5, 6], "vals": [1, 2, 3, 4, 5, 6]}) - cats = Categorical([1, 2, 3, 4, 5, 6]) - exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) - df["cats"] = df["cats"].astype("category") - tm.assert_frame_equal(exp_df, df) - - df = DataFrame( - {"cats": ["a", "b", "b", "a", "a", "d"], "vals": [1, 2, 3, 4, 5, 6]} - ) - cats = Categorical(["a", "b", "b", "a", "a", "d"]) - exp_df = DataFrame({"cats": cats, "vals": [1, 2, 3, 4, 5, 6]}) - df["cats"] = df["cats"].astype("category") - tm.assert_frame_equal(exp_df, df) - - # with keywords - lst = ["a", "b", "c", "a"] - s = Series(lst) - exp = Series(Categorical(lst, ordered=True)) - res = s.astype(CategoricalDtype(None, ordered=True)) - tm.assert_series_equal(res, exp) - - exp = Series(Categorical(lst, categories=list("abcdef"), ordered=True)) - res = s.astype(CategoricalDtype(list("abcdef"), ordered=True)) - tm.assert_series_equal(res, exp) - - def test_astype_categorical_to_other(self): - cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) - ser = Series(np.random.RandomState(0).randint(0, 10000, 100)).sort_values() - ser = pd.cut(ser, range(0, 10500, 500), right=False, labels=cat) - - expected = ser - tm.assert_series_equal(ser.astype("category"), expected) - tm.assert_series_equal(ser.astype(CategoricalDtype()), expected) - msg = r"Cannot cast object dtype to float64" - with pytest.raises(ValueError, match=msg): - ser.astype("float64") - - cat = Series(Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])) - exp = Series(["a", "b", "b", "a", "a", "c", "c", "c"]) - tm.assert_series_equal(cat.astype("str"), exp) - s2 = Series(Categorical(["1", "2", "3", "4"])) - exp2 = Series([1, 2, 3, 4]).astype("int") - tm.assert_series_equal(s2.astype("int"), exp2) - - # object don't sort correctly, so just compare that we have the same - # values - def cmp(a, b): - tm.assert_almost_equal(np.sort(np.unique(a)), np.sort(np.unique(b))) - - expected = Series(np.array(ser.values), name="value_group") - cmp(ser.astype("object"), expected) - cmp(ser.astype(np.object_), expected) - - # array conversion - tm.assert_almost_equal(np.array(ser), np.array(ser.values)) - - tm.assert_series_equal(ser.astype("category"), ser) - tm.assert_series_equal(ser.astype(CategoricalDtype()), ser) - - roundtrip_expected = ser.cat.set_categories( - ser.cat.categories.sort_values() - ).cat.remove_unused_categories() - result = ser.astype("object").astype("category") - tm.assert_series_equal(result, roundtrip_expected) - result = ser.astype("object").astype(CategoricalDtype()) - tm.assert_series_equal(result, roundtrip_expected) - - def test_categorical_astype_to_int(self, any_int_or_nullable_int_dtype): - # GH 39402 - - df = DataFrame(data={"col1": pd.array([2.0, 1.0, 3.0])}) - df.col1 = df.col1.astype("category") - df.col1 = df.col1.astype(any_int_or_nullable_int_dtype) - expected = DataFrame( - {"col1": pd.array([2, 1, 3], dtype=any_int_or_nullable_int_dtype)} - ) - tm.assert_frame_equal(df, expected) - - def test_series_to_categorical(self): - # see gh-16524: test conversion of Series to Categorical - series = Series(["a", "b", "c"]) - - result = Series(series, dtype="category") - expected = Series(["a", "b", "c"], dtype="category") - - tm.assert_series_equal(result, expected) - - def test_reindex_astype_order_consistency(self): - # GH 17444 - s = Series([1, 2, 3], index=[2, 0, 1]) - new_index = [0, 1, 2] - temp_dtype = "category" - new_dtype = str - s1 = s.reindex(new_index).astype(temp_dtype).astype(new_dtype) - s2 = s.astype(temp_dtype).reindex(new_index).astype(new_dtype) - tm.assert_series_equal(s1, s2)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39976
2021-02-22T21:03:48Z
2021-02-22T22:58:05Z
2021-02-22T22:58:05Z
2021-02-22T23:11:02Z
BUG: Incomplete Styler copy methods fix (#39708)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index f7204ceb9d412..08159d6a1d1d4 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -131,7 +131,7 @@ Other enhancements - Disallow :class:`DataFrame` indexer for ``iloc`` for :meth:`Series.__getitem__` and :meth:`DataFrame.__getitem__`, (:issue:`39004`) - :meth:`Series.apply` can now accept list-like or dictionary-like arguments that aren't lists or dictionaries, e.g. ``ser.apply(np.array(["sum", "mean"]))``, which was already the case for :meth:`DataFrame.apply` (:issue:`39140`) - :meth:`DataFrame.plot.scatter` can now accept a categorical column as the argument to ``c`` (:issue:`12380`, :issue:`31357`) -- :meth:`.Styler.set_tooltips` allows on hover tooltips to be added to styled HTML dataframes (:issue:`35643`, :issue:`21266`, :issue:`39317`) +- :meth:`.Styler.set_tooltips` allows on hover tooltips to be added to styled HTML dataframes (:issue:`35643`, :issue:`21266`, :issue:`39317`, :issue:`39708`) - :meth:`.Styler.set_tooltips_class` and :meth:`.Styler.set_table_styles` amended to optionally allow certain css-string input arguments (:issue:`39564`) - :meth:`.Styler.apply` now more consistently accepts ndarray function returns, i.e. in all cases for ``axis`` is ``0, 1 or None`` (:issue:`39359`) - :meth:`.Styler.apply` and :meth:`.Styler.applymap` now raise errors if wrong format CSS is passed on render (:issue:`39660`) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index e50f5986098d3..dcae87f9d6d48 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -785,16 +785,29 @@ def _copy(self, deepcopy: bool = False) -> Styler: self.data, precision=self.precision, caption=self.caption, - uuid=self.uuid, - table_styles=self.table_styles, + table_attributes=self.table_attributes, + cell_ids=self.cell_ids, na_rep=self.na_rep, ) + + styler.uuid = self.uuid + styler.hidden_index = self.hidden_index + if deepcopy: styler.ctx = copy.deepcopy(self.ctx) styler._todo = copy.deepcopy(self._todo) + styler.table_styles = copy.deepcopy(self.table_styles) + styler.hidden_columns = copy.copy(self.hidden_columns) + styler.cell_context = copy.deepcopy(self.cell_context) + styler.tooltips = copy.deepcopy(self.tooltips) else: styler.ctx = self.ctx styler._todo = self._todo + styler.table_styles = self.table_styles + styler.hidden_columns = self.hidden_columns + styler.cell_context = self.cell_context + styler.tooltips = self.tooltips + return styler def __copy__(self) -> Styler: diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index f0d1090899043..09e14d06f4d9b 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -72,28 +72,101 @@ def test_update_ctx_flatten_multi_and_trailing_semi(self): } assert self.styler.ctx == expected - def test_copy(self): - s2 = copy.copy(self.styler) - assert self.styler is not s2 - assert self.styler.ctx is s2.ctx # shallow - assert self.styler._todo is s2._todo - - self.styler._update_ctx(self.attrs) - self.styler.highlight_max() - assert self.styler.ctx == s2.ctx - assert self.styler._todo == s2._todo - - def test_deepcopy(self): - s2 = copy.deepcopy(self.styler) - assert self.styler is not s2 - assert self.styler.ctx is not s2.ctx - assert self.styler._todo is not s2._todo + @pytest.mark.parametrize("do_changes", [True, False]) + @pytest.mark.parametrize("do_render", [True, False]) + def test_copy(self, do_changes, do_render): + # Updated in GH39708 + # Change some defaults (to check later if the new values are copied) + if do_changes: + self.styler.set_table_styles( + [{"selector": "th", "props": [("foo", "bar")]}] + ) + self.styler.set_table_attributes('class="foo" data-bar') + self.styler.hidden_index = not self.styler.hidden_index + self.styler.hide_columns("A") + classes = pd.DataFrame( + [["favorite-val red", ""], [None, "blue my-val"]], + index=self.df.index, + columns=self.df.columns, + ) + self.styler.set_td_classes(classes) + ttips = pd.DataFrame( + data=[["Favorite", ""], [np.nan, "my"]], + columns=self.df.columns, + index=self.df.index, + ) + self.styler.set_tooltips(ttips) + self.styler.cell_ids = not self.styler.cell_ids + + if do_render: + self.styler.render() + + s_copy = copy.copy(self.styler) + s_deepcopy = copy.deepcopy(self.styler) + + assert self.styler is not s_copy + assert self.styler is not s_deepcopy + + # Check for identity + assert self.styler.ctx is s_copy.ctx + assert self.styler._todo is s_copy._todo + assert self.styler.table_styles is s_copy.table_styles + assert self.styler.hidden_columns is s_copy.hidden_columns + assert self.styler.cell_context is s_copy.cell_context + assert self.styler.tooltips is s_copy.tooltips + if do_changes: # self.styler.tooltips is not None + assert self.styler.tooltips.tt_data is s_copy.tooltips.tt_data + assert ( + self.styler.tooltips.class_properties + is s_copy.tooltips.class_properties + ) + assert self.styler.tooltips.table_styles is s_copy.tooltips.table_styles + + # Check for non-identity + assert self.styler.ctx is not s_deepcopy.ctx + assert self.styler._todo is not s_deepcopy._todo + assert self.styler.hidden_columns is not s_deepcopy.hidden_columns + assert self.styler.cell_context is not s_deepcopy.cell_context + if do_changes: # self.styler.table_style is not None + assert self.styler.table_styles is not s_deepcopy.table_styles + if do_changes: # self.styler.tooltips is not None + assert self.styler.tooltips is not s_deepcopy.tooltips + assert self.styler.tooltips.tt_data is not s_deepcopy.tooltips.tt_data + assert ( + self.styler.tooltips.class_properties + is not s_deepcopy.tooltips.class_properties + ) + assert ( + self.styler.tooltips.table_styles + is not s_deepcopy.tooltips.table_styles + ) self.styler._update_ctx(self.attrs) self.styler.highlight_max() - assert self.styler.ctx != s2.ctx - assert s2._todo == [] - assert self.styler._todo != s2._todo + assert self.styler.ctx == s_copy.ctx + assert self.styler.ctx != s_deepcopy.ctx + assert self.styler._todo == s_copy._todo + assert self.styler._todo != s_deepcopy._todo + assert s_deepcopy._todo == [] + + equal_attributes = [ + "table_styles", + "table_attributes", + "cell_ids", + "hidden_index", + "hidden_columns", + "cell_context", + ] + for s2 in [s_copy, s_deepcopy]: + for att in equal_attributes: + assert self.styler.__dict__[att] == s2.__dict__[att] + if do_changes: # self.styler.tooltips is not None + tm.assert_frame_equal(self.styler.tooltips.tt_data, s2.tooltips.tt_data) + assert ( + self.styler.tooltips.class_properties + == s2.tooltips.class_properties + ) + assert self.styler.tooltips.table_styles == s2.tooltips.table_styles def test_clear(self): # updated in GH 39396
- [x] closes #39708 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry I haven't made so many pull requests before, so I hope this is going into the right direction.
https://api.github.com/repos/pandas-dev/pandas/pulls/39975
2021-02-22T20:34:30Z
2021-03-05T00:52:34Z
2021-03-05T00:52:34Z
2021-03-05T08:42:48Z
update pyperclip link
diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index 788fc62165c0c..e9c20ff42f51b 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -66,7 +66,7 @@ EXCEPT_MSG = """ Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit - https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error + https://pyperclip.readthedocs.io/en/latest/#not-implemented-error """ ENCODING = "utf-8"
looks like the link is outdated. updated it. - [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39974
2021-02-22T19:46:44Z
2021-02-22T23:51:51Z
2021-02-22T23:51:51Z
2021-02-23T05:31:59Z
DOC: fix a mis-formatted external link
diff --git a/doc/source/user_guide/cookbook.rst b/doc/source/user_guide/cookbook.rst index 66b564838e5e2..94a5f807d2262 100644 --- a/doc/source/user_guide/cookbook.rst +++ b/doc/source/user_guide/cookbook.rst @@ -1410,7 +1410,7 @@ Often it's useful to obtain the lower (or upper) triangular form of a correlatio corr_mat.where(mask) -The ``method`` argument within ``DataFrame.corr`` can accept a callable in addition to the named correlation types. Here we compute the ``distance correlation <https://en.wikipedia.org/wiki/Distance_correlation>``__ matrix for a ``DataFrame`` object. +The ``method`` argument within ``DataFrame.corr`` can accept a callable in addition to the named correlation types. Here we compute the `distance correlation <https://en.wikipedia.org/wiki/Distance_correlation>`__ matrix for a ``DataFrame`` object. .. ipython:: python
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39973
2021-02-22T17:40:51Z
2021-02-22T23:54:31Z
2021-02-22T23:54:31Z
2021-02-23T01:09:04Z
PERF: halve render time in Styler with itertuples
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d5177075afda5..acab78728ad9a 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -269,6 +269,7 @@ Performance improvements - Performance improvement in :meth:`core.window.rolling.RollingGroupby.corr`, :meth:`core.window.expanding.ExpandingGroupby.corr`, :meth:`core.window.expanding.ExpandingGroupby.corr` and :meth:`core.window.expanding.ExpandingGroupby.cov` (:issue:`39591`) - Performance improvement in :func:`unique` for object data type (:issue:`37615`) - Performance improvement in :class:`core.window.rolling.ExpandingGroupby` aggregation methods (:issue:`39664`) +- Performance improvement in :class:`Styler` where render times are more than 50% reduced (:issue:`39972` :issue:`39952`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 3b0d857217d43..854f41d6b4dc3 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -499,7 +499,7 @@ def _translate(self): head.append(index_header_row) body = [] - for r, idx in enumerate(self.data.index): + for r, row_tup in enumerate(self.data.itertuples()): row_es = [] for c, value in enumerate(rlabels[r]): rid = [ @@ -520,10 +520,9 @@ def _translate(self): es["attributes"] = f'rowspan="{rowspan}"' row_es.append(es) - for c, col in enumerate(self.data.columns): + for c, value in enumerate(row_tup[1:]): cs = [DATA_CLASS, f"row{r}", f"col{c}"] formatter = self._display_funcs[(r, c)] - value = self.data.iloc[r, c] row_dict = { "type": "td", "value": value,
``` before after ratio [dfb92d0f] [e5c2790b] <master> <perf_itertups> - 149±1ms 74.4±2ms 0.50 io.style.RenderApply.time_render(24, 120) - 31.9±1ms 15.9±0.8ms 0.50 io.style.RenderApply.time_render(24, 12) - 86.3±20ms 42.3±1ms 0.49 io.style.RenderApply.time_render(12, 120) - 12.2±0.2ms 5.93±0.2ms 0.49 io.style.RenderApply.time_render(12, 12) - 44.8±0.5ms 21.7±0.3ms 0.48 io.style.RenderApply.time_render(36, 12) - 227±2ms 99.9±1ms 0.44 io.style.RenderApply.time_render(36, 120) SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ``` FYI `Styler` now faster than `to_html`, even without any function stripping... ``` df = pd.DataFrame(np.random.rand(10000,10)) %timeit df.to_html() 1.9 s ± 63.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) %timeit df.style.render() 1.71 s ± 14.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39972
2021-02-22T17:12:44Z
2021-02-23T13:26:50Z
2021-02-23T13:26:50Z
2021-03-30T05:04:59Z
REGR: Fix assignment bug for unary operators
diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index d305024909703..41cea7fe125a1 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -16,6 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) +- Fixed regression in :class:`IntegerArray` unary ops propagating mask on assignment (:issue:`39943`) - Fixed regression in :meth:`DataFrame.__setitem__` not aligning :class:`DataFrame` on right-hand side for boolean indexer (:issue:`39931`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index d62a05253b265..b16b4b3ae856a 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -316,13 +316,13 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): super().__init__(values, mask, copy=copy) def __neg__(self): - return type(self)(-self._data, self._mask) + return type(self)(-self._data, self._mask.copy()) def __pos__(self): return self def __abs__(self): - return type(self)(np.abs(self._data), self._mask) + return type(self)(np.abs(self._data), self._mask.copy()) @classmethod def _from_sequence( diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index bae14f4e560c2..8cf876fa32d7b 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -172,7 +172,7 @@ def __len__(self) -> int: return len(self._data) def __invert__(self: BaseMaskedArrayT) -> BaseMaskedArrayT: - return type(self)(~self._data, self._mask) + return type(self)(~self._data, self._mask.copy()) def to_numpy( self, diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py index 88e11f57a7835..1fc7f824c6daa 100644 --- a/pandas/tests/arrays/masked/test_arithmetic.py +++ b/pandas/tests/arrays/masked/test_arithmetic.py @@ -162,3 +162,16 @@ def test_error_len_mismatch(data, all_arithmetic_operators): s = pd.Series(data) with pytest.raises(ValueError, match="Lengths must match"): op(s, other) + + +@pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"]) +@pytest.mark.parametrize( + "values, dtype", [([1, 2, 3], "Int64"), ([True, False, True], "boolean")] +) +def test_unary_op_does_not_propagate_mask(op, values, dtype): + # https://github.com/pandas-dev/pandas/issues/39943 + s = pd.Series(values, dtype=dtype) + result = getattr(s, op)() + expected = result.copy(deep=True) + s[0] = None + tm.assert_series_equal(result, expected)
- [x] closes https://github.com/pandas-dev/pandas/issues/39943 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry If there was somehow a way to copy the mask only on write so we aren't always copying that may be better. @simonjayhawkins I put this in the `IntegerArray` tests even though we're technically checking a `Series`, let me know if you'd prefer I rewrite or move elsewhere.
https://api.github.com/repos/pandas-dev/pandas/pulls/39971
2021-02-22T16:11:16Z
2021-02-23T11:07:54Z
2021-02-23T11:07:54Z
2021-02-27T12:20:07Z
DOC: fix a warning using obsolete package
diff --git a/doc/source/user_guide/style.ipynb b/doc/source/user_guide/style.ipynb index 57cd67675893b..a67bac0c65462 100644 --- a/doc/source/user_guide/style.ipynb +++ b/doc/source/user_guide/style.ipynb @@ -1154,7 +1154,7 @@ "metadata": {}, "outputs": [], "source": [ - "from IPython.html import widgets\n", + "from ipywidgets import widgets\n", "@widgets.interact\n", "def f(h_neg=(0, 359, 1), h_pos=(0, 359), s=(0., 99.9), l=(0., 99.9)):\n", " return df.style.background_gradient(\n",
currently there is a warning: "/home/runner/miniconda3/envs/pandas-dev/lib/python3.8/site-packages/IPython/html.py:12: ShimWarning: The `IPython.html` package has been deprecated since IPython 4.0. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`. warn("The `IPython.html` package has been deprecated since IPython 4.0. "" this change fixes the warning. - [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39969
2021-02-22T14:36:39Z
2021-02-22T21:41:31Z
2021-02-22T21:41:31Z
2021-02-22T21:54:35Z
Backport PR #39966 on branch 1.2.x (DOC: fix link in 1.2.3 release notes)
diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index 4231b6d94b1b9..5ed8fd84472c4 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -15,7 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- Fixed regression in :func:`pandas.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) +- Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) - .. ---------------------------------------------------------------------------
Backport PR #39966: DOC: fix link in 1.2.3 release notes
https://api.github.com/repos/pandas-dev/pandas/pulls/39968
2021-02-22T13:26:39Z
2021-02-22T15:22:45Z
2021-02-22T15:22:45Z
2021-02-22T15:22:45Z
DOC: fix link in 1.2.3 release notes
diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index 4231b6d94b1b9..5ed8fd84472c4 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -15,7 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- Fixed regression in :func:`pandas.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) +- Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) - .. ---------------------------------------------------------------------------
https://api.github.com/repos/pandas-dev/pandas/pulls/39966
2021-02-22T09:29:23Z
2021-02-22T13:25:41Z
2021-02-22T13:25:41Z
2021-02-22T13:36:42Z
DOC : Updated the comparison with spreadsheets with GroupBy
diff --git a/doc/source/_static/spreadsheets/group-by.png b/doc/source/_static/spreadsheets/group-by.png new file mode 100644 index 0000000000000..984d4e55df33d Binary files /dev/null and b/doc/source/_static/spreadsheets/group-by.png differ diff --git a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst index bdd0f7d8cfddf..a873e671d035b 100644 --- a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst +++ b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst @@ -365,6 +365,27 @@ In Excel, there are `merging of tables can be done through a VLOOKUP * It will include all columns from the lookup table, instead of just a single specified column * It supports :ref:`more complex join operations <merging.join>` +GroupBy +------- + +In Excel, this can be done by using the `Query Editor <hhttps://support.microsoft.com/en-us/office/about-power-query-in-excel-7104fbee-9e62-4cb9-a02e-5bfb1a6c536a>`_. + +.. image:: ../../_static/spreadsheets/group-by.png + +The equivalent in pandas: +We can use :meth:`~DataFrame.groupby`. +For example - + +.. ipython:: python + + df = pd.DataFrame( + { + 'Animal': ['Falcon', 'Falcon', 'Parrot', 'Parrot'], + 'Max Speed': [380., 370., 24., 26.], + } + ) + df + df.groupby(['Animal']).mean() Other considerations --------------------
- [x] part of #38990 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39965
2021-02-22T06:19:14Z
2021-07-29T20:35:07Z
null
2021-07-29T20:35:08Z
CI: conditional xfail flaky test
diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py index 3d9d780a1e878..8e1e9fb6e458f 100644 --- a/pandas/tests/io/parser/common/test_chunksize.py +++ b/pandas/tests/io/parser/common/test_chunksize.py @@ -173,7 +173,7 @@ def test_chunks_have_consistent_numerical_type(all_parsers): assert result.a.dtype == float -def test_warn_if_chunks_have_mismatched_type(all_parsers): +def test_warn_if_chunks_have_mismatched_type(all_parsers, request): warning_type = None parser = all_parsers integers = [str(i) for i in range(499999)] @@ -184,8 +184,27 @@ def test_warn_if_chunks_have_mismatched_type(all_parsers): if parser.engine == "c" and parser.low_memory: warning_type = DtypeWarning - with tm.assert_produces_warning(warning_type): - df = parser.read_csv(StringIO(data)) + buf = StringIO(data) + + try: + with tm.assert_produces_warning(warning_type): + df = parser.read_csv(buf) + except AssertionError as err: + # 2021-02-21 this occasionally fails on the CI with an unexpected + # ResourceWarning that we have been unable to track down, + # see GH#38630 + if "ResourceError" not in str(err) or parser.engine != "python": + raise + + # Check the main assertion of the test before re-raising + assert df.a.dtype == object + + mark = pytest.mark.xfail( + reason="ResourceWarning for unclosed SSL Socket, GH#38630" + ) + request.node.add_marker(mark) + raise + assert df.a.dtype == object
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39964
2021-02-22T02:53:38Z
2021-02-22T22:57:17Z
2021-02-22T22:57:17Z
2021-02-22T23:10:48Z
ENH: NDArrayBackedExtensionArray swapaxes, delete-with-axis
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 57df9ed9ed2d7..ad0bf76b0556b 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -369,8 +369,16 @@ def where( res_values = np.where(mask, self._ndarray, value) return self._from_backing_data(res_values) - def delete(self: NDArrayBackedExtensionArrayT, loc) -> NDArrayBackedExtensionArrayT: - res_values = np.delete(self._ndarray, loc) + def delete( + self: NDArrayBackedExtensionArrayT, loc, axis: int = 0 + ) -> NDArrayBackedExtensionArrayT: + res_values = np.delete(self._ndarray, loc, axis=axis) + return self._from_backing_data(res_values) + + def swapaxes( + self: NDArrayBackedExtensionArrayT, axis1, axis2 + ) -> NDArrayBackedExtensionArrayT: + res_values = self._ndarray.swapaxes(axis1, axis2) return self._from_backing_data(res_values) # ------------------------------------------------------------------------ diff --git a/pandas/tests/extension/base/dim2.py b/pandas/tests/extension/base/dim2.py index c6455ce15533a..fbe2537e8a7bf 100644 --- a/pandas/tests/extension/base/dim2.py +++ b/pandas/tests/extension/base/dim2.py @@ -25,6 +25,26 @@ def maybe_xfail_masked_reductions(arr, request): class Dim2CompatTests(BaseExtensionTests): + def test_swapaxes(self, data): + arr2d = data.repeat(2).reshape(-1, 2) + + result = arr2d.swapaxes(0, 1) + expected = arr2d.T + self.assert_extension_array_equal(result, expected) + + def test_delete_2d(self, data): + arr2d = data.repeat(3).reshape(-1, 3) + + # axis = 0 + result = arr2d.delete(1, axis=0) + expected = data.delete(1).repeat(3).reshape(-1, 3) + self.assert_extension_array_equal(result, expected) + + # axis = 1 + result = arr2d.delete(1, axis=1) + expected = data.repeat(2).reshape(-1, 2) + self.assert_extension_array_equal(result, expected) + def test_take_2d(self, data): arr2d = data.reshape(-1, 1)
Sits on top of #39880
https://api.github.com/repos/pandas-dev/pandas/pulls/39963
2021-02-22T00:31:46Z
2021-02-25T13:40:45Z
2021-02-25T13:40:45Z
2021-02-25T14:55:41Z
REF: ensure _sanitize_column returns ArrayLike
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 916d4f9f2fd28..ff835eb32f6df 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -399,7 +399,9 @@ def __init__( # sanitize_array coerces np.nan to a string under certain versions # of numpy values = maybe_infer_to_datetimelike(values) - if not isinstance(values, (np.ndarray, ExtensionArray)): + if isinstance(values, np.ndarray): + values = sanitize_to_nanoseconds(values) + elif not isinstance(values, ExtensionArray): values = com.convert_to_list_like(values) # By convention, empty lists result in object dtype: @@ -409,9 +411,6 @@ def __init__( values = [values[idx] for idx in np.where(~null_mask)[0]] values = sanitize_array(values, None, dtype=sanitize_dtype) - else: - values = sanitize_to_nanoseconds(values) - if dtype.categories is None: try: codes, categories = factorize(values, sort=True) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 669bfe08d42b0..00cc1aeab336f 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1432,7 +1432,7 @@ def maybe_infer_to_datetimelike( if not len(v): return value - def try_datetime(v): + def try_datetime(v: np.ndarray) -> ArrayLike: # safe coerce to datetime64 try: # GH19671 @@ -1451,14 +1451,15 @@ def try_datetime(v): except (ValueError, TypeError): pass else: - return DatetimeIndex(values).tz_localize("UTC").tz_convert(tz=tz) + dti = DatetimeIndex(values).tz_localize("UTC").tz_convert(tz=tz) + return dti._data except TypeError: # e.g. <class 'numpy.timedelta64'> is not convertible to datetime pass return v.reshape(shape) - def try_timedelta(v): + def try_timedelta(v: np.ndarray) -> np.ndarray: # safe coerce to timedelta64 # will try first with a string & object conversion diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2d6cfff561aab..5b06059d4302c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4000,7 +4000,7 @@ def assign(self, **kwargs) -> DataFrame: data[k] = com.apply_if_callable(v, data) return data - def _sanitize_column(self, value): + def _sanitize_column(self, value) -> ArrayLike: """ Ensures new columns (which go into the BlockManager as new blocks) are always copied and converted into an array. @@ -4011,7 +4011,7 @@ def _sanitize_column(self, value): Returns ------- - numpy.ndarray + numpy.ndarray or ExtensionArray """ self._ensure_valid_index(value) @@ -4025,7 +4025,7 @@ def _sanitize_column(self, value): value = value.copy() value = sanitize_index(value, self.index) - elif isinstance(value, Index) or is_sequence(value): + elif is_sequence(value): # turn me into an ndarray value = sanitize_index(value, self.index) @@ -4035,7 +4035,7 @@ def _sanitize_column(self, value): else: value = com.asarray_tuplesafe(value) elif isinstance(value, Index): - value = value.copy(deep=True) + value = value.copy(deep=True)._values else: value = value.copy()
Part of making Block._maybe_coerce_values unnecessary
https://api.github.com/repos/pandas-dev/pandas/pulls/39962
2021-02-21T23:12:31Z
2021-02-22T13:21:29Z
2021-02-22T13:21:29Z
2021-02-22T15:32:29Z
REF: ensure soft_convert_objects returns ArrayLike
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 9f2c82d760785..dc8b36a3898b7 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1986,7 +1986,7 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, Parameters ---------- - values : ndarray + values : ndarray[object] Array of object elements to convert. na_values : set Set of values that should be interpreted as NaN. @@ -2007,7 +2007,8 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, Returns ------- - Array of converted object values to numerical ones. + np.ndarray + Array of converted object values to numerical ones. """ if len(values) == 0: return np.array([], dtype='i8') @@ -2159,7 +2160,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, Parameters ---------- - values : ndarray + values : ndarray[object] Array of object elements to convert. try_float : bool, default False If an array-like object contains only float or NaN values is @@ -2179,7 +2180,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, Returns ------- - Array of converted object values to more specific dtypes if applicable. + np.ndarray or ExtensionArray """ cdef: Py_ssize_t i, n @@ -2309,7 +2310,10 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, if seen.datetimetz_: if is_datetime_with_singletz_array(objects): from pandas import DatetimeIndex - return DatetimeIndex(objects) + dti = DatetimeIndex(objects) + + # unbox to DatetimeArray + return dti._data seen.object_ = True if not seen.object_: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 669bfe08d42b0..b80d985f219d5 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1234,7 +1234,7 @@ def soft_convert_objects( numeric: bool = True, timedelta: bool = True, copy: bool = True, -): +) -> ArrayLike: """ Try to coerce datetime, timedelta, and numeric object-dtype columns to inferred dtype. @@ -1249,7 +1249,7 @@ def soft_convert_objects( Returns ------- - np.ndarray + np.ndarray or ExtensionArray """ validate_bool_kwarg(datetime, "datetime") validate_bool_kwarg(numeric, "numeric") diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index efda1f8038cb7..d12be7f94822c 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -128,7 +128,6 @@ class Block(PandasObject): __slots__ = ["_mgr_locs", "values", "ndim"] is_numeric = False - is_float = False is_bool = False is_object = False is_extension = False @@ -1290,7 +1289,7 @@ def _interpolate( data = self.values if inplace else self.values.copy() # only deal with floats - if not self.is_float: + if self.dtype.kind != "f": if self.dtype.kind not in ["i", "u"]: return [self] data = data.astype(np.float64) @@ -1955,7 +1954,6 @@ def is_bool(self): class FloatBlock(NumericBlock): __slots__ = () - is_float = True def to_native_types( self, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs @@ -2144,7 +2142,6 @@ def to_native_types(self, na_rep="NaT", **kwargs): class DatetimeBlock(DatetimeLikeBlockMixin): __slots__ = () - is_datetime = True fill_value = np.datetime64("NaT", "ns") _dtype = fill_value.dtype _holder = DatetimeArray diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 8f18f87f2decc..a125f85efc8d3 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -39,7 +39,7 @@ def test_concat_copy(self): result = concat([df, df2, df3], axis=1, copy=False) for b in result._mgr.blocks: - if b.is_float: + if b.dtype.kind == "f": assert b.values.base is df._mgr.blocks[0].values.base elif b.dtype.kind in ["i", "u"]: assert b.values.base is df2._mgr.blocks[0].values.base @@ -50,7 +50,7 @@ def test_concat_copy(self): df4 = DataFrame(np.random.randn(4, 1)) result = concat([df, df2, df3, df4], axis=1, copy=False) for b in result._mgr.blocks: - if b.is_float: + if b.dtype.kind == "f": assert b.values.base is None elif b.dtype.kind in ["i", "u"]: assert b.values.base is df2._mgr.blocks[0].values.base
moves towards making _maybe_coerce_values unnecessary (perf!) Also removes is_datetime and is_float attrs from Block, unrelated but ended up in the same branch.
https://api.github.com/repos/pandas-dev/pandas/pulls/39961
2021-02-21T22:36:45Z
2021-02-22T13:22:14Z
2021-02-22T13:22:14Z
2021-02-22T15:33:17Z
CLN: Remove some duplicated tests and parametrize
diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index d1f1db741509f..21ea6fbd2e3c6 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -498,122 +498,71 @@ def test_floating_index_doc_example(self): assert s.loc[3] == 2 assert s.iloc[3] == 3 - def test_floating_misc(self): + def test_floating_misc(self, indexer_sl): # related 236 # scalar/slicing of a float index s = Series(np.arange(5), index=np.arange(5) * 2.5, dtype=np.int64) # label based slicing - result1 = s[1.0:3.0] - result2 = s.loc[1.0:3.0] - result3 = s.loc[1.0:3.0] - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) + result = indexer_sl(s)[1.0:3.0] + expected = Series(1, index=[2.5]) + tm.assert_series_equal(result, expected) # exact indexing when found - result1 = s[5.0] - result2 = s.loc[5.0] - result3 = s.loc[5.0] - assert result1 == result2 - assert result1 == result3 - result1 = s[5] - result2 = s.loc[5] - result3 = s.loc[5] - assert result1 == result2 - assert result1 == result3 + result = indexer_sl(s)[5.0] + assert result == 2 - assert s[5.0] == s[5] + result = indexer_sl(s)[5] + assert result == 2 # value not found (and no fallbacking at all) # scalar integers with pytest.raises(KeyError, match=r"^4$"): - s.loc[4] - with pytest.raises(KeyError, match=r"^4$"): - s.loc[4] - with pytest.raises(KeyError, match=r"^4$"): - s[4] + indexer_sl(s)[4] # fancy floats/integers create the correct entry (as nan) # fancy tests expected = Series([2, 0], index=Float64Index([5.0, 0.0])) for fancy_idx in [[5.0, 0.0], np.array([5.0, 0.0])]: # float - tm.assert_series_equal(s[fancy_idx], expected) - tm.assert_series_equal(s.loc[fancy_idx], expected) - tm.assert_series_equal(s.loc[fancy_idx], expected) + tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected) expected = Series([2, 0], index=Index([5, 0], dtype="int64")) for fancy_idx in [[5, 0], np.array([5, 0])]: # int - tm.assert_series_equal(s[fancy_idx], expected) - tm.assert_series_equal(s.loc[fancy_idx], expected) - tm.assert_series_equal(s.loc[fancy_idx], expected) + tm.assert_series_equal(indexer_sl(s)[fancy_idx], expected) # all should return the same as we are slicing 'the same' - result1 = s.loc[2:5] - result2 = s.loc[2.0:5.0] - result3 = s.loc[2.0:5] - result4 = s.loc[2.1:5] - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) - tm.assert_series_equal(result1, result4) - - # previously this did fallback indexing - result1 = s[2:5] - result2 = s[2.0:5.0] - result3 = s[2.0:5] - result4 = s[2.1:5] + result1 = indexer_sl(s)[2:5] + result2 = indexer_sl(s)[2.0:5.0] + result3 = indexer_sl(s)[2.0:5] + result4 = indexer_sl(s)[2.1:5] tm.assert_series_equal(result1, result2) tm.assert_series_equal(result1, result3) tm.assert_series_equal(result1, result4) - result1 = s.loc[2:5] - result2 = s.loc[2.0:5.0] - result3 = s.loc[2.0:5] - result4 = s.loc[2.1:5] - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) - tm.assert_series_equal(result1, result4) + expected = Series([1, 2], index=[2.5, 5.0]) + result = indexer_sl(s)[2:5] - # combined test - result1 = s.loc[2:5] - result2 = s.loc[2:5] - result3 = s[2:5] - - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) + tm.assert_series_equal(result, expected) # list selection - result1 = s[[0.0, 5, 10]] - result2 = s.loc[[0.0, 5, 10]] - result3 = s.loc[[0.0, 5, 10]] - result4 = s.iloc[[0, 2, 4]] + result1 = indexer_sl(s)[[0.0, 5, 10]] + result2 = s.iloc[[0, 2, 4]] tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) - tm.assert_series_equal(result1, result4) with pytest.raises(KeyError, match="with any missing labels"): - s[[1.6, 5, 10]] - with pytest.raises(KeyError, match="with any missing labels"): - s.loc[[1.6, 5, 10]] + indexer_sl(s)[[1.6, 5, 10]] with pytest.raises(KeyError, match="with any missing labels"): - s[[0, 1, 2]] - with pytest.raises(KeyError, match="with any missing labels"): - s.loc[[0, 1, 2]] + indexer_sl(s)[[0, 1, 2]] - result1 = s.loc[[2.5, 5]] - result2 = s.loc[[2.5, 5]] - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, Series([1, 2], index=[2.5, 5.0])) + result = indexer_sl(s)[[2.5, 5]] + tm.assert_series_equal(result, Series([1, 2], index=[2.5, 5.0])) - result1 = s[[2.5]] - result2 = s.loc[[2.5]] - result3 = s.loc[[2.5]] - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) - tm.assert_series_equal(result1, Series([1], index=[2.5])) + result = indexer_sl(s)[[2.5]] + tm.assert_series_equal(result, Series([1], index=[2.5])) def test_floating_tuples(self): # see gh-13509 diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index d5e5cabc93b66..3b3ea1227ba99 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -35,28 +35,11 @@ class TestiLoc(Base): - def test_iloc_getitem_int(self): - # integer + @pytest.mark.parametrize("key", [2, -1, [0, 1, 2]]) + def test_iloc_getitem_int_and_list_int(self, key): self.check_result( "iloc", - 2, - typs=["labels", "mixed", "ts", "floats", "empty"], - fails=IndexError, - ) - - def test_iloc_getitem_neg_int(self): - # neg integer - self.check_result( - "iloc", - -1, - typs=["labels", "mixed", "ts", "floats", "empty"], - fails=IndexError, - ) - - def test_iloc_getitem_list_int(self): - self.check_result( - "iloc", - [0, 1, 2], + key, typs=["labels", "mixed", "ts", "floats", "empty"], fails=IndexError, ) @@ -371,7 +354,7 @@ def test_iloc_getitem_bool_diff_len(self, index): s = Series([1, 2, 3]) msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}" with pytest.raises(IndexError, match=msg): - _ = s.iloc[index] + s.iloc[index] def test_iloc_getitem_slice(self): df = DataFrame( diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index aec12f4cedcea..34f7ec9418028 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -266,14 +266,11 @@ def test_dups_fancy_indexing_only_missing_label(self): # ToDo: check_index_type can be True after GH 11497 - def test_dups_fancy_indexing_missing_label(self): + @pytest.mark.parametrize("vals", [[0, 1, 2], list("abc")]) + def test_dups_fancy_indexing_missing_label(self, vals): # GH 4619; duplicate indexer with missing label - df = DataFrame({"A": [0, 1, 2]}) - with pytest.raises(KeyError, match="with any missing labels"): - df.loc[[0, 8, 0]] - - df = DataFrame({"A": list("abc")}) + df = DataFrame({"A": vals}) with pytest.raises(KeyError, match="with any missing labels"): df.loc[[0, 8, 0]] @@ -455,9 +452,6 @@ def test_multi_assign(self): df2.loc[mask, cols] = dft.loc[mask, cols] tm.assert_frame_equal(df2, expected) - df2.loc[mask, cols] = dft.loc[mask, cols] - tm.assert_frame_equal(df2, expected) - # with an ndarray on rhs # coerces to float64 because values has float64 dtype # GH 14001 @@ -472,8 +466,6 @@ def test_multi_assign(self): df2 = df.copy() df2.loc[mask, cols] = dft.loc[mask, cols].values tm.assert_frame_equal(df2, expected) - df2.loc[mask, cols] = dft.loc[mask, cols].values - tm.assert_frame_equal(df2, expected) def test_multi_assign_broadcasting_rhs(self): # broadcasting on the rhs is required diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index c98666b38b8b8..829bba5f2930d 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -266,7 +266,7 @@ def test_loc_getitem_bool_diff_len(self, index): s = Series([1, 2, 3]) msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}" with pytest.raises(IndexError, match=msg): - _ = s.loc[index] + s.loc[index] def test_loc_getitem_int_slice(self): # TODO: test something here? @@ -408,7 +408,11 @@ def frame_for_consistency(self): } ) - def test_loc_setitem_consistency(self, frame_for_consistency): + @pytest.mark.parametrize( + "val", + [0, np.array(0, dtype=np.int64), np.array([0, 0, 0, 0, 0], dtype=np.int64)], + ) + def test_loc_setitem_consistency(self, frame_for_consistency, val): # GH 6149 # coerce similarly for setitem and loc when rows have a null-slice expected = DataFrame( @@ -418,15 +422,7 @@ def test_loc_setitem_consistency(self, frame_for_consistency): } ) df = frame_for_consistency.copy() - df.loc[:, "date"] = 0 - tm.assert_frame_equal(df, expected) - - df = frame_for_consistency.copy() - df.loc[:, "date"] = np.array(0, dtype=np.int64) - tm.assert_frame_equal(df, expected) - - df = frame_for_consistency.copy() - df.loc[:, "date"] = np.array([0, 0, 0, 0, 0], dtype=np.int64) + df.loc[:, "date"] = val tm.assert_frame_equal(df, expected) def test_loc_setitem_consistency_dt64_to_str(self, frame_for_consistency): @@ -554,8 +550,6 @@ def test_loc_modify_datetime(self): def test_loc_setitem_frame(self): df = DataFrame(np.random.randn(4, 4), index=list("abcd"), columns=list("ABCD")) - result = df.iloc[0, 0] - df.loc["a", "A"] = 1 result = df.loc["a", "A"] assert result == 1 @@ -762,7 +756,7 @@ def test_loc_coercion(self): result = df.iloc[3:] tm.assert_series_equal(result.dtypes, expected) - def test_setitem_new_key_tz(self): + def test_setitem_new_key_tz(self, indexer_sl): # GH#12862 should not raise on assigning the second value vals = [ pd.to_datetime(42).tz_localize("UTC"), @@ -771,14 +765,8 @@ def test_setitem_new_key_tz(self): expected = Series(vals, index=["foo", "bar"]) ser = Series(dtype=object) - ser["foo"] = vals[0] - ser["bar"] = vals[1] - - tm.assert_series_equal(ser, expected) - - ser = Series(dtype=object) - ser.loc["foo"] = vals[0] - ser.loc["bar"] = vals[1] + indexer_sl(ser)["foo"] = vals[0] + indexer_sl(ser)["bar"] = vals[1] tm.assert_series_equal(ser, expected) @@ -1104,7 +1092,7 @@ def test_loc_getitem_timedelta_0seconds(self): df.index = timedelta_range(start="0s", periods=10, freq="s") expected = df.loc[Timedelta("0s") :, :] result = df.loc["0s":, :] - tm.assert_frame_equal(expected, result) + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "val,expected", [(2 ** 63 - 1, Series([1])), (2 ** 63, Series([2]))] @@ -1120,12 +1108,12 @@ def test_loc_getitem_uint64_scalar(self, val, expected): def test_loc_setitem_int_label_with_float64index(self): # note labels are floats ser = Series(["a", "b", "c"], index=[0, 0.5, 1]) - tmp = ser.copy() + expected = ser.copy() ser.loc[1] = "zoo" - tmp.iloc[2] = "zoo" + expected.iloc[2] = "zoo" - tm.assert_series_equal(ser, tmp) + tm.assert_series_equal(ser, expected) @pytest.mark.parametrize( "indexer, expected", @@ -1363,42 +1351,18 @@ def test_frame_loc_getitem_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] - tm.assert_frame_equal(res, df.loc[df.A > 2]) - - 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] - tm.assert_frame_equal(res, df.loc[df.A > 2]) - - res = df.loc[lambda x: x.B == "b", :] - tm.assert_frame_equal(res, df.loc[df.B == "b", :]) - res = df.loc[lambda x: x.B == "b", :] tm.assert_frame_equal(res, df.loc[df.B == "b", :]) res = df.loc[lambda x: x.A > 2, lambda x: x.columns == "B"] tm.assert_frame_equal(res, df.loc[df.A > 2, [False, True, False]]) - res = df.loc[lambda x: x.A > 2, lambda x: x.columns == "B"] - tm.assert_frame_equal(res, df.loc[df.A > 2, [False, True, False]]) - - res = df.loc[lambda x: x.A > 2, lambda x: "B"] - tm.assert_series_equal(res, df.loc[df.A > 2, "B"]) - res = df.loc[lambda x: x.A > 2, lambda x: "B"] tm.assert_series_equal(res, df.loc[df.A > 2, "B"]) res = df.loc[lambda x: x.A > 2, lambda x: ["A", "B"]] tm.assert_frame_equal(res, df.loc[df.A > 2, ["A", "B"]]) - res = df.loc[lambda x: x.A > 2, lambda x: ["A", "B"]] - tm.assert_frame_equal(res, df.loc[df.A > 2, ["A", "B"]]) - - res = df.loc[lambda x: x.A == 2, lambda x: ["A", "B"]] - tm.assert_frame_equal(res, df.loc[df.A == 2, ["A", "B"]]) - res = df.loc[lambda x: x.A == 2, lambda x: ["A", "B"]] tm.assert_frame_equal(res, df.loc[df.A == 2, ["A", "B"]]) @@ -1406,9 +1370,6 @@ def test_frame_loc_getitem_callable(self): res = df.loc[lambda x: 1, lambda x: "A"] assert res == df.loc[1, "A"] - res = df.loc[lambda x: 1, lambda x: "A"] - assert res == df.loc[1, "A"] - def test_frame_loc_getitem_callable_mixture(self): # GH#11485 df = DataFrame({"A": [1, 2, 3, 4], "B": list("aabb"), "C": [1, 2, 3, 4]}) @@ -1416,21 +1377,12 @@ def test_frame_loc_getitem_callable_mixture(self): res = df.loc[lambda x: x.A > 2, ["A", "B"]] tm.assert_frame_equal(res, df.loc[df.A > 2, ["A", "B"]]) - res = df.loc[lambda x: x.A > 2, ["A", "B"]] - tm.assert_frame_equal(res, df.loc[df.A > 2, ["A", "B"]]) - - res = df.loc[[2, 3], lambda x: ["A", "B"]] - tm.assert_frame_equal(res, df.loc[[2, 3], ["A", "B"]]) - res = df.loc[[2, 3], lambda x: ["A", "B"]] tm.assert_frame_equal(res, df.loc[[2, 3], ["A", "B"]]) res = df.loc[3, lambda x: ["A", "B"]] tm.assert_series_equal(res, df.loc[3, ["A", "B"]]) - res = df.loc[3, lambda x: ["A", "B"]] - tm.assert_series_equal(res, df.loc[3, ["A", "B"]]) - def test_frame_loc_getitem_callable_labels(self): # GH#11485 df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD")) @@ -1439,9 +1391,6 @@ def test_frame_loc_getitem_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"]] - tm.assert_frame_equal(res, df.loc[["A", "C"]]) - res = df.loc[lambda x: ["A", "C"], :] tm.assert_frame_equal(res, df.loc[["A", "C"], :]) @@ -1611,18 +1560,16 @@ def test_loc_getitem_label_slice_across_dst(self): expected = 2 assert result == expected - def test_loc_getitem_label_slice_period(self): - ix = pd.period_range(start="2017-01-01", end="2018-01-01", freq="M") - ser = ix.to_series() - result = ser.loc[: ix[-2]] - expected = ser.iloc[:-1] - - tm.assert_series_equal(result, expected) - - def test_loc_getitem_label_slice_timedelta64(self): - ix = timedelta_range(start="1 day", end="2 days", freq="1H") - ser = ix.to_series() - result = ser.loc[: ix[-2]] + @pytest.mark.parametrize( + "index", + [ + pd.period_range(start="2017-01-01", end="2018-01-01", freq="M"), + timedelta_range(start="1 day", end="2 days", freq="1H"), + ], + ) + def test_loc_getitem_label_slice_period_timedelta(self, index): + ser = index.to_series() + result = ser.loc[: index[-2]] expected = ser.iloc[:-1] tm.assert_series_equal(result, expected) @@ -1716,23 +1663,13 @@ def test_loc_setitem_bool_mask_timedeltaindex(self): ) tm.assert_frame_equal(expected, result) - def test_loc_setitem_mask_with_datetimeindex_tz(self): + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_loc_setitem_mask_with_datetimeindex_tz(self, tz): # GH#16889 # support .loc with alignment and tz-aware DatetimeIndex mask = np.array([True, False, True, False]) - idx = date_range("20010101", periods=4, tz="UTC") - df = DataFrame({"a": np.arange(4)}, index=idx).astype("float64") - - result = df.copy() - result.loc[mask, :] = df.loc[mask, :] - tm.assert_frame_equal(result, df) - - result = df.copy() - result.loc[mask] = df.loc[mask] - tm.assert_frame_equal(result, df) - - idx = date_range("20010101", periods=4) + idx = date_range("20010101", periods=4, tz=tz) df = DataFrame({"a": np.arange(4)}, index=idx).astype("float64") result = df.copy()
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them There were a few duplicates from the ix removal
https://api.github.com/repos/pandas-dev/pandas/pulls/39960
2021-02-21T20:51:25Z
2021-02-22T22:30:49Z
2021-02-22T22:30:48Z
2021-02-22T23:07:09Z
TYP: maybe_cast_to_datetime
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index dd75473da6d78..1172fd25de3e4 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -521,6 +521,9 @@ def sanitize_array( subarr = construct_1d_arraylike_from_scalar(data, len(index), dtype) else: + # realize e.g. generators + # TODO: non-standard array-likes we can convert to ndarray more efficiently? + data = list(data) subarr = _try_cast(data, dtype, copy, raise_cast_failure) subarr = _sanitize_ndim(subarr, data, dtype, index) @@ -594,13 +597,18 @@ def _maybe_repeat(arr: ArrayLike, index: Optional[Index]) -> ArrayLike: return arr -def _try_cast(arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bool): +def _try_cast( + arr: Union[list, np.ndarray], + dtype: Optional[DtypeObj], + copy: bool, + raise_cast_failure: bool, +) -> ArrayLike: """ Convert input to numpy ndarray and optionally cast to a given dtype. Parameters ---------- - arr : ndarray, list, tuple, iterator (catchall) + arr : ndarray or list Excludes: ExtensionArray, Series, Index. dtype : np.dtype, ExtensionDtype or None copy : bool @@ -608,6 +616,10 @@ def _try_cast(arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bo raise_cast_failure : bool If True, and if a dtype is specified, raise errors during casting. Otherwise an object array is returned. + + Returns + ------- + np.ndarray or ExtensionArray """ # perf shortcut as this is the most common case if ( diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 3a6830467ab50..531d784925e9d 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1422,7 +1422,7 @@ def maybe_infer_to_datetimelike( v = np.array(v, copy=False) # we only care about object dtypes - if not is_object_dtype(v): + if not is_object_dtype(v.dtype): return value shape = v.shape @@ -1499,7 +1499,9 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: return value -def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]): +def maybe_cast_to_datetime( + value: Union[ExtensionArray, np.ndarray, list], dtype: Optional[DtypeObj] +) -> Union[ExtensionArray, np.ndarray, list]: """ try to cast the array/value to a datetimelike dtype, converting float nan to iNaT @@ -1563,26 +1565,28 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]): try: if is_datetime64: - value = to_datetime(value, errors="raise") + dti = to_datetime(value, errors="raise") # GH 25843: Remove tz information since the dtype # didn't specify one - if value.tz is not None: - value = value.tz_localize(None) - value = value._values + if dti.tz is not None: + dti = dti.tz_localize(None) + value = dti._values elif is_datetime64tz: # The string check can be removed once issue #13712 # is solved. String data that is passed with a # datetime64tz is assumed to be naive which should # be localized to the timezone. is_dt_string = is_string_dtype(value.dtype) - value = to_datetime(value, errors="raise").array - if is_dt_string: + dta = to_datetime(value, errors="raise").array + if dta.tz is not None: + value = dta.astype(dtype, copy=False) + elif is_dt_string: # Strings here are naive, so directly localize - value = value.tz_localize(dtype.tz) + value = dta.tz_localize(dtype.tz) else: # Numeric values are UTC at this point, # so localize and convert - value = value.tz_localize("UTC").tz_convert(dtype.tz) + value = dta.tz_localize("UTC").tz_convert(dtype.tz) elif is_timedelta64: value = to_timedelta(value, errors="raise")._values except OutOfBoundsDatetime: @@ -1595,6 +1599,8 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]): getattr(value, "dtype", None) ) and not is_datetime64_dtype(dtype): if is_object_dtype(dtype): + value = cast(np.ndarray, value) + if value.dtype != DT64NS_DTYPE: value = value.astype(DT64NS_DTYPE) ints = np.asarray(value).view("i8") @@ -1603,25 +1609,20 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]): # we have a non-castable dtype that was passed raise TypeError(f"Cannot cast datetime64 to {dtype}") - else: - - is_array = isinstance(value, np.ndarray) - - # catch a datetime/timedelta that is not of ns variety - # and no coercion specified - if is_array and value.dtype.kind in ["M", "m"]: + elif isinstance(value, np.ndarray): + if value.dtype.kind in ["M", "m"]: + # catch a datetime/timedelta that is not of ns variety + # and no coercion specified value = sanitize_to_nanoseconds(value) + elif value.dtype == object: + value = maybe_infer_to_datetimelike(value) + + else: # only do this if we have an array and the dtype of the array is not # setup already we are not an integer/object, so don't bother with this # conversion - elif not ( - is_array - and not ( - issubclass(value.dtype.type, np.integer) or value.dtype == np.object_ - ) - ): - value = maybe_infer_to_datetimelike(value) + value = maybe_infer_to_datetimelike(value) return value @@ -1835,7 +1836,9 @@ def construct_1d_ndarray_preserving_na( return subarr -def maybe_cast_to_integer_array(arr, dtype: Dtype, copy: bool = False): +def maybe_cast_to_integer_array( + arr: Union[list, np.ndarray], dtype: np.dtype, copy: bool = False +): """ Takes any dtype and returns the casted version, raising for when data is incompatible with integer/unsigned integer dtypes. @@ -1844,9 +1847,9 @@ def maybe_cast_to_integer_array(arr, dtype: Dtype, copy: bool = False): Parameters ---------- - arr : array-like + arr : np.ndarray or list The array to cast. - dtype : str, np.dtype + dtype : np.dtype The integer dtype to cast the array to. copy: bool, default False Whether to make a copy of the array before returning. @@ -1880,7 +1883,7 @@ def maybe_cast_to_integer_array(arr, dtype: Dtype, copy: bool = False): assert is_integer_dtype(dtype) try: - if not hasattr(arr, "astype"): + if not isinstance(arr, np.ndarray): casted = np.array(arr, dtype=dtype, copy=copy) else: casted = arr.astype(dtype, copy=copy)
Underlying motivation is to make Block._maybe_coerce_values unnecessary, which will improve `__init__` perf
https://api.github.com/repos/pandas-dev/pandas/pulls/39959
2021-02-21T17:49:53Z
2021-02-24T00:38:35Z
2021-02-24T00:38:35Z
2021-02-24T02:07:34Z
DOC: remove unnecessary index.html from the URL
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 67c74f9a04618..d7c1ca8bca598 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -29,7 +29,7 @@ The pandas I/O API is a set of top level ``reader`` functions accessed like binary;`Feather Format <https://github.com/wesm/feather>`__;:ref:`read_feather<io.feather>`;:ref:`to_feather<io.feather>` binary;`Parquet Format <https://parquet.apache.org/>`__;:ref:`read_parquet<io.parquet>`;:ref:`to_parquet<io.parquet>` binary;`ORC Format <https://orc.apache.org/>`__;:ref:`read_orc<io.orc>`; - binary;`Msgpack <https://msgpack.org/index.html>`__;:ref:`read_msgpack<io.msgpack>`;:ref:`to_msgpack<io.msgpack>` + binary;`Msgpack <https://msgpack.org/>`__;:ref:`read_msgpack<io.msgpack>`;:ref:`to_msgpack<io.msgpack>` binary;`Stata <https://en.wikipedia.org/wiki/Stata>`__;:ref:`read_stata<io.stata_reader>`;:ref:`to_stata<io.stata_writer>` binary;`SAS <https://en.wikipedia.org/wiki/SAS_(software)>`__;:ref:`read_sas<io.sas_reader>`; binary;`SPSS <https://en.wikipedia.org/wiki/SPSS>`__;:ref:`read_spss<io.spss_reader>`;
remove unnecessary index.html from the URL - [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39958
2021-02-21T17:07:32Z
2021-02-24T00:39:05Z
2021-02-24T00:39:05Z
2021-02-24T01:03:26Z
REF: Move transform into apply
diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 744a1ffa5fea1..0a4e03fa97402 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -20,28 +20,19 @@ Sequence, Tuple, Union, - cast, ) from pandas._typing import ( AggFuncType, - AggFuncTypeBase, - AggFuncTypeDict, - Axis, FrameOrSeries, - FrameOrSeriesUnion, ) from pandas.core.dtypes.common import ( is_dict_like, is_list_like, ) -from pandas.core.dtypes.generic import ( - ABCDataFrame, - ABCSeries, -) +from pandas.core.dtypes.generic import ABCSeries -from pandas.core.algorithms import safe_sort from pandas.core.base import SpecificationError import pandas.core.common as com from pandas.core.indexes.api import Index @@ -405,134 +396,3 @@ def validate_func_kwargs( no_arg_message = "Must provide 'func' or named aggregation **kwargs." raise TypeError(no_arg_message) return columns, func - - -def transform( - obj: FrameOrSeries, func: AggFuncType, axis: Axis, *args, **kwargs -) -> FrameOrSeriesUnion: - """ - Transform a DataFrame or Series - - Parameters - ---------- - obj : DataFrame or Series - Object to compute the transform on. - func : string, function, list, or dictionary - Function(s) to compute the transform with. - axis : {0 or 'index', 1 or 'columns'} - Axis along which the function is applied: - - * 0 or 'index': apply function to each column. - * 1 or 'columns': apply function to each row. - - Returns - ------- - DataFrame or Series - Result of applying ``func`` along the given axis of the - Series or DataFrame. - - Raises - ------ - ValueError - If the transform function fails or does not transform. - """ - is_series = obj.ndim == 1 - - if obj._get_axis_number(axis) == 1: - assert not is_series - return transform(obj.T, func, 0, *args, **kwargs).T - - if is_list_like(func) and not is_dict_like(func): - func = cast(List[AggFuncTypeBase], func) - # Convert func equivalent dict - if is_series: - func = {com.get_callable_name(v) or v: v for v in func} - else: - func = {col: func for col in obj} - - if is_dict_like(func): - func = cast(AggFuncTypeDict, func) - return transform_dict_like(obj, func, *args, **kwargs) - - # func is either str or callable - func = cast(AggFuncTypeBase, func) - try: - result = transform_str_or_callable(obj, func, *args, **kwargs) - except Exception: - raise ValueError("Transform function failed") - - # Functions that transform may return empty Series/DataFrame - # when the dtype is not appropriate - if isinstance(result, (ABCSeries, ABCDataFrame)) and result.empty and not obj.empty: - raise ValueError("Transform function failed") - if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals( - obj.index - ): - raise ValueError("Function did not transform") - - return result - - -def transform_dict_like( - obj: FrameOrSeries, - func: AggFuncTypeDict, - *args, - **kwargs, -): - """ - Compute transform in the case of a dict-like func - """ - from pandas.core.reshape.concat import concat - - if len(func) == 0: - raise ValueError("No transform functions were provided") - - if obj.ndim != 1: - # Check for missing columns on a frame - cols = set(func.keys()) - set(obj.columns) - if len(cols) > 0: - cols_sorted = list(safe_sort(list(cols))) - raise SpecificationError(f"Column(s) {cols_sorted} do not exist") - - # Can't use func.values(); wouldn't work for a Series - if any(is_dict_like(v) for _, v in func.items()): - # GH 15931 - deprecation of renaming keys - raise SpecificationError("nested renamer is not supported") - - results: Dict[Hashable, FrameOrSeriesUnion] = {} - for name, how in func.items(): - colg = obj._gotitem(name, ndim=1) - try: - results[name] = transform(colg, how, 0, *args, **kwargs) - except Exception as err: - if str(err) in { - "Function did not transform", - "No transform functions were provided", - }: - raise err - - # combine results - if not results: - raise ValueError("Transform function failed") - return concat(results, axis=1) - - -def transform_str_or_callable( - obj: FrameOrSeries, func: AggFuncTypeBase, *args, **kwargs -) -> FrameOrSeriesUnion: - """ - Compute transform in the case of a string or callable func - """ - if isinstance(func, str): - return obj._try_aggregate_string_function(func, *args, **kwargs) - - if not args and not kwargs: - f = obj._get_cython_func(func) - if f: - return getattr(obj, f)() - - # Two possible ways to use a UDF - apply or call directly - try: - return obj.apply(func, args=args, **kwargs) - except Exception: - return func(obj, *args, **kwargs) diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b41c432dff172..e43e9dadda033 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -6,6 +6,7 @@ TYPE_CHECKING, Any, Dict, + Hashable, Iterator, List, Optional, @@ -151,6 +152,7 @@ def f(x): else: f = func + self.orig_f: AggFuncType = func self.f: AggFuncType = f @property @@ -197,6 +199,131 @@ def agg(self) -> Optional[FrameOrSeriesUnion]: # caller can react return None + def transform(self) -> FrameOrSeriesUnion: + """ + Transform a DataFrame or Series. + + Returns + ------- + DataFrame or Series + Result of applying ``func`` along the given axis of the + Series or DataFrame. + + Raises + ------ + ValueError + If the transform function fails or does not transform. + """ + obj = self.obj + func = self.orig_f + axis = self.axis + args = self.args + kwargs = self.kwargs + + is_series = obj.ndim == 1 + + if obj._get_axis_number(axis) == 1: + assert not is_series + return obj.T.transform(func, 0, *args, **kwargs).T + + if is_list_like(func) and not is_dict_like(func): + func = cast(List[AggFuncTypeBase], func) + # Convert func equivalent dict + if is_series: + func = {com.get_callable_name(v) or v: v for v in func} + else: + func = {col: func for col in obj} + + if is_dict_like(func): + func = cast(AggFuncTypeDict, func) + return self.transform_dict_like(func) + + # func is either str or callable + func = cast(AggFuncTypeBase, func) + try: + result = self.transform_str_or_callable(func) + except Exception: + raise ValueError("Transform function failed") + + # Functions that transform may return empty Series/DataFrame + # when the dtype is not appropriate + if ( + isinstance(result, (ABCSeries, ABCDataFrame)) + and result.empty + and not obj.empty + ): + raise ValueError("Transform function failed") + if not isinstance(result, (ABCSeries, ABCDataFrame)) or not result.index.equals( + obj.index + ): + raise ValueError("Function did not transform") + + return result + + def transform_dict_like(self, func): + """ + Compute transform in the case of a dict-like func + """ + from pandas.core.reshape.concat import concat + + obj = self.obj + args = self.args + kwargs = self.kwargs + + if len(func) == 0: + raise ValueError("No transform functions were provided") + + if obj.ndim != 1: + # Check for missing columns on a frame + cols = set(func.keys()) - set(obj.columns) + if len(cols) > 0: + cols_sorted = list(safe_sort(list(cols))) + raise SpecificationError(f"Column(s) {cols_sorted} do not exist") + + # Can't use func.values(); wouldn't work for a Series + if any(is_dict_like(v) for _, v in func.items()): + # GH 15931 - deprecation of renaming keys + raise SpecificationError("nested renamer is not supported") + + results: Dict[Hashable, FrameOrSeriesUnion] = {} + for name, how in func.items(): + colg = obj._gotitem(name, ndim=1) + try: + results[name] = colg.transform(how, 0, *args, **kwargs) + except Exception as err: + if str(err) in { + "Function did not transform", + "No transform functions were provided", + }: + raise err + + # combine results + if not results: + raise ValueError("Transform function failed") + return concat(results, axis=1) + + def transform_str_or_callable(self, func) -> FrameOrSeriesUnion: + """ + Compute transform in the case of a string or callable func + """ + obj = self.obj + args = self.args + kwargs = self.kwargs + + if isinstance(func, str): + return obj._try_aggregate_string_function(func, *args, **kwargs) + + if not args and not kwargs: + f = obj._get_cython_func(func) + if f: + return getattr(obj, f)() + + # Two possible ways to use a UDF - apply or call directly + try: + return obj.apply(func, args=args, **kwargs) + except Exception: + return func(obj, *args, **kwargs) + def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion: """ Compute aggregation in the case of a list-like argument. @@ -901,6 +1028,9 @@ def __init__( def apply(self): raise NotImplementedError + def transform(self): + raise NotImplementedError + class ResamplerWindowApply(Apply): axis = 0 @@ -924,3 +1054,6 @@ def __init__( def apply(self): raise NotImplementedError + + def transform(self): + raise NotImplementedError diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3fe330f659513..070f3dae7ae1c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -139,7 +139,6 @@ from pandas.core.aggregation import ( reconstruct_func, relabel_result, - transform, ) from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ExtensionArray @@ -7786,7 +7785,10 @@ def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): def transform( self, func: AggFuncType, axis: Axis = 0, *args, **kwargs ) -> DataFrame: - result = transform(self, func, axis, *args, **kwargs) + from pandas.core.apply import frame_apply + + op = frame_apply(self, func=func, axis=axis, args=args, kwargs=kwargs) + result = op.transform() assert isinstance(result, DataFrame) return result diff --git a/pandas/core/series.py b/pandas/core/series.py index cbb66918a661b..c2c0f0384ed71 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -94,7 +94,6 @@ ops, ) from pandas.core.accessor import CachedAccessor -from pandas.core.aggregation import transform from pandas.core.apply import series_apply from pandas.core.arrays import ExtensionArray from pandas.core.arrays.categorical import CategoricalAccessor @@ -4035,7 +4034,10 @@ def aggregate(self, func=None, axis=0, *args, **kwargs): def transform( self, func: AggFuncType, axis: Axis = 0, *args, **kwargs ) -> FrameOrSeriesUnion: - return transform(self, func, axis, *args, **kwargs) + # Validate axis argument + self._get_axis_number(axis) + result = series_apply(self, func=func, args=args, kwargs=kwargs).transform() + return result def apply( self,
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Cleanups and consolidations to follow.
https://api.github.com/repos/pandas-dev/pandas/pulls/39957
2021-02-21T13:53:51Z
2021-02-21T17:33:33Z
2021-02-21T17:33:33Z
2021-02-21T17:38:02Z
REF: Move the rest of DataFrame.agg into apply
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b41c432dff172..4a96f2d593510 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -151,6 +151,7 @@ def f(x): else: f = func + self.orig_f: AggFuncType = func self.f: AggFuncType = f @property @@ -527,6 +528,35 @@ def apply(self) -> FrameOrSeriesUnion: return self.apply_standard() + def agg(self): + obj = self.obj + axis = self.axis + + # TODO: Avoid having to change state + self.obj = self.obj if self.axis == 0 else self.obj.T + self.axis = 0 + + result = None + try: + result = super().agg() + except TypeError as err: + exc = TypeError( + "DataFrame constructor called with " + f"incompatible data and dtype: {err}" + ) + raise exc from err + finally: + self.obj = obj + self.axis = axis + + if axis == 1: + result = result.T if result is not None else result + + if result is None: + result = self.obj.apply(self.orig_f, axis, args=self.args, **self.kwargs) + + return result + def apply_empty_result(self): """ we have an empty result; at least 1 axis is 0 diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3fe330f659513..c31eb3704c77d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7727,21 +7727,14 @@ def _gotitem( examples=_agg_examples_doc, ) def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): + from pandas.core.apply import frame_apply + axis = self._get_axis_number(axis) relabeling, func, columns, order = reconstruct_func(func, **kwargs) - result = None - try: - result = self._aggregate(func, axis, *args, **kwargs) - except TypeError as err: - exc = TypeError( - "DataFrame constructor called with " - f"incompatible data and dtype: {err}" - ) - raise exc from err - if result is None: - return self.apply(func, axis=axis, args=args, **kwargs) + op = frame_apply(self, func=func, axis=axis, args=args, kwargs=kwargs) + result = op.agg() if relabeling: # This is to keep the order to columns occurrence unchanged, and also @@ -7757,25 +7750,6 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): return result - def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): - from pandas.core.apply import frame_apply - - op = frame_apply( - self if axis == 0 else self.T, - func=arg, - axis=0, - args=args, - kwargs=kwargs, - ) - result = op.agg() - - if axis == 1: - # NDFrame.aggregate returns a tuple, and we need to transpose - # only result - result = result.T if result is not None else result - - return result - agg = aggregate @doc(
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run
https://api.github.com/repos/pandas-dev/pandas/pulls/39955
2021-02-21T13:16:53Z
2021-02-21T17:32:44Z
2021-02-21T17:32:44Z
2021-02-21T17:37:43Z
REF: Move the rest of Series.agg into apply
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b41c432dff172..b0f8534f2da54 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -845,6 +845,36 @@ def apply(self) -> FrameOrSeriesUnion: return self.apply_standard() + def agg(self): + result = super().agg() + if result is None: + f = self.f + args = self.args + kwargs = self.kwargs + + # string, list-like, and dict-like are entirely handled in super + assert callable(f) + + # we can be called from an inner function which + # passes this meta-data + kwargs.pop("_axis", None) + kwargs.pop("_level", None) + + # try a regular apply, this evaluates lambdas + # row-by-row; however if the lambda is expected a Series + # expression, e.g.: lambda x: x-x.quantile(0.25) + # this will fail, so we can try a vectorized evaluation + + # we cannot FIRST try the vectorized evaluation, because + # then .agg and .apply would have different semantics if the + # operation is actually defined on the Series, e.g. str + try: + result = self.obj.apply(f, *args, **kwargs) + except (ValueError, AttributeError, TypeError): + result = f(self.obj, *args, **kwargs) + + return result + def apply_empty_result(self) -> Series: obj = self.obj return obj._constructor(dtype=obj.dtype, index=obj.index).__finalize__( diff --git a/pandas/core/series.py b/pandas/core/series.py index cbb66918a661b..f3fbecd748e6d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4003,26 +4003,6 @@ def aggregate(self, func=None, axis=0, *args, **kwargs): op = series_apply(self, func, args=args, kwargs=kwargs) result = op.agg() - if result is None: - - # we can be called from an inner function which - # passes this meta-data - kwargs.pop("_axis", None) - kwargs.pop("_level", None) - - # try a regular apply, this evaluates lambdas - # row-by-row; however if the lambda is expected a Series - # expression, e.g.: lambda x: x-x.quantile(0.25) - # this will fail, so we can try a vectorized evaluation - - # we cannot FIRST try the vectorized evaluation, because - # then .agg and .apply would have different semantics if the - # operation is actually defined on the Series, e.g. str - try: - result = self.apply(func, *args, **kwargs) - except (ValueError, AttributeError, TypeError): - result = func(self, *args, **kwargs) - return result agg = aggregate @@ -4146,8 +4126,7 @@ def apply( Helsinki 2.484907 dtype: float64 """ - op = series_apply(self, func, convert_dtype, args, kwargs) - return op.apply() + return series_apply(self, func, convert_dtype, args, kwargs).apply() def _reduce( self,
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/39954
2021-02-21T12:34:19Z
2021-02-21T17:32:11Z
2021-02-21T17:32:11Z
2021-02-21T17:37:28Z
PERF: avoid object conversion in fillna(method=pad|backfill) for masked arrays
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index bcdd9c6fa5717..65167e6467fd5 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -11,6 +11,7 @@ date_range, isnull, period_range, + timedelta_range, ) from .pandas_vb_common import tm @@ -355,15 +356,42 @@ def time_isnull_obj(self): class Fillna: - params = ([True, False], ["pad", "bfill"]) - param_names = ["inplace", "method"] - - def setup(self, inplace, method): - values = np.random.randn(10000, 100) - values[::2] = np.nan - self.df = DataFrame(values) - - def time_frame_fillna(self, inplace, method): + params = ( + [True, False], + ["pad", "bfill"], + [ + "float64", + "float32", + "object", + "Int64", + "Float64", + "datetime64[ns]", + "datetime64[ns, tz]", + "timedelta64[ns]", + ], + ) + param_names = ["inplace", "method", "dtype"] + + def setup(self, inplace, method, dtype): + N, M = 10000, 100 + if dtype in ("datetime64[ns]", "datetime64[ns, tz]", "timedelta64[ns]"): + data = { + "datetime64[ns]": date_range("2011-01-01", freq="H", periods=N), + "datetime64[ns, tz]": date_range( + "2011-01-01", freq="H", periods=N, tz="Asia/Tokyo" + ), + "timedelta64[ns]": timedelta_range(start="1 day", periods=N, freq="1D"), + } + self.df = DataFrame({f"col_{i}": data[dtype] for i in range(M)}) + self.df[::2] = None + else: + values = np.random.randn(N, M) + values[::2] = np.nan + if dtype == "Int64": + values = values.round() + self.df = DataFrame(values, dtype=dtype) + + def time_frame_fillna(self, inplace, method, dtype): self.df.fillna(inplace=inplace, method=method) diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index e99963c6ad56b..ecb9830024900 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -375,6 +375,7 @@ Performance improvements - Performance improvement in :meth:`IntervalIndex.isin` (:issue:`38353`) - Performance improvement in :meth:`Series.mean` for nullable data types (:issue:`34814`) - Performance improvement in :meth:`Series.isin` for nullable data types (:issue:`38340`) +- Performance improvement in :meth:`DataFrame.fillna` with ``method="pad|backfill"`` for nullable floating and nullable integer dtypes (:issue:`39953`) - Performance improvement in :meth:`DataFrame.corr` for method=kendall (:issue:`28329`) - Performance improvement in :meth:`core.window.rolling.Rolling.corr` and :meth:`core.window.rolling.Rolling.cov` (:issue:`39388`) - Performance improvement in :meth:`core.window.rolling.RollingGroupby.corr`, :meth:`core.window.expanding.ExpandingGroupby.corr`, :meth:`core.window.expanding.ExpandingGroupby.corr` and :meth:`core.window.expanding.ExpandingGroupby.cov` (:issue:`39591`) diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 1a1b263ae356e..5783d3c2353aa 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -597,10 +597,11 @@ def pad(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): @cython.boundscheck(False) @cython.wraparound(False) -def pad_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): +def pad_inplace(algos_t[:] values, uint8_t[:] mask, limit=None): cdef: Py_ssize_t i, N algos_t val + uint8_t prev_mask int lim, fill_count = 0 N = len(values) @@ -612,15 +613,18 @@ def pad_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): lim = validate_limit(N, limit) val = values[0] + prev_mask = mask[0] for i in range(N): if mask[i]: if fill_count >= lim: continue fill_count += 1 values[i] = val + mask[i] = prev_mask else: fill_count = 0 val = values[i] + prev_mask = mask[i] @cython.boundscheck(False) @@ -739,10 +743,11 @@ def backfill(ndarray[algos_t] old, ndarray[algos_t] new, limit=None) -> ndarray: @cython.boundscheck(False) @cython.wraparound(False) -def backfill_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): +def backfill_inplace(algos_t[:] values, uint8_t[:] mask, limit=None): cdef: Py_ssize_t i, N algos_t val + uint8_t prev_mask int lim, fill_count = 0 N = len(values) @@ -754,15 +759,18 @@ def backfill_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): lim = validate_limit(N, limit) val = values[N - 1] + prev_mask = mask[N - 1] for i in range(N - 1, -1, -1): if mask[i]: if fill_count >= lim: continue fill_count += 1 values[i] = val + mask[i] = prev_mask else: fill_count = 0 val = values[i] + prev_mask = mask[i] @cython.boundscheck(False) diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index ad0bf76b0556b..4615cb4ec7abd 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -279,7 +279,7 @@ def fillna( if mask.any(): if method is not None: func = missing.get_fill_func(method) - new_values = func(self._ndarray.copy(), limit=limit, mask=mask) + new_values, _ = func(self._ndarray.copy(), limit=limit, mask=mask) # TODO: PandasArray didn't used to copy, need tests for this new_values = self._from_backing_data(new_values) else: diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 3b80c0b189108..86a1bcf24167c 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -702,7 +702,7 @@ def fillna(self, value=None, method=None, limit=None): if mask.any(): if method is not None: func = missing.get_fill_func(method) - new_values = func(self.astype(object), limit=limit, mask=mask) + new_values, _ = func(self.astype(object), limit=limit, mask=mask) new_values = self._from_sequence(new_values, dtype=self.dtype) else: # fill with value diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 8cf876fa32d7b..eff06a5c62894 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -28,6 +28,7 @@ cache_readonly, doc, ) +from pandas.util._validators import validate_fillna_kwargs from pandas.core.dtypes.base import ExtensionDtype from pandas.core.dtypes.common import ( @@ -38,12 +39,16 @@ is_string_dtype, pandas_dtype, ) +from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import ( isna, notna, ) -from pandas.core import nanops +from pandas.core import ( + missing, + nanops, +) from pandas.core.algorithms import ( factorize_array, isin, @@ -144,6 +149,39 @@ def __getitem__( return type(self)(self._data[item], self._mask[item]) + @doc(ExtensionArray.fillna) + def fillna( + self: BaseMaskedArrayT, value=None, method=None, limit=None + ) -> BaseMaskedArrayT: + value, method = validate_fillna_kwargs(value, method) + + mask = self._mask + + if is_array_like(value): + if len(value) != len(self): + raise ValueError( + f"Length of 'value' does not match. Got ({len(value)}) " + f" expected {len(self)}" + ) + value = value[mask] + + if mask.any(): + if method is not None: + func = missing.get_fill_func(method) + new_values, new_mask = func( + self._data.copy(), + limit=limit, + mask=mask.copy(), + ) + return type(self)(new_values, new_mask.view(np.bool_)) + else: + # fill with value + new_values = self.copy() + new_values[mask] = value + else: + new_values = self.copy() + return new_values + def _coerce_to_array(self, values) -> Tuple[np.ndarray, np.ndarray]: raise AbstractMethodError(self) diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 26fe6338118b6..e003efeabcb66 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -400,7 +400,7 @@ def fillna(self, value=None, method=None, limit=None): if mask.any(): if method is not None: func = missing.get_fill_func(method) - new_values = func(self.to_numpy(object), limit=limit, mask=mask) + new_values, _ = func(self.to_numpy(object), limit=limit, mask=mask) new_values = self._from_sequence(new_values) else: # fill with value diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 597023cb5b000..2e1a14104c16c 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1727,16 +1727,13 @@ def _slice(self, slicer): def fillna( self, value, limit=None, inplace: bool = False, downcast=None ) -> List[Block]: - values = self.values if inplace else self.values.copy() - values = values.fillna(value=value, limit=limit) + values = self.values.fillna(value=value, limit=limit) return [self.make_block_same_class(values=values)] def interpolate( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, **kwargs ): - - values = self.values if inplace else self.values.copy() - new_values = values.fillna(value=fill_value, method=method, limit=limit) + new_values = self.values.fillna(value=fill_value, method=method, limit=limit) return self.make_block_same_class(new_values) def diff(self, n: int, axis: int = 1) -> List[Block]: diff --git a/pandas/core/missing.py b/pandas/core/missing.py index d1597b23cf577..1b5a7237b5287 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -660,9 +660,9 @@ def interpolate_2d( method = clean_fill_method(method) tvalues = transf(values) if method == "pad": - result = _pad_2d(tvalues, limit=limit) + result, _ = _pad_2d(tvalues, limit=limit) else: - result = _backfill_2d(tvalues, limit=limit) + result, _ = _backfill_2d(tvalues, limit=limit) result = transf(result) # reshape back @@ -698,8 +698,8 @@ def new_func(values, limit=None, mask=None): # This needs to occur before casting to int64 mask = isna(values) - result = func(values.view("i8"), limit=limit, mask=mask) - return result.view(values.dtype) + result, mask = func(values.view("i8"), limit=limit, mask=mask) + return result.view(values.dtype), mask return func(values, limit=limit, mask=mask) @@ -707,17 +707,25 @@ def new_func(values, limit=None, mask=None): @_datetimelike_compat -def _pad_1d(values, limit=None, mask=None): +def _pad_1d( + values: np.ndarray, + limit: int | None = None, + mask: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray]: mask = _fillna_prep(values, mask) algos.pad_inplace(values, mask, limit=limit) - return values + return values, mask @_datetimelike_compat -def _backfill_1d(values, limit=None, mask=None): +def _backfill_1d( + values: np.ndarray, + limit: int | None = None, + mask: np.ndarray | None = None, +) -> tuple[np.ndarray, np.ndarray]: mask = _fillna_prep(values, mask) algos.backfill_inplace(values, mask, limit=limit) - return values + return values, mask @_datetimelike_compat @@ -729,7 +737,7 @@ def _pad_2d(values, limit=None, mask=None): else: # for test coverage pass - return values + return values, mask @_datetimelike_compat @@ -741,7 +749,7 @@ def _backfill_2d(values, limit=None, mask=None): else: # for test coverage pass - return values + return values, mask _fill_methods = {"pad": _pad_1d, "backfill": _backfill_1d} diff --git a/pandas/core/series.py b/pandas/core/series.py index 5a5d1c44b312c..e1a6c6884e003 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4529,7 +4529,7 @@ def _replace_single(self, to_replace, method: str, inplace: bool, limit): fill_f = missing.get_fill_func(method) mask = missing.mask_missing(result.values, to_replace) - values = fill_f(result.values, limit=limit, mask=mask) + values, _ = fill_f(result.values, limit=limit, mask=mask) if values.dtype == orig_dtype and inplace: return diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index 0cf03533915f2..c501694a7c2d5 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -69,6 +69,18 @@ def test_fillna_limit_backfill(self, data_missing): expected = pd.Series(data_missing.take([1, 0, 1, 1, 1])) self.assert_series_equal(result, expected) + def test_fillna_no_op_returns_copy(self, data): + data = data[~data.isna()] + + valid = data[0] + result = data.fillna(valid) + assert result is not data + self.assert_extension_array_equal(result, data) + + result = data.fillna(method="backfill") + assert result is not data + self.assert_extension_array_equal(result, data) + def test_fillna_series(self, data_missing): fill_value = data_missing[1] ser = pd.Series(data_missing) diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 1bc06ee4b6397..24c0d619e2b1a 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -132,6 +132,10 @@ def test_fillna_series_method(self): def test_fillna_limit_backfill(self): pass + @unsupported_fill + def test_fillna_no_op_returns_copy(self): + pass + @unsupported_fill def test_fillna_series(self): pass diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index e8995bc654428..718ef087e47d3 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -309,6 +309,11 @@ def test_fillna_scalar(self, data_missing): # Non-scalar "scalar" values. super().test_fillna_scalar(data_missing) + @skip_nested + def test_fillna_no_op_returns_copy(self, data): + # Non-scalar "scalar" values. + super().test_fillna_no_op_returns_copy(data) + @skip_nested def test_fillna_series(self, data_missing): # Non-scalar "scalar" values. diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 067fada5edcae..a49e1b4a367fd 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -221,6 +221,13 @@ def test_fillna_limit_backfill(self, data_missing): with tm.assert_produces_warning(PerformanceWarning): super().test_fillna_limit_backfill(data_missing) + def test_fillna_no_op_returns_copy(self, data, request): + if np.isnan(data.fill_value): + request.node.add_marker( + pytest.mark.xfail(reason="returns array with different fill value") + ) + super().test_fillna_no_op_returns_copy(data) + def test_fillna_series_method(self, data_missing): with tm.assert_produces_warning(PerformanceWarning): super().test_fillna_limit_backfill(data_missing)
``` [ 75.00%] ··· frame_methods.Fillna.time_frame_fillna ok [ 75.00%] ··· ========= ======== ============ ============= ========== ============= ============= -- dtype ------------------ ----------------------------------------------------------------- inplace method float64 float32 object Int64 Float64 ========= ======== ============ ============= ========== ============= ============= True pad 3.44±0.3ms 2.64±0.2ms 307±10ms 3.97±0.2ms 3.72±0.1ms True bfill 3.23±0.2ms 2.89±0.2ms 275±8ms 2.34±0.1ms 2.45±0.09ms False pad 3.62±0.1ms 2.06±0.01ms 181±3ms 4.23±0.07ms 4.16±0.07ms False bfill 3.59±0.2ms 2.06±0.02ms 186±6ms 4.35±0.09ms 4.18±0.06ms ========= ======== ============ ============= ========== ============= ============= ``` ``` before after ratio [2e5c28fc] [d3ae0cf1] <master> <BaseMaskedArray.fillna> - 2.28±0.06ms 2.06±0.02ms 0.91 frame_methods.Fillna.time_frame_fillna(False, 'bfill', 'float32') - 15.5±0.2ms 2.45±0.09ms 0.16 frame_methods.Fillna.time_frame_fillna(True, 'bfill', 'Float64') - 16.5±0.2ms 2.34±0.1ms 0.14 frame_methods.Fillna.time_frame_fillna(True, 'bfill', 'Int64') - 85.2±0.9ms 4.18±0.06ms 0.05 frame_methods.Fillna.time_frame_fillna(False, 'bfill', 'Float64') - 86.6±0.6ms 4.16±0.07ms 0.05 frame_methods.Fillna.time_frame_fillna(False, 'pad', 'Float64') - 90.9±0.8ms 4.35±0.09ms 0.05 frame_methods.Fillna.time_frame_fillna(False, 'bfill', 'Int64') - 92.4±0.4ms 4.23±0.07ms 0.05 frame_methods.Fillna.time_frame_fillna(False, 'pad', 'Int64') - 85.3±1ms 3.72±0.1ms 0.04 frame_methods.Fillna.time_frame_fillna(True, 'pad', 'Float64') - 92.5±2ms 3.97±0.2ms 0.04 frame_methods.Fillna.time_frame_fillna(True, 'pad', 'Int64') SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39953
2021-02-21T12:19:42Z
2021-03-05T19:00:20Z
2021-03-05T19:00:20Z
2021-03-06T09:55:11Z
PERF: Styler render improvement by limiting .join()
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 877e146fd8681..be748dfbdb2d6 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -466,7 +466,7 @@ def _translate(self): } colspan = col_lengths.get((r, c), 0) if colspan > 1: - es["attributes"] = [f'colspan="{colspan}"'] + es["attributes"] = f'colspan="{colspan}"' row_es.append(es) head.append(row_es) @@ -517,7 +517,7 @@ def _translate(self): } rowspan = idx_lengths.get((c, r), 0) if rowspan > 1: - es["attributes"] = [f'rowspan="{rowspan}"'] + es["attributes"] = f'rowspan="{rowspan}"' row_es.append(es) for c, col in enumerate(self.data.columns): @@ -529,6 +529,7 @@ def _translate(self): "value": value, "display_value": formatter(value), "is_visible": (c not in hidden_columns), + "attributes": "", } # only add an id if the cell has a style diff --git a/pandas/io/formats/templates/html.tpl b/pandas/io/formats/templates/html.tpl index b315c57a65cdf..65fc1dfbb37c4 100644 --- a/pandas/io/formats/templates/html.tpl +++ b/pandas/io/formats/templates/html.tpl @@ -39,7 +39,7 @@ <tr> {% for c in r %} {% if c.is_visible != False %} - <{{c.type}} class="{{c.class}}" {{c.attributes|join(" ")}}>{{c.value}}</{{c.type}}> + <{{c.type}} class="{{c.class}}" {{c.attributes}}>{{c.value}}</{{c.type}}> {% endif %} {% endfor %} </tr> @@ -56,7 +56,7 @@ <tr> {% for c in r %} {% if c.is_visible != False %} - <{{c.type}} {% if c.id is defined -%} id="T_{{uuid}}{{c.id}}" {%- endif %} class="{{c.class}}" {{c.attributes|join(" ")}}>{{c.display_value}}</{{c.type}}> + <{{c.type}} {% if c.id is defined -%} id="T_{{uuid}}{{c.id}}" {%- endif %} class="{{c.class}}" {{c.attributes}}>{{c.display_value}}</{{c.type}}> {% endif %} {% endfor %} </tr> diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index d134f33e15525..2a6505a43b80a 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -1323,7 +1323,7 @@ def test_mi_sparse(self): "display_value": "a", "is_visible": True, "type": "th", - "attributes": ['rowspan="2"'], + "attributes": 'rowspan="2"', "class": "row_heading level0 row0", "id": "level0_row0", }
Currently `<th>` only have attributes when there is a row or column span. `<td>` never have attributes currently. So there is no need for repititive `join()` operations, especially inside the jinja2 template. Could be preconfigured outside. We can get around 10-15% better render times. ``` [ 75.00%] ··· io.style.RenderApply.time_render ok [ 75.00%] ··· ====== ============ ============ -- rows ------ ------------------------- cols 12 120 ====== ============ ============ 12 11.6±0.5ms 77.0±0.5ms 24 29.2±0.5ms 144±1ms 36 43.7±0.9ms 209±2ms ====== ============ ============ ``` versus master ``` [100.00%] ··· io.style.RenderApply.time_render ok [100.00%] ··· ====== ============ ========== -- rows ------ ----------------------- cols 12 120 ====== ============ ========== 12 12.9±0.4ms 89.8±4ms 24 31.4±0.9ms 166±2ms 36 46.5±2ms 250±40ms ====== ============ ========== ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39952
2021-02-21T11:27:43Z
2021-02-21T18:03:47Z
2021-02-21T18:03:47Z
2021-03-30T05:05:11Z
TYP: hashing
diff --git a/pandas/_libs/hashing.pyx b/pandas/_libs/hashing.pyx index ead967386ed1d..2dd2f1feadd70 100644 --- a/pandas/_libs/hashing.pyx +++ b/pandas/_libs/hashing.pyx @@ -27,7 +27,9 @@ DEF dROUNDS = 4 @cython.boundscheck(False) -def hash_object_array(ndarray[object] arr, str key, str encoding="utf8"): +def hash_object_array( + ndarray[object] arr, str key, str encoding="utf8" +) -> np.ndarray[np.uint64]: """ Parameters ---------- diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 4e04425436af4..1ff481553e413 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -269,7 +269,7 @@ def item_from_zerodim(val: object) -> object: @cython.wraparound(False) @cython.boundscheck(False) -def fast_unique_multiple(list arrays, sort: bool = True): +def fast_unique_multiple(list arrays, sort: bool = True) -> list: """ Generate a list of unique values from a list of arrays. @@ -345,7 +345,7 @@ def fast_unique_multiple_list(lists: list, sort: bool = True) -> list: @cython.wraparound(False) @cython.boundscheck(False) -def fast_unique_multiple_list_gen(object gen, bint sort=True): +def fast_unique_multiple_list_gen(object gen, bint sort=True) -> list: """ Generate a list of unique values from a generator of lists. @@ -409,7 +409,7 @@ def dicts_to_array(dicts: list, columns: list): return result -def fast_zip(list ndarrays): +def fast_zip(list ndarrays) -> ndarray[object]: """ For zipping multiple ndarrays into an ndarray of tuples. """ @@ -621,7 +621,7 @@ def array_equivalent_object(left: object[:], right: object[:]) -> bool: @cython.wraparound(False) @cython.boundscheck(False) -def astype_intsafe(ndarray[object] arr, new_dtype): +def astype_intsafe(ndarray[object] arr, new_dtype) -> ndarray: cdef: Py_ssize_t i, n = len(arr) object val @@ -891,7 +891,7 @@ def generate_slices(const int64_t[:] labels, Py_ssize_t ngroups): def indices_fast(ndarray index, const int64_t[:] labels, list keys, - list sorted_labels): + list sorted_labels) -> dict: """ Parameters ---------- @@ -1979,8 +1979,12 @@ cpdef bint is_interval_array(ndarray values): @cython.boundscheck(False) @cython.wraparound(False) -def maybe_convert_numeric(ndarray[object] values, set na_values, - bint convert_empty=True, bint coerce_numeric=False): +def maybe_convert_numeric( + ndarray[object] values, + set na_values, + bint convert_empty=True, + bint coerce_numeric=False, +) -> ndarray: """ Convert object array to a numeric array if possible. @@ -2154,7 +2158,7 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, def maybe_convert_objects(ndarray[object] objects, bint try_float=False, bint safe=False, bint convert_datetime=False, bint convert_timedelta=False, - bint convert_to_nullable_integer=False): + bint convert_to_nullable_integer=False) -> "ArrayLike": """ Type inference function-- convert object array to proper dtype @@ -2181,6 +2185,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, Returns ------- np.ndarray or ExtensionArray + Array of converted object values to more specific dtypes if applicable. """ cdef: Py_ssize_t i, n @@ -2408,13 +2413,13 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, # Note: no_default is exported to the public API in pandas.api.extensions -no_default = object() #: Sentinel indicating the default value. +no_default = object() # Sentinel indicating the default value. @cython.boundscheck(False) @cython.wraparound(False) def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=True, - object na_value=no_default, object dtype=object): + object na_value=no_default, object dtype=object) -> "ArrayLike": """ Substitute for np.vectorize with pandas-friendly dtype inference. @@ -2469,7 +2474,9 @@ def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=Tr @cython.boundscheck(False) @cython.wraparound(False) -def map_infer(ndarray arr, object f, bint convert=True, bint ignore_na=False): +def map_infer( + ndarray arr, object f, bint convert=True, bint ignore_na=False +) -> "ArrayLike": """ Substitute for np.vectorize with pandas-friendly dtype inference. @@ -2483,7 +2490,7 @@ def map_infer(ndarray arr, object f, bint convert=True, bint ignore_na=False): Returns ------- - ndarray + np.ndarray or ExtensionArray """ cdef: Py_ssize_t i, n @@ -2513,7 +2520,7 @@ def map_infer(ndarray arr, object f, bint convert=True, bint ignore_na=False): return result -def to_object_array(rows: object, int min_width=0): +def to_object_array(rows: object, min_width: int = 0) -> ndarray: """ Convert a list of lists into an object array. @@ -2529,7 +2536,7 @@ def to_object_array(rows: object, int min_width=0): Returns ------- - numpy array of the object dtype. + np.ndarray[object, ndim=2] """ cdef: Py_ssize_t i, j, n, k, tmp @@ -2621,7 +2628,7 @@ def to_object_array_tuples(rows: object): @cython.wraparound(False) @cython.boundscheck(False) -def fast_multiget(dict mapping, ndarray keys, default=np.nan): +def fast_multiget(dict mapping, ndarray keys, default=np.nan) -> "ArrayLike": cdef: Py_ssize_t i, n = len(keys) object val diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 62549079309f6..dbf2446f43af3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9151,7 +9151,7 @@ def count( return result.astype("int64") - def _count_level(self, level: Level, axis: Axis = 0, numeric_only=False): + def _count_level(self, level: Level, axis: int = 0, numeric_only: bool = False): if numeric_only: frame = self._get_numeric_data() else: diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index 6d375a92ea50a..9d488bb13b0f1 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -1,12 +1,27 @@ """ data hash pandas / numpy objects """ +from __future__ import annotations + import itertools -from typing import Optional +from typing import ( + TYPE_CHECKING, + Hashable, + Iterable, + Iterator, + Optional, + Tuple, + Union, + cast, +) import numpy as np -import pandas._libs.hashing as hashing +from pandas._libs.hashing import hash_object_array +from pandas._typing import ( + ArrayLike, + FrameOrSeriesUnion, +) from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -20,17 +35,30 @@ ABCSeries, ) +if TYPE_CHECKING: + from pandas import ( + Categorical, + Index, + MultiIndex, + Series, + ) + + # 16 byte long hashing key _default_hash_key = "0123456789123456" -def combine_hash_arrays(arrays, num_items: int): +def combine_hash_arrays(arrays: Iterator[np.ndarray], num_items: int) -> np.ndarray: """ Parameters ---------- - arrays : generator + arrays : Iterator[np.ndarray] num_items : int + Returns + ------- + np.ndarray[int64] + Should be the same as CPython's tupleobject.c """ try: @@ -53,17 +81,18 @@ def combine_hash_arrays(arrays, num_items: int): def hash_pandas_object( - obj, + obj: Union[Index, FrameOrSeriesUnion], index: bool = True, encoding: str = "utf8", hash_key: Optional[str] = _default_hash_key, categorize: bool = True, -): +) -> Series: """ Return a data hash of the Index/Series/DataFrame. Parameters ---------- + obj : Index, Series, or DataFrame index : bool, default True Include the index in the hash (if Series/DataFrame). encoding : str, default 'utf8' @@ -139,13 +168,17 @@ def hash_pandas_object( return h -def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): +def hash_tuples( + vals: Union[MultiIndex, Iterable[Tuple[Hashable, ...]]], + encoding: str = "utf8", + hash_key: str = _default_hash_key, +) -> np.ndarray: """ - Hash an MultiIndex / list-of-tuples efficiently + Hash an MultiIndex / listlike-of-tuples efficiently. Parameters ---------- - vals : MultiIndex, list-of-tuples, or single tuple + vals : MultiIndex or listlike-of-tuples encoding : str, default 'utf8' hash_key : str, default _default_hash_key @@ -153,11 +186,7 @@ def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): ------- ndarray of hashed values array """ - is_tuple = False - if isinstance(vals, tuple): - vals = [vals] - is_tuple = True - elif not is_list_like(vals): + if not is_list_like(vals): raise TypeError("must be convertible to a list-of-tuples") from pandas import ( @@ -166,33 +195,33 @@ def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): ) if not isinstance(vals, ABCMultiIndex): - vals = MultiIndex.from_tuples(vals) + mi = MultiIndex.from_tuples(vals) + else: + mi = vals # create a list-of-Categoricals - vals = [ - Categorical(vals.codes[level], vals.levels[level], ordered=False, fastpath=True) - for level in range(vals.nlevels) + cat_vals = [ + Categorical(mi.codes[level], mi.levels[level], ordered=False, fastpath=True) + for level in range(mi.nlevels) ] # hash the list-of-ndarrays hashes = ( - _hash_categorical(cat, encoding=encoding, hash_key=hash_key) for cat in vals + _hash_categorical(cat, encoding=encoding, hash_key=hash_key) for cat in cat_vals ) - h = combine_hash_arrays(hashes, len(vals)) - if is_tuple: - h = h[0] + h = combine_hash_arrays(hashes, len(cat_vals)) return h -def _hash_categorical(c, encoding: str, hash_key: str): +def _hash_categorical(cat: Categorical, encoding: str, hash_key: str) -> np.ndarray: """ Hash a Categorical by hashing its categories, and then mapping the codes to the hashes Parameters ---------- - c : Categorical + cat : Categorical encoding : str hash_key : str @@ -201,7 +230,7 @@ def _hash_categorical(c, encoding: str, hash_key: str): ndarray of hashed values array, same size as len(c) """ # Convert ExtensionArrays to ndarrays - values = np.asarray(c.categories._values) + values = np.asarray(cat.categories._values) hashed = hash_array(values, encoding, hash_key, categorize=False) # we have uint64, as we don't directly support missing values @@ -211,9 +240,9 @@ def _hash_categorical(c, encoding: str, hash_key: str): # # TODO: GH 15362 - mask = c.isna() + mask = cat.isna() if len(hashed): - result = hashed.take(c.codes) + result = hashed.take(cat.codes) else: result = np.zeros(len(mask), dtype="uint64") @@ -224,17 +253,17 @@ def _hash_categorical(c, encoding: str, hash_key: str): def hash_array( - vals, + vals: ArrayLike, encoding: str = "utf8", hash_key: str = _default_hash_key, categorize: bool = True, -): +) -> np.ndarray: """ Given a 1d array, return an array of deterministic integers. Parameters ---------- - vals : ndarray, Categorical + vals : ndarray or ExtensionArray encoding : str, default 'utf8' Encoding for data & key when strings. hash_key : str, default _default_hash_key @@ -255,10 +284,24 @@ def hash_array( # hash values. (This check is above the complex check so that we don't ask # numpy if categorical is a subdtype of complex, as it will choke). if is_categorical_dtype(dtype): + vals = cast("Categorical", vals) return _hash_categorical(vals, encoding, hash_key) elif is_extension_array_dtype(dtype): vals, _ = vals._values_for_factorize() - dtype = vals.dtype + + return _hash_ndarray(vals, encoding, hash_key, categorize) + + +def _hash_ndarray( + vals: np.ndarray, + encoding: str = "utf8", + hash_key: str = _default_hash_key, + categorize: bool = True, +) -> np.ndarray: + """ + See hash_array.__doc__. + """ + dtype = vals.dtype # we'll be working with everything as 64-bit values, so handle this # 128-bit value early @@ -289,10 +332,10 @@ def hash_array( return _hash_categorical(cat, encoding, hash_key) try: - vals = hashing.hash_object_array(vals, hash_key, encoding) + vals = hash_object_array(vals, hash_key, encoding) except TypeError: # we have mixed types - vals = hashing.hash_object_array( + vals = hash_object_array( vals.astype(str).astype(object), hash_key, encoding ) diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index 94786292adb51..e373323dfb6e1 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -113,8 +113,10 @@ def test_hash_tuples(): expected = hash_pandas_object(MultiIndex.from_tuples(tuples)).values tm.assert_numpy_array_equal(result, expected) - result = hash_tuples(tuples[0]) - assert result == expected[0] + # We only need to support MultiIndex and list-of-tuples + msg = "|".join(["object is not iterable", "zip argument #1 must support iteration"]) + with pytest.raises(TypeError, match=msg): + hash_tuples(tuples[0]) @pytest.mark.parametrize("val", [5, "foo", pd.Timestamp("20130101")])
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39949
2021-02-21T03:23:57Z
2021-03-08T18:11:59Z
2021-03-08T18:11:59Z
2021-03-08T18:12:12Z
REF: implement array_algos.take
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 4dac4dd557af2..24a8fbcb3bb2d 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -39,7 +39,6 @@ from pandas.core.dtypes.cast import ( construct_1d_object_array_from_listlike, infer_dtype_from_array, - maybe_promote, ) from pandas.core.dtypes.common import ( ensure_float64, @@ -83,6 +82,7 @@ na_value_for_dtype, ) +from pandas.core.array_algos.take import take_nd from pandas.core.construction import ( array, ensure_wrapped_if_datetimelike, @@ -1414,219 +1414,6 @@ def get_indexer(current_indexer, other_indexer): # ---- # -def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None): - def wrapper( - arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan - ): - if arr_dtype is not None: - arr = arr.view(arr_dtype) - if out_dtype is not None: - out = out.view(out_dtype) - if fill_wrap is not None: - fill_value = fill_wrap(fill_value) - f(arr, indexer, out, fill_value=fill_value) - - return wrapper - - -def _convert_wrapper(f, conv_dtype): - def wrapper( - arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan - ): - if conv_dtype == object: - # GH#39755 avoid casting dt64/td64 to integers - arr = ensure_wrapped_if_datetimelike(arr) - arr = arr.astype(conv_dtype) - f(arr, indexer, out, fill_value=fill_value) - - return wrapper - - -def _take_2d_multi_object( - arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value, mask_info -) -> None: - # this is not ideal, performance-wise, but it's better than raising - # an exception (best to optimize in Cython to avoid getting here) - row_idx, col_idx = indexer - if mask_info is not None: - (row_mask, col_mask), (row_needs, col_needs) = mask_info - else: - row_mask = row_idx == -1 - col_mask = col_idx == -1 - row_needs = row_mask.any() - col_needs = col_mask.any() - if fill_value is not None: - if row_needs: - out[row_mask, :] = fill_value - if col_needs: - out[:, col_mask] = fill_value - for i in range(len(row_idx)): - u_ = row_idx[i] - for j in range(len(col_idx)): - v = col_idx[j] - out[i, j] = arr[u_, v] - - -def _take_nd_object( - arr: np.ndarray, - indexer: np.ndarray, - out: np.ndarray, - axis: int, - fill_value, - mask_info, -): - if mask_info is not None: - mask, needs_masking = mask_info - else: - mask = indexer == -1 - needs_masking = mask.any() - if arr.dtype != out.dtype: - arr = arr.astype(out.dtype) - if arr.shape[axis] > 0: - arr.take(ensure_platform_int(indexer), axis=axis, out=out) - if needs_masking: - outindexer = [slice(None)] * arr.ndim - outindexer[axis] = mask - out[tuple(outindexer)] = fill_value - - -_take_1d_dict = { - ("int8", "int8"): algos.take_1d_int8_int8, - ("int8", "int32"): algos.take_1d_int8_int32, - ("int8", "int64"): algos.take_1d_int8_int64, - ("int8", "float64"): algos.take_1d_int8_float64, - ("int16", "int16"): algos.take_1d_int16_int16, - ("int16", "int32"): algos.take_1d_int16_int32, - ("int16", "int64"): algos.take_1d_int16_int64, - ("int16", "float64"): algos.take_1d_int16_float64, - ("int32", "int32"): algos.take_1d_int32_int32, - ("int32", "int64"): algos.take_1d_int32_int64, - ("int32", "float64"): algos.take_1d_int32_float64, - ("int64", "int64"): algos.take_1d_int64_int64, - ("int64", "float64"): algos.take_1d_int64_float64, - ("float32", "float32"): algos.take_1d_float32_float32, - ("float32", "float64"): algos.take_1d_float32_float64, - ("float64", "float64"): algos.take_1d_float64_float64, - ("object", "object"): algos.take_1d_object_object, - ("bool", "bool"): _view_wrapper(algos.take_1d_bool_bool, np.uint8, np.uint8), - ("bool", "object"): _view_wrapper(algos.take_1d_bool_object, np.uint8, None), - ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( - algos.take_1d_int64_int64, np.int64, np.int64, np.int64 - ), -} - -_take_2d_axis0_dict = { - ("int8", "int8"): algos.take_2d_axis0_int8_int8, - ("int8", "int32"): algos.take_2d_axis0_int8_int32, - ("int8", "int64"): algos.take_2d_axis0_int8_int64, - ("int8", "float64"): algos.take_2d_axis0_int8_float64, - ("int16", "int16"): algos.take_2d_axis0_int16_int16, - ("int16", "int32"): algos.take_2d_axis0_int16_int32, - ("int16", "int64"): algos.take_2d_axis0_int16_int64, - ("int16", "float64"): algos.take_2d_axis0_int16_float64, - ("int32", "int32"): algos.take_2d_axis0_int32_int32, - ("int32", "int64"): algos.take_2d_axis0_int32_int64, - ("int32", "float64"): algos.take_2d_axis0_int32_float64, - ("int64", "int64"): algos.take_2d_axis0_int64_int64, - ("int64", "float64"): algos.take_2d_axis0_int64_float64, - ("float32", "float32"): algos.take_2d_axis0_float32_float32, - ("float32", "float64"): algos.take_2d_axis0_float32_float64, - ("float64", "float64"): algos.take_2d_axis0_float64_float64, - ("object", "object"): algos.take_2d_axis0_object_object, - ("bool", "bool"): _view_wrapper(algos.take_2d_axis0_bool_bool, np.uint8, np.uint8), - ("bool", "object"): _view_wrapper(algos.take_2d_axis0_bool_object, np.uint8, None), - ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( - algos.take_2d_axis0_int64_int64, np.int64, np.int64, fill_wrap=np.int64 - ), -} - -_take_2d_axis1_dict = { - ("int8", "int8"): algos.take_2d_axis1_int8_int8, - ("int8", "int32"): algos.take_2d_axis1_int8_int32, - ("int8", "int64"): algos.take_2d_axis1_int8_int64, - ("int8", "float64"): algos.take_2d_axis1_int8_float64, - ("int16", "int16"): algos.take_2d_axis1_int16_int16, - ("int16", "int32"): algos.take_2d_axis1_int16_int32, - ("int16", "int64"): algos.take_2d_axis1_int16_int64, - ("int16", "float64"): algos.take_2d_axis1_int16_float64, - ("int32", "int32"): algos.take_2d_axis1_int32_int32, - ("int32", "int64"): algos.take_2d_axis1_int32_int64, - ("int32", "float64"): algos.take_2d_axis1_int32_float64, - ("int64", "int64"): algos.take_2d_axis1_int64_int64, - ("int64", "float64"): algos.take_2d_axis1_int64_float64, - ("float32", "float32"): algos.take_2d_axis1_float32_float32, - ("float32", "float64"): algos.take_2d_axis1_float32_float64, - ("float64", "float64"): algos.take_2d_axis1_float64_float64, - ("object", "object"): algos.take_2d_axis1_object_object, - ("bool", "bool"): _view_wrapper(algos.take_2d_axis1_bool_bool, np.uint8, np.uint8), - ("bool", "object"): _view_wrapper(algos.take_2d_axis1_bool_object, np.uint8, None), - ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( - algos.take_2d_axis1_int64_int64, np.int64, np.int64, fill_wrap=np.int64 - ), -} - -_take_2d_multi_dict = { - ("int8", "int8"): algos.take_2d_multi_int8_int8, - ("int8", "int32"): algos.take_2d_multi_int8_int32, - ("int8", "int64"): algos.take_2d_multi_int8_int64, - ("int8", "float64"): algos.take_2d_multi_int8_float64, - ("int16", "int16"): algos.take_2d_multi_int16_int16, - ("int16", "int32"): algos.take_2d_multi_int16_int32, - ("int16", "int64"): algos.take_2d_multi_int16_int64, - ("int16", "float64"): algos.take_2d_multi_int16_float64, - ("int32", "int32"): algos.take_2d_multi_int32_int32, - ("int32", "int64"): algos.take_2d_multi_int32_int64, - ("int32", "float64"): algos.take_2d_multi_int32_float64, - ("int64", "int64"): algos.take_2d_multi_int64_int64, - ("int64", "float64"): algos.take_2d_multi_int64_float64, - ("float32", "float32"): algos.take_2d_multi_float32_float32, - ("float32", "float64"): algos.take_2d_multi_float32_float64, - ("float64", "float64"): algos.take_2d_multi_float64_float64, - ("object", "object"): algos.take_2d_multi_object_object, - ("bool", "bool"): _view_wrapper(algos.take_2d_multi_bool_bool, np.uint8, np.uint8), - ("bool", "object"): _view_wrapper(algos.take_2d_multi_bool_object, np.uint8, None), - ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( - algos.take_2d_multi_int64_int64, np.int64, np.int64, fill_wrap=np.int64 - ), -} - - -def _get_take_nd_function( - ndim: int, arr_dtype: np.dtype, out_dtype: np.dtype, axis: int = 0, mask_info=None -): - if ndim <= 2: - tup = (arr_dtype.name, out_dtype.name) - if ndim == 1: - func = _take_1d_dict.get(tup, None) - elif ndim == 2: - if axis == 0: - func = _take_2d_axis0_dict.get(tup, None) - else: - func = _take_2d_axis1_dict.get(tup, None) - if func is not None: - return func - - tup = (out_dtype.name, out_dtype.name) - if ndim == 1: - func = _take_1d_dict.get(tup, None) - elif ndim == 2: - if axis == 0: - func = _take_2d_axis0_dict.get(tup, None) - else: - func = _take_2d_axis1_dict.get(tup, None) - if func is not None: - func = _convert_wrapper(func, out_dtype) - return func - - def func2(arr, indexer, out, fill_value=np.nan): - indexer = ensure_int64(indexer) - _take_nd_object( - arr, indexer, out, axis=axis, fill_value=fill_value, mask_info=mask_info - ) - - return func2 - - def take( arr, indices: np.ndarray, axis: int = 0, allow_fill: bool = False, fill_value=None ): @@ -1720,190 +1507,6 @@ def take( return result -def _take_preprocess_indexer_and_fill_value( - arr: np.ndarray, - indexer: Optional[np.ndarray], - axis: int, - out: Optional[np.ndarray], - fill_value, - allow_fill: bool, -): - mask_info = None - - if indexer is None: - indexer = np.arange(arr.shape[axis], dtype=np.int64) - dtype, fill_value = arr.dtype, arr.dtype.type() - else: - indexer = ensure_int64(indexer, copy=False) - if not allow_fill: - dtype, fill_value = arr.dtype, arr.dtype.type() - mask_info = None, False - else: - # check for promotion based on types only (do this first because - # it's faster than computing a mask) - dtype, fill_value = maybe_promote(arr.dtype, fill_value) - if dtype != arr.dtype and (out is None or out.dtype != dtype): - # check if promotion is actually required based on indexer - mask = indexer == -1 - needs_masking = mask.any() - mask_info = mask, needs_masking - if needs_masking: - if out is not None and out.dtype != dtype: - raise TypeError("Incompatible type for fill_value") - else: - # if not, then depromote, set fill_value to dummy - # (it won't be used but we don't want the cython code - # to crash when trying to cast it to dtype) - dtype, fill_value = arr.dtype, arr.dtype.type() - - return indexer, dtype, fill_value, mask_info - - -def take_nd( - arr, - indexer, - axis: int = 0, - out: Optional[np.ndarray] = None, - fill_value=lib.no_default, - allow_fill: bool = True, -): - """ - Specialized Cython take which sets NaN values in one pass - - This dispatches to ``take`` defined on ExtensionArrays. It does not - currently dispatch to ``SparseArray.take`` for sparse ``arr``. - - Parameters - ---------- - arr : array-like - Input array. - indexer : ndarray - 1-D array of indices to take, subarrays corresponding to -1 value - indices are filed with fill_value - axis : int, default 0 - Axis to take from - out : ndarray or None, default None - Optional output array, must be appropriate type to hold input and - fill_value together, if indexer has any -1 value entries; call - maybe_promote to determine this type for any fill_value - fill_value : any, default np.nan - Fill value to replace -1 values with - allow_fill : boolean, default True - If False, indexer is assumed to contain no -1 values so no filling - will be done. This short-circuits computation of a mask. Result is - undefined if allow_fill == False and -1 is present in indexer. - - Returns - ------- - subarray : array-like - May be the same type as the input, or cast to an ndarray. - """ - if fill_value is lib.no_default: - fill_value = na_value_for_dtype(arr.dtype, compat=False) - - if isinstance(arr, ABCExtensionArray): - # Check for EA to catch DatetimeArray, TimedeltaArray - return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) - - arr = extract_array(arr) - arr = np.asarray(arr) - - indexer, dtype, fill_value, mask_info = _take_preprocess_indexer_and_fill_value( - arr, indexer, axis, out, fill_value, allow_fill - ) - - flip_order = False - if arr.ndim == 2 and arr.flags.f_contiguous: - flip_order = True - - if flip_order: - arr = arr.T - axis = arr.ndim - axis - 1 - if out is not None: - out = out.T - - # at this point, it's guaranteed that dtype can hold both the arr values - # and the fill_value - if out is None: - out_shape_ = list(arr.shape) - out_shape_[axis] = len(indexer) - out_shape = tuple(out_shape_) - if arr.flags.f_contiguous and axis == arr.ndim - 1: - # minor tweak that can make an order-of-magnitude difference - # for dataframes initialized directly from 2-d ndarrays - # (s.t. df.values is c-contiguous and df._mgr.blocks[0] is its - # f-contiguous transpose) - out = np.empty(out_shape, dtype=dtype, order="F") - else: - out = np.empty(out_shape, dtype=dtype) - - func = _get_take_nd_function( - arr.ndim, arr.dtype, out.dtype, axis=axis, mask_info=mask_info - ) - func(arr, indexer, out, fill_value) - - if flip_order: - out = out.T - return out - - -def take_2d_multi( - arr: np.ndarray, indexer: np.ndarray, fill_value=np.nan -) -> np.ndarray: - """ - Specialized Cython take which sets NaN values in one pass. - """ - # This is only called from one place in DataFrame._reindex_multi, - # so we know indexer is well-behaved. - assert indexer is not None - assert indexer[0] is not None - assert indexer[1] is not None - - row_idx, col_idx = indexer - - row_idx = ensure_int64(row_idx) - col_idx = ensure_int64(col_idx) - indexer = row_idx, col_idx - mask_info = None - - # check for promotion based on types only (do this first because - # it's faster than computing a mask) - dtype, fill_value = maybe_promote(arr.dtype, fill_value) - if dtype != arr.dtype: - # check if promotion is actually required based on indexer - row_mask = row_idx == -1 - col_mask = col_idx == -1 - row_needs = row_mask.any() - col_needs = col_mask.any() - mask_info = (row_mask, col_mask), (row_needs, col_needs) - - if not (row_needs or col_needs): - # if not, then depromote, set fill_value to dummy - # (it won't be used but we don't want the cython code - # to crash when trying to cast it to dtype) - dtype, fill_value = arr.dtype, arr.dtype.type() - - # at this point, it's guaranteed that dtype can hold both the arr values - # and the fill_value - out_shape = len(row_idx), len(col_idx) - out = np.empty(out_shape, dtype=dtype) - - func = _take_2d_multi_dict.get((arr.dtype.name, out.dtype.name), None) - if func is None and arr.dtype != out.dtype: - func = _take_2d_multi_dict.get((out.dtype.name, out.dtype.name), None) - if func is not None: - func = _convert_wrapper(func, out.dtype) - if func is None: - - def func(arr, indexer, out, fill_value=np.nan): - _take_2d_multi_object( - arr, indexer, out, fill_value=fill_value, mask_info=mask_info - ) - - func(arr, indexer, out=out, fill_value=fill_value) - return out - - # ------------ # # searchsorted # # ------------ # diff --git a/pandas/core/array_algos/take.py b/pandas/core/array_algos/take.py new file mode 100644 index 0000000000000..906aea0a90982 --- /dev/null +++ b/pandas/core/array_algos/take.py @@ -0,0 +1,433 @@ +from typing import Optional + +import numpy as np + +from pandas._libs import ( + algos as libalgos, + lib, +) + +from pandas.core.dtypes.cast import maybe_promote +from pandas.core.dtypes.common import ( + ensure_int64, + ensure_platform_int, +) +from pandas.core.dtypes.missing import na_value_for_dtype + +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, +) + + +def take_nd( + arr, + indexer, + axis: int = 0, + out: Optional[np.ndarray] = None, + fill_value=lib.no_default, + allow_fill: bool = True, +): + + """ + Specialized Cython take which sets NaN values in one pass + + This dispatches to ``take`` defined on ExtensionArrays. It does not + currently dispatch to ``SparseArray.take`` for sparse ``arr``. + + Parameters + ---------- + arr : array-like + Input array. + indexer : ndarray + 1-D array of indices to take, subarrays corresponding to -1 value + indices are filed with fill_value + axis : int, default 0 + Axis to take from + out : ndarray or None, default None + Optional output array, must be appropriate type to hold input and + fill_value together, if indexer has any -1 value entries; call + maybe_promote to determine this type for any fill_value + fill_value : any, default np.nan + Fill value to replace -1 values with + allow_fill : boolean, default True + If False, indexer is assumed to contain no -1 values so no filling + will be done. This short-circuits computation of a mask. Result is + undefined if allow_fill == False and -1 is present in indexer. + + Returns + ------- + subarray : array-like + May be the same type as the input, or cast to an ndarray. + """ + if fill_value is lib.no_default: + fill_value = na_value_for_dtype(arr.dtype, compat=False) + + arr = extract_array(arr, extract_numpy=True) + + if not isinstance(arr, np.ndarray): + # i.e. ExtensionArray, + # includes for EA to catch DatetimeArray, TimedeltaArray + return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) + + arr = np.asarray(arr) + + indexer, dtype, fill_value, mask_info = _take_preprocess_indexer_and_fill_value( + arr, indexer, axis, out, fill_value, allow_fill + ) + + flip_order = False + if arr.ndim == 2 and arr.flags.f_contiguous: + flip_order = True + + if flip_order: + arr = arr.T + axis = arr.ndim - axis - 1 + if out is not None: + out = out.T + + # at this point, it's guaranteed that dtype can hold both the arr values + # and the fill_value + if out is None: + out_shape_ = list(arr.shape) + out_shape_[axis] = len(indexer) + out_shape = tuple(out_shape_) + if arr.flags.f_contiguous and axis == arr.ndim - 1: + # minor tweak that can make an order-of-magnitude difference + # for dataframes initialized directly from 2-d ndarrays + # (s.t. df.values is c-contiguous and df._mgr.blocks[0] is its + # f-contiguous transpose) + out = np.empty(out_shape, dtype=dtype, order="F") + else: + out = np.empty(out_shape, dtype=dtype) + + func = _get_take_nd_function( + arr.ndim, arr.dtype, out.dtype, axis=axis, mask_info=mask_info + ) + func(arr, indexer, out, fill_value) + + if flip_order: + out = out.T + return out + + +def take_2d_multi( + arr: np.ndarray, indexer: np.ndarray, fill_value=np.nan +) -> np.ndarray: + """ + Specialized Cython take which sets NaN values in one pass. + """ + # This is only called from one place in DataFrame._reindex_multi, + # so we know indexer is well-behaved. + assert indexer is not None + assert indexer[0] is not None + assert indexer[1] is not None + + row_idx, col_idx = indexer + + row_idx = ensure_int64(row_idx) + col_idx = ensure_int64(col_idx) + indexer = row_idx, col_idx + mask_info = None + + # check for promotion based on types only (do this first because + # it's faster than computing a mask) + dtype, fill_value = maybe_promote(arr.dtype, fill_value) + if dtype != arr.dtype: + # check if promotion is actually required based on indexer + row_mask = row_idx == -1 + col_mask = col_idx == -1 + row_needs = row_mask.any() + col_needs = col_mask.any() + mask_info = (row_mask, col_mask), (row_needs, col_needs) + + if not (row_needs or col_needs): + # if not, then depromote, set fill_value to dummy + # (it won't be used but we don't want the cython code + # to crash when trying to cast it to dtype) + dtype, fill_value = arr.dtype, arr.dtype.type() + + # at this point, it's guaranteed that dtype can hold both the arr values + # and the fill_value + out_shape = len(row_idx), len(col_idx) + out = np.empty(out_shape, dtype=dtype) + + func = _take_2d_multi_dict.get((arr.dtype.name, out.dtype.name), None) + if func is None and arr.dtype != out.dtype: + func = _take_2d_multi_dict.get((out.dtype.name, out.dtype.name), None) + if func is not None: + func = _convert_wrapper(func, out.dtype) + + if func is not None: + func(arr, indexer, out=out, fill_value=fill_value) + else: + _take_2d_multi_object( + arr, indexer, out, fill_value=fill_value, mask_info=mask_info + ) + + return out + + +def _get_take_nd_function( + ndim: int, arr_dtype: np.dtype, out_dtype: np.dtype, axis: int = 0, mask_info=None +): + + if ndim <= 2: + tup = (arr_dtype.name, out_dtype.name) + if ndim == 1: + func = _take_1d_dict.get(tup, None) + elif ndim == 2: + if axis == 0: + func = _take_2d_axis0_dict.get(tup, None) + else: + func = _take_2d_axis1_dict.get(tup, None) + if func is not None: + return func + + tup = (out_dtype.name, out_dtype.name) + if ndim == 1: + func = _take_1d_dict.get(tup, None) + elif ndim == 2: + if axis == 0: + func = _take_2d_axis0_dict.get(tup, None) + else: + func = _take_2d_axis1_dict.get(tup, None) + if func is not None: + func = _convert_wrapper(func, out_dtype) + return func + + def func2(arr, indexer, out, fill_value=np.nan): + indexer = ensure_int64(indexer) + _take_nd_object( + arr, indexer, out, axis=axis, fill_value=fill_value, mask_info=mask_info + ) + + return func2 + + +def _view_wrapper(f, arr_dtype=None, out_dtype=None, fill_wrap=None): + def wrapper( + arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan + ): + if arr_dtype is not None: + arr = arr.view(arr_dtype) + if out_dtype is not None: + out = out.view(out_dtype) + if fill_wrap is not None: + fill_value = fill_wrap(fill_value) + f(arr, indexer, out, fill_value=fill_value) + + return wrapper + + +def _convert_wrapper(f, conv_dtype): + def wrapper( + arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value=np.nan + ): + if conv_dtype == object: + # GH#39755 avoid casting dt64/td64 to integers + arr = ensure_wrapped_if_datetimelike(arr) + arr = arr.astype(conv_dtype) + f(arr, indexer, out, fill_value=fill_value) + + return wrapper + + +_take_1d_dict = { + ("int8", "int8"): libalgos.take_1d_int8_int8, + ("int8", "int32"): libalgos.take_1d_int8_int32, + ("int8", "int64"): libalgos.take_1d_int8_int64, + ("int8", "float64"): libalgos.take_1d_int8_float64, + ("int16", "int16"): libalgos.take_1d_int16_int16, + ("int16", "int32"): libalgos.take_1d_int16_int32, + ("int16", "int64"): libalgos.take_1d_int16_int64, + ("int16", "float64"): libalgos.take_1d_int16_float64, + ("int32", "int32"): libalgos.take_1d_int32_int32, + ("int32", "int64"): libalgos.take_1d_int32_int64, + ("int32", "float64"): libalgos.take_1d_int32_float64, + ("int64", "int64"): libalgos.take_1d_int64_int64, + ("int64", "float64"): libalgos.take_1d_int64_float64, + ("float32", "float32"): libalgos.take_1d_float32_float32, + ("float32", "float64"): libalgos.take_1d_float32_float64, + ("float64", "float64"): libalgos.take_1d_float64_float64, + ("object", "object"): libalgos.take_1d_object_object, + ("bool", "bool"): _view_wrapper(libalgos.take_1d_bool_bool, np.uint8, np.uint8), + ("bool", "object"): _view_wrapper(libalgos.take_1d_bool_object, np.uint8, None), + ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( + libalgos.take_1d_int64_int64, np.int64, np.int64, np.int64 + ), +} + +_take_2d_axis0_dict = { + ("int8", "int8"): libalgos.take_2d_axis0_int8_int8, + ("int8", "int32"): libalgos.take_2d_axis0_int8_int32, + ("int8", "int64"): libalgos.take_2d_axis0_int8_int64, + ("int8", "float64"): libalgos.take_2d_axis0_int8_float64, + ("int16", "int16"): libalgos.take_2d_axis0_int16_int16, + ("int16", "int32"): libalgos.take_2d_axis0_int16_int32, + ("int16", "int64"): libalgos.take_2d_axis0_int16_int64, + ("int16", "float64"): libalgos.take_2d_axis0_int16_float64, + ("int32", "int32"): libalgos.take_2d_axis0_int32_int32, + ("int32", "int64"): libalgos.take_2d_axis0_int32_int64, + ("int32", "float64"): libalgos.take_2d_axis0_int32_float64, + ("int64", "int64"): libalgos.take_2d_axis0_int64_int64, + ("int64", "float64"): libalgos.take_2d_axis0_int64_float64, + ("float32", "float32"): libalgos.take_2d_axis0_float32_float32, + ("float32", "float64"): libalgos.take_2d_axis0_float32_float64, + ("float64", "float64"): libalgos.take_2d_axis0_float64_float64, + ("object", "object"): libalgos.take_2d_axis0_object_object, + ("bool", "bool"): _view_wrapper( + libalgos.take_2d_axis0_bool_bool, np.uint8, np.uint8 + ), + ("bool", "object"): _view_wrapper( + libalgos.take_2d_axis0_bool_object, np.uint8, None + ), + ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( + libalgos.take_2d_axis0_int64_int64, np.int64, np.int64, fill_wrap=np.int64 + ), +} + +_take_2d_axis1_dict = { + ("int8", "int8"): libalgos.take_2d_axis1_int8_int8, + ("int8", "int32"): libalgos.take_2d_axis1_int8_int32, + ("int8", "int64"): libalgos.take_2d_axis1_int8_int64, + ("int8", "float64"): libalgos.take_2d_axis1_int8_float64, + ("int16", "int16"): libalgos.take_2d_axis1_int16_int16, + ("int16", "int32"): libalgos.take_2d_axis1_int16_int32, + ("int16", "int64"): libalgos.take_2d_axis1_int16_int64, + ("int16", "float64"): libalgos.take_2d_axis1_int16_float64, + ("int32", "int32"): libalgos.take_2d_axis1_int32_int32, + ("int32", "int64"): libalgos.take_2d_axis1_int32_int64, + ("int32", "float64"): libalgos.take_2d_axis1_int32_float64, + ("int64", "int64"): libalgos.take_2d_axis1_int64_int64, + ("int64", "float64"): libalgos.take_2d_axis1_int64_float64, + ("float32", "float32"): libalgos.take_2d_axis1_float32_float32, + ("float32", "float64"): libalgos.take_2d_axis1_float32_float64, + ("float64", "float64"): libalgos.take_2d_axis1_float64_float64, + ("object", "object"): libalgos.take_2d_axis1_object_object, + ("bool", "bool"): _view_wrapper( + libalgos.take_2d_axis1_bool_bool, np.uint8, np.uint8 + ), + ("bool", "object"): _view_wrapper( + libalgos.take_2d_axis1_bool_object, np.uint8, None + ), + ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( + libalgos.take_2d_axis1_int64_int64, np.int64, np.int64, fill_wrap=np.int64 + ), +} + +_take_2d_multi_dict = { + ("int8", "int8"): libalgos.take_2d_multi_int8_int8, + ("int8", "int32"): libalgos.take_2d_multi_int8_int32, + ("int8", "int64"): libalgos.take_2d_multi_int8_int64, + ("int8", "float64"): libalgos.take_2d_multi_int8_float64, + ("int16", "int16"): libalgos.take_2d_multi_int16_int16, + ("int16", "int32"): libalgos.take_2d_multi_int16_int32, + ("int16", "int64"): libalgos.take_2d_multi_int16_int64, + ("int16", "float64"): libalgos.take_2d_multi_int16_float64, + ("int32", "int32"): libalgos.take_2d_multi_int32_int32, + ("int32", "int64"): libalgos.take_2d_multi_int32_int64, + ("int32", "float64"): libalgos.take_2d_multi_int32_float64, + ("int64", "int64"): libalgos.take_2d_multi_int64_int64, + ("int64", "float64"): libalgos.take_2d_multi_int64_float64, + ("float32", "float32"): libalgos.take_2d_multi_float32_float32, + ("float32", "float64"): libalgos.take_2d_multi_float32_float64, + ("float64", "float64"): libalgos.take_2d_multi_float64_float64, + ("object", "object"): libalgos.take_2d_multi_object_object, + ("bool", "bool"): _view_wrapper( + libalgos.take_2d_multi_bool_bool, np.uint8, np.uint8 + ), + ("bool", "object"): _view_wrapper( + libalgos.take_2d_multi_bool_object, np.uint8, None + ), + ("datetime64[ns]", "datetime64[ns]"): _view_wrapper( + libalgos.take_2d_multi_int64_int64, np.int64, np.int64, fill_wrap=np.int64 + ), +} + + +def _take_nd_object( + arr: np.ndarray, + indexer: np.ndarray, + out: np.ndarray, + axis: int, + fill_value, + mask_info, +): + if mask_info is not None: + mask, needs_masking = mask_info + else: + mask = indexer == -1 + needs_masking = mask.any() + if arr.dtype != out.dtype: + arr = arr.astype(out.dtype) + if arr.shape[axis] > 0: + arr.take(ensure_platform_int(indexer), axis=axis, out=out) + if needs_masking: + outindexer = [slice(None)] * arr.ndim + outindexer[axis] = mask + out[tuple(outindexer)] = fill_value + + +def _take_2d_multi_object( + arr: np.ndarray, indexer: np.ndarray, out: np.ndarray, fill_value, mask_info +) -> None: + # this is not ideal, performance-wise, but it's better than raising + # an exception (best to optimize in Cython to avoid getting here) + row_idx, col_idx = indexer + if mask_info is not None: + (row_mask, col_mask), (row_needs, col_needs) = mask_info + else: + row_mask = row_idx == -1 + col_mask = col_idx == -1 + row_needs = row_mask.any() + col_needs = col_mask.any() + if fill_value is not None: + if row_needs: + out[row_mask, :] = fill_value + if col_needs: + out[:, col_mask] = fill_value + for i in range(len(row_idx)): + u_ = row_idx[i] + for j in range(len(col_idx)): + v = col_idx[j] + out[i, j] = arr[u_, v] + + +def _take_preprocess_indexer_and_fill_value( + arr: np.ndarray, + indexer: Optional[np.ndarray], + axis: int, + out: Optional[np.ndarray], + fill_value, + allow_fill: bool, +): + mask_info = None + + if indexer is None: + indexer = np.arange(arr.shape[axis], dtype=np.int64) + dtype, fill_value = arr.dtype, arr.dtype.type() + else: + indexer = ensure_int64(indexer, copy=False) + if not allow_fill: + dtype, fill_value = arr.dtype, arr.dtype.type() + mask_info = None, False + else: + # check for promotion based on types only (do this first because + # it's faster than computing a mask) + dtype, fill_value = maybe_promote(arr.dtype, fill_value) + if dtype != arr.dtype and (out is None or out.dtype != dtype): + # check if promotion is actually required based on indexer + mask = indexer == -1 + needs_masking = mask.any() + mask_info = mask, needs_masking + if needs_masking: + if out is not None and out.dtype != dtype: + raise TypeError("Incompatible type for fill_value") + else: + # if not, then depromote, set fill_value to dummy + # (it won't be used but we don't want the cython code + # to crash when trying to cast it to dtype) + dtype, fill_value = arr.dtype, arr.dtype.type() + + return indexer, dtype, fill_value, mask_info diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 7a216e411dcc2..da15fd2a7d646 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -141,6 +141,7 @@ relabel_result, transform, ) +from pandas.core.array_algos.take import take_2d_multi from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ExtensionArray from pandas.core.arrays.sparse import SparseFrameAccessor @@ -4186,9 +4187,7 @@ def _reindex_multi(self, axes, copy: bool, fill_value) -> DataFrame: if row_indexer is not None and col_indexer is not None: indexer = row_indexer, col_indexer - new_values = algorithms.take_2d_multi( - self.values, indexer, fill_value=fill_value - ) + new_values = take_2d_multi(self.values, indexer, fill_value=fill_value) return self._constructor(new_values, index=new_index, columns=new_columns) else: return self._reindex_with_indexers(
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39948
2021-02-21T02:08:06Z
2021-02-23T13:26:22Z
2021-02-23T13:26:22Z
2021-02-23T14:55:35Z
TYP: stubfile for _libs.lib
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi new file mode 100644 index 0000000000000..dcb8677ce1e7e --- /dev/null +++ b/pandas/_libs/lib.pyi @@ -0,0 +1,176 @@ +from typing import ( + Any, + Tuple, + Union, +) + +import numpy as np + +from pandas._typing import ArrayLike + +# placeholder until we can specify np.ndarray[object, ndim=2] +ndarray_obj_2d = np.ndarray + +no_default: object + +def item_from_zerodim(val: object) -> object: ... +def infer_dtype(value: object, skipna: bool = True) -> str: ... + +def is_iterator(obj: object) -> bool: ... +def is_scalar(val: object) -> bool: ... +def is_list_like(obj: object, allow_sets: bool = True) -> bool: ... + +def is_period(val: object) -> bool: ... +def is_interval(val: object) -> bool: ... +def is_decimal(val: object) -> bool: ... +def is_complex(val: object) -> bool: ... +def is_bool(val: object) -> bool: ... +def is_integer(val: object) -> bool: ... +def is_float(val: object) -> bool: ... + +def is_interval_array(values: np.ndarray) -> bool: ... +def is_period_array(values: np.ndarray) -> bool: ... +def is_datetime64_array(values: np.ndarray) -> bool: ... +def is_timedelta_or_timedelta64_array(values: np.ndarray) -> bool: ... +def is_datetime_with_singletz_array(values: np.ndarray) -> bool: ... + +def is_time_array(values: np.ndarray, skipna: bool = False): ... +def is_date_array(values: np.ndarray, skipna: bool = False): ... +def is_datetime_array(values: np.ndarray, skipna: bool = False): ... +def is_string_array(values: np.ndarray, skipna: bool = False): ... +def is_float_array(values: np.ndarray, skipna: bool = False): ... +def is_integer_array(values: np.ndarray, skipna: bool = False): ... +def is_bool_array(values: np.ndarray, skipna: bool = False): ... + +def fast_multiget(mapping: dict, keys: np.ndarray, default=np.nan) -> ArrayLike: ... + +# TODO: gen: Generator? +def fast_unique_multiple_list_gen(gen: object, sort: bool = True) -> list: ... +def fast_unique_multiple_list(lists: list, sort: bool = True) -> list: ... +def fast_unique_multiple(arrays: list, sort: bool = True) -> list: ... + +# TODO: f: Callable? +def map_infer( + arr: np.ndarray, f: object, convert: bool = True, ignore_na: bool = False +) -> ArrayLike: ... + +def maybe_convert_objects( + objects: np.ndarray[object], + try_float: bool = False, + safe: bool = False, + convert_datetime: bool = False, + convert_timedelta: bool = False, + convert_to_nullable_integer: bool = False, +) -> ArrayLike: ... + +def maybe_convert_numeric( + values: np.ndarray[object], + na_values: set, + convert_empty: bool = True, + coerce_numeric: bool = False, +) -> np.ndarray: ... + +# TODO: restrict `arr`? +def ensure_string_array( + arr, + na_value: object = np.nan, + convert_na_value: bool = True, + copy: bool = True, + skipna: bool = True, +) -> np.ndarray[object]: ... + +def infer_datetimelike_array(arr: np.ndarray[object]) -> str: ... + +# TODO: new_dtype -> np.dtype? +def astype_intsafe(arr: np.ndarray[object], new_dtype) -> np.ndarray: ... + +def fast_zip(ndarrays: list) -> np.ndarray[object]: ... + +# TODO: can we be more specific about rows? +def to_object_array_tuples(rows: object) -> ndarray_obj_2d: ... + +def tuples_to_object_array(tuples: np.ndarray[object]) -> ndarray_obj_2d: ... + +# TODO: can we be more specific about rows? +def to_object_array(rows: object, min_width: int = 0) -> ndarray_obj_2d: ... + +def dicts_to_array(dicts: list, columns: list) -> ndarray_obj_2d: ... + + +def maybe_booleans_to_slice( + mask: np.ndarray[np.uint8] +) -> Union[slice, np.ndarray[np.uint8]]: ... + +def maybe_indices_to_slice( + indices: np.ndarray[np.intp], max_len: int +) -> Union[slice, np.ndarray[np.intp]]: ... + +def clean_index_list(obj: list) -> Tuple[Union[list, np.ndarray], bool]: ... + + +# ----------------------------------------------------------------- +# Functions for which we lie, using ndarray[foo] in place of foo[:] + +# actually object[:] +def memory_usage_of_objects(arr: np.ndarray[object]) -> np.int64: ... + + +# TODO: f: Callable? +# TODO: dtype -> DtypeObj? +def map_infer_mask( + arr: np.ndarray, + f: object, + mask: np.ndarray[np.uint8], # actually const uint8_t[:] + convert: bool = True, + na_value: Any = no_default, + dtype: Any = object, +) -> ArrayLike: ... + +def indices_fast( + index: np.ndarray, + labels: np.ndarray[np.int64], # actually const int64_t[:] + keys: list, + sorted_labels: list, +) -> dict: ... + +def generate_slices( + labels: np.ndarray[np.int64], # actually const int64_t[:] + ngroups: int +) -> Tuple[np.ndarray[np.int64], np.ndarray[np.int64]]: ... + +def count_level_2d( + mask: np.ndarray[np.uint8], # actually ndarray[uint8_t, ndim=2, cast=True], + labels: np.ndarray[np.int64], # actually const int64_t[:] + max_bin: int, + axis: int +) -> np.ndarray[np.int64]: ... # actually np.ndarray[np.int64, ndim=2] + +def get_level_sorter( + label: np.ndarray[np.int64], # actually const int64_t[:] + starts: np.ndarray[np.int64], # actually const int64_t[:] +) -> np.ndarray[np.int64]: ... # actually np.ndarray[np.int64, ndim=1] + + +def generate_bins_dt64( + values: np.ndarray[np.int64], + binner: np.ndarray[np.int64], # actually const int64_t[:] + closed: object = "left", + hasnans: bool = False, +) -> np.ndarray[np.int64]: ... # actually np.ndarray[np.int64, ndim=1] + + +# actually object[:] for both args +def array_equivalent_object( + left: np.ndarray[object], right: np.ndarray[object] +) -> bool: ... + +# actually const float64_t[:] +def has_infs_f8(arr: np.ndarray[np.float64]) -> bool: ... + +# actually const float32_t[:] +def has_infs_f4(arr: np.ndarray[np.float32]) -> bool: ... + +def get_reverse_indexer( + indexer: np.ndarray[np.int64], # actually const int64_t[:] + length: int, +) -> np.ndarray[np.int64]: ... diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 9f2c82d760785..f6d4c9805e0b7 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -269,7 +269,7 @@ def item_from_zerodim(val: object) -> object: @cython.wraparound(False) @cython.boundscheck(False) -def fast_unique_multiple(list arrays, sort: bool = True): +def fast_unique_multiple(list arrays, sort: bool = True) -> list: """ Generate a list of unique values from a list of arrays. @@ -345,7 +345,7 @@ def fast_unique_multiple_list(lists: list, sort: bool = True) -> list: @cython.wraparound(False) @cython.boundscheck(False) -def fast_unique_multiple_list_gen(object gen, bint sort=True): +def fast_unique_multiple_list_gen(object gen, bint sort=True) -> list: """ Generate a list of unique values from a generator of lists. @@ -409,7 +409,7 @@ def dicts_to_array(dicts: list, columns: list): return result -def fast_zip(list ndarrays): +def fast_zip(list ndarrays) -> ndarray[object]: """ For zipping multiple ndarrays into an ndarray of tuples. """ @@ -621,7 +621,7 @@ def array_equivalent_object(left: object[:], right: object[:]) -> bool: @cython.wraparound(False) @cython.boundscheck(False) -def astype_intsafe(ndarray[object] arr, new_dtype): +def astype_intsafe(ndarray[object] arr, new_dtype) -> ndarray: cdef: Py_ssize_t i, n = len(arr) object val @@ -891,7 +891,7 @@ def generate_slices(const int64_t[:] labels, Py_ssize_t ngroups): def indices_fast(ndarray index, const int64_t[:] labels, list keys, - list sorted_labels): + list sorted_labels) -> dict: """ Parameters ---------- @@ -1979,8 +1979,12 @@ cpdef bint is_interval_array(ndarray values): @cython.boundscheck(False) @cython.wraparound(False) -def maybe_convert_numeric(ndarray[object] values, set na_values, - bint convert_empty=True, bint coerce_numeric=False): +def maybe_convert_numeric( + ndarray[object] values, + set na_values, + bint convert_empty=True, + bint coerce_numeric=False, +) -> ndarray: """ Convert object array to a numeric array if possible. @@ -2007,7 +2011,8 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, Returns ------- - Array of converted object values to numerical ones. + np.ndarray + Array of converted object values to numerical ones. """ if len(values) == 0: return np.array([], dtype='i8') @@ -2153,7 +2158,7 @@ def maybe_convert_numeric(ndarray[object] values, set na_values, def maybe_convert_objects(ndarray[object] objects, bint try_float=False, bint safe=False, bint convert_datetime=False, bint convert_timedelta=False, - bint convert_to_nullable_integer=False): + bint convert_to_nullable_integer=False) -> "ArrayLike": """ Type inference function-- convert object array to proper dtype @@ -2179,7 +2184,8 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, Returns ------- - Array of converted object values to more specific dtypes if applicable. + np.ndarray or ExtensionArray + Array of converted object values to more specific dtypes if applicable. """ cdef: Py_ssize_t i, n @@ -2309,7 +2315,7 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, if seen.datetimetz_: if is_datetime_with_singletz_array(objects): from pandas import DatetimeIndex - return DatetimeIndex(objects) + return DatetimeIndex(objects)._data seen.object_ = True if not seen.object_: @@ -2404,13 +2410,13 @@ def maybe_convert_objects(ndarray[object] objects, bint try_float=False, # Note: no_default is exported to the public API in pandas.api.extensions -no_default = object() #: Sentinel indicating the default value. +no_default = object() # Sentinel indicating the default value. @cython.boundscheck(False) @cython.wraparound(False) def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=True, - object na_value=no_default, object dtype=object): + object na_value=no_default, object dtype=object) -> "ArrayLike": """ Substitute for np.vectorize with pandas-friendly dtype inference. @@ -2465,7 +2471,9 @@ def map_infer_mask(ndarray arr, object f, const uint8_t[:] mask, bint convert=Tr @cython.boundscheck(False) @cython.wraparound(False) -def map_infer(ndarray arr, object f, bint convert=True, bint ignore_na=False): +def map_infer( + ndarray arr, object f, bint convert=True, bint ignore_na=False +) -> "ArrayLike": """ Substitute for np.vectorize with pandas-friendly dtype inference. @@ -2479,7 +2487,7 @@ def map_infer(ndarray arr, object f, bint convert=True, bint ignore_na=False): Returns ------- - ndarray + np.ndarray or ExtensionArray """ cdef: Py_ssize_t i, n @@ -2509,7 +2517,7 @@ def map_infer(ndarray arr, object f, bint convert=True, bint ignore_na=False): return result -def to_object_array(rows: object, int min_width=0): +def to_object_array(rows: object, min_width: int = 0): """ Convert a list of lists into an object array. @@ -2525,7 +2533,7 @@ def to_object_array(rows: object, int min_width=0): Returns ------- - numpy array of the object dtype. + np.ndarray[object, ndim=2] """ cdef: Py_ssize_t i, j, n, k, tmp @@ -2581,7 +2589,7 @@ def to_object_array_tuples(rows: object): Returns ------- - numpy array of the object dtype. + np.ndarray[object, ndim=2] """ cdef: Py_ssize_t i, j, n, k, tmp @@ -2617,7 +2625,7 @@ def to_object_array_tuples(rows: object): @cython.wraparound(False) @cython.boundscheck(False) -def fast_multiget(dict mapping, ndarray keys, default=np.nan): +def fast_multiget(dict mapping, ndarray keys, default=np.nan) -> "ArrayLike": cdef: Py_ssize_t i, n = len(keys) object val diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3fe330f659513..af5f7cd4c6322 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8932,7 +8932,7 @@ def count( return result.astype("int64") - def _count_level(self, level: Level, axis: Axis = 0, numeric_only=False): + def _count_level(self, level: Level, axis: int = 0, numeric_only=False): if numeric_only: frame = self._get_numeric_data() else: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 00cb65fff3803..2efa50a7308e9 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -775,7 +775,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F): counts[label] = group.shape[0] result[label] = res - result = lib.maybe_convert_objects(result, try_float=0) + result = lib.maybe_convert_objects(result, try_float=False) result = maybe_cast_result(result, obj, numeric_only=True) return result, counts diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 71095b8f4113a..03772b41744db 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1126,7 +1126,7 @@ def _format_with_header( values = self._values if is_object_dtype(values.dtype): - values = lib.maybe_convert_objects(values, safe=1) + values = lib.maybe_convert_objects(values, safe=True) result = [pprint_thing(x, escape_chars=("\t", "\r", "\n")) for x in values]
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry cc @simonjayhawkins @Dr-Irv there are a couple of kludges (ndarray_obj_2d, const memoryviews), interested in your thoughts on how to handle these
https://api.github.com/repos/pandas-dev/pandas/pulls/39947
2021-02-21T00:37:40Z
2021-02-22T15:44:47Z
null
2021-02-22T15:44:50Z
refactor styler tests
diff --git a/pandas/tests/io/formats/style/__init__.py b/pandas/tests/io/formats/style/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/io/formats/style/test_align.py b/pandas/tests/io/formats/style/test_align.py new file mode 100644 index 0000000000000..f81c1fbd6d85e --- /dev/null +++ b/pandas/tests/io/formats/style/test_align.py @@ -0,0 +1,406 @@ +import pytest + +from pandas import DataFrame + +pytest.importorskip("jinja2") + + +def bar_grad(a=None, b=None, c=None, d=None): + """Used in multiple tests to simplify formatting of expected result""" + ret = [("width", "10em"), ("height", "80%")] + if all(x is None for x in [a, b, c, d]): + return ret + return ret + [ + ( + "background", + f"linear-gradient(90deg,{','.join(x for x in [a, b, c, d] if x)})", + ) + ] + + +class TestStylerBarAlign: + def test_bar_align_left(self): + df = DataFrame({"A": [0, 1, 2]}) + result = df.style.bar()._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (2, 0): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + } + assert result == expected + + result = df.style.bar(color="red", width=50)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad("red 25.0%", " transparent 25.0%"), + (2, 0): bar_grad("red 50.0%", " transparent 50.0%"), + } + assert result == expected + + df["C"] = ["a"] * len(df) + result = df.style.bar(color="red", width=50)._compute().ctx + assert result == expected + df["C"] = df["C"].astype("category") + result = df.style.bar(color="red", width=50)._compute().ctx + assert result == expected + + def test_bar_align_left_0points(self): + df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) + result = df.style.bar()._compute().ctx + expected = { + (0, 0): bar_grad(), + (0, 1): bar_grad(), + (0, 2): bar_grad(), + (1, 0): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (1, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (1, 2): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (2, 0): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + (2, 1): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + (2, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + } + assert result == expected + + result = df.style.bar(axis=1)._compute().ctx + expected = { + (0, 0): bar_grad(), + (0, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (0, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + (1, 0): bar_grad(), + (1, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (1, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + (2, 0): bar_grad(), + (2, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), + (2, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), + } + assert result == expected + + def test_bar_align_mid_pos_and_neg(self): + df = DataFrame({"A": [-10, 0, 20, 90]}) + result = df.style.bar(align="mid", color=["#d65f5f", "#5fba7d"])._compute().ctx + expected = { + (0, 0): bar_grad( + "#d65f5f 10.0%", + " transparent 10.0%", + ), + (1, 0): bar_grad(), + (2, 0): bar_grad( + " transparent 10.0%", + " #5fba7d 10.0%", + " #5fba7d 30.0%", + " transparent 30.0%", + ), + (3, 0): bar_grad( + " transparent 10.0%", + " #5fba7d 10.0%", + " #5fba7d 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_mid_all_pos(self): + df = DataFrame({"A": [10, 20, 50, 100]}) + + result = df.style.bar(align="mid", color=["#d65f5f", "#5fba7d"])._compute().ctx + + expected = { + (0, 0): bar_grad( + "#5fba7d 10.0%", + " transparent 10.0%", + ), + (1, 0): bar_grad( + "#5fba7d 20.0%", + " transparent 20.0%", + ), + (2, 0): bar_grad( + "#5fba7d 50.0%", + " transparent 50.0%", + ), + (3, 0): bar_grad( + "#5fba7d 100.0%", + " transparent 100.0%", + ), + } + + assert result == expected + + def test_bar_align_mid_all_neg(self): + df = DataFrame({"A": [-100, -60, -30, -20]}) + + result = df.style.bar(align="mid", color=["#d65f5f", "#5fba7d"])._compute().ctx + + expected = { + (0, 0): bar_grad( + "#d65f5f 100.0%", + " transparent 100.0%", + ), + (1, 0): bar_grad( + " transparent 40.0%", + " #d65f5f 40.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + (2, 0): bar_grad( + " transparent 70.0%", + " #d65f5f 70.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + (3, 0): bar_grad( + " transparent 80.0%", + " #d65f5f 80.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_zero_pos_and_neg(self): + # See https://github.com/pandas-dev/pandas/pull/14757 + df = DataFrame({"A": [-10, 0, 20, 90]}) + + result = ( + df.style.bar(align="zero", color=["#d65f5f", "#5fba7d"], width=90) + ._compute() + .ctx + ) + expected = { + (0, 0): bar_grad( + " transparent 40.0%", + " #d65f5f 40.0%", + " #d65f5f 45.0%", + " transparent 45.0%", + ), + (1, 0): bar_grad(), + (2, 0): bar_grad( + " transparent 45.0%", + " #5fba7d 45.0%", + " #5fba7d 55.0%", + " transparent 55.0%", + ), + (3, 0): bar_grad( + " transparent 45.0%", + " #5fba7d 45.0%", + " #5fba7d 90.0%", + " transparent 90.0%", + ), + } + assert result == expected + + def test_bar_align_left_axis_none(self): + df = DataFrame({"A": [0, 1], "B": [2, 4]}) + result = df.style.bar(axis=None)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + "#d65f5f 25.0%", + " transparent 25.0%", + ), + (0, 1): bar_grad( + "#d65f5f 50.0%", + " transparent 50.0%", + ), + (1, 1): bar_grad( + "#d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_zero_axis_none(self): + df = DataFrame({"A": [0, 1], "B": [-2, 4]}) + result = df.style.bar(align="zero", axis=None)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + " transparent 50.0%", + " #d65f5f 50.0%", + " #d65f5f 62.5%", + " transparent 62.5%", + ), + (0, 1): bar_grad( + " transparent 25.0%", + " #d65f5f 25.0%", + " #d65f5f 50.0%", + " transparent 50.0%", + ), + (1, 1): bar_grad( + " transparent 50.0%", + " #d65f5f 50.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_mid_axis_none(self): + df = DataFrame({"A": [0, 1], "B": [-2, 4]}) + result = df.style.bar(align="mid", axis=None)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + " transparent 33.3%", + " #d65f5f 33.3%", + " #d65f5f 50.0%", + " transparent 50.0%", + ), + (0, 1): bar_grad( + "#d65f5f 33.3%", + " transparent 33.3%", + ), + (1, 1): bar_grad( + " transparent 33.3%", + " #d65f5f 33.3%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_mid_vmin(self): + df = DataFrame({"A": [0, 1], "B": [-2, 4]}) + result = df.style.bar(align="mid", axis=None, vmin=-6)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + " transparent 60.0%", + " #d65f5f 60.0%", + " #d65f5f 70.0%", + " transparent 70.0%", + ), + (0, 1): bar_grad( + " transparent 40.0%", + " #d65f5f 40.0%", + " #d65f5f 60.0%", + " transparent 60.0%", + ), + (1, 1): bar_grad( + " transparent 60.0%", + " #d65f5f 60.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_mid_vmax(self): + df = DataFrame({"A": [0, 1], "B": [-2, 4]}) + result = df.style.bar(align="mid", axis=None, vmax=8)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + " transparent 20.0%", + " #d65f5f 20.0%", + " #d65f5f 30.0%", + " transparent 30.0%", + ), + (0, 1): bar_grad( + "#d65f5f 20.0%", + " transparent 20.0%", + ), + (1, 1): bar_grad( + " transparent 20.0%", + " #d65f5f 20.0%", + " #d65f5f 60.0%", + " transparent 60.0%", + ), + } + assert result == expected + + def test_bar_align_mid_vmin_vmax_wide(self): + df = DataFrame({"A": [0, 1], "B": [-2, 4]}) + result = df.style.bar(align="mid", axis=None, vmin=-3, vmax=7)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + " transparent 30.0%", + " #d65f5f 30.0%", + " #d65f5f 40.0%", + " transparent 40.0%", + ), + (0, 1): bar_grad( + " transparent 10.0%", + " #d65f5f 10.0%", + " #d65f5f 30.0%", + " transparent 30.0%", + ), + (1, 1): bar_grad( + " transparent 30.0%", + " #d65f5f 30.0%", + " #d65f5f 70.0%", + " transparent 70.0%", + ), + } + assert result == expected + + def test_bar_align_mid_vmin_vmax_clipping(self): + df = DataFrame({"A": [0, 1], "B": [-2, 4]}) + result = df.style.bar(align="mid", axis=None, vmin=-1, vmax=3)._compute().ctx + expected = { + (0, 0): bar_grad(), + (1, 0): bar_grad( + " transparent 25.0%", + " #d65f5f 25.0%", + " #d65f5f 50.0%", + " transparent 50.0%", + ), + (0, 1): bar_grad("#d65f5f 25.0%", " transparent 25.0%"), + (1, 1): bar_grad( + " transparent 25.0%", + " #d65f5f 25.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_mid_nans(self): + df = DataFrame({"A": [1, None], "B": [-1, 3]}) + result = df.style.bar(align="mid", axis=None)._compute().ctx + expected = { + (0, 0): bar_grad( + " transparent 25.0%", + " #d65f5f 25.0%", + " #d65f5f 50.0%", + " transparent 50.0%", + ), + (0, 1): bar_grad("#d65f5f 25.0%", " transparent 25.0%"), + (1, 1): bar_grad( + " transparent 25.0%", + " #d65f5f 25.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_align_zero_nans(self): + df = DataFrame({"A": [1, None], "B": [-1, 2]}) + result = df.style.bar(align="zero", axis=None)._compute().ctx + expected = { + (0, 0): bar_grad( + " transparent 50.0%", + " #d65f5f 50.0%", + " #d65f5f 75.0%", + " transparent 75.0%", + ), + (0, 1): bar_grad( + " transparent 25.0%", + " #d65f5f 25.0%", + " #d65f5f 50.0%", + " transparent 50.0%", + ), + (1, 1): bar_grad( + " transparent 50.0%", + " #d65f5f 50.0%", + " #d65f5f 100.0%", + " transparent 100.0%", + ), + } + assert result == expected + + def test_bar_bad_align_raises(self): + df = DataFrame({"A": [-100, -60, -30, -20]}) + msg = "`align` must be one of {'left', 'zero',' mid'}" + with pytest.raises(ValueError, match=msg): + df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]) diff --git a/pandas/tests/io/formats/style/test_highlight.py b/pandas/tests/io/formats/style/test_highlight.py new file mode 100644 index 0000000000000..e02e1f012c662 --- /dev/null +++ b/pandas/tests/io/formats/style/test_highlight.py @@ -0,0 +1,70 @@ +import numpy as np +import pytest + +from pandas import DataFrame + +pytest.importorskip("jinja2") + + +class TestStylerHighlight: + def test_highlight_null(self): + df = DataFrame({"A": [0, np.nan]}) + result = df.style.highlight_null()._compute().ctx + expected = {(1, 0): [("background-color", "red")]} + assert result == expected + + def test_highlight_null_subset(self): + # GH 31345 + df = DataFrame({"A": [0, np.nan], "B": [0, np.nan]}) + result = ( + df.style.highlight_null(null_color="red", subset=["A"]) + .highlight_null(null_color="green", subset=["B"]) + ._compute() + .ctx + ) + expected = { + (1, 0): [("background-color", "red")], + (1, 1): [("background-color", "green")], + } + assert result == expected + + def test_highlight_max(self): + df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) + css_seq = [("background-color", "yellow")] + # max(df) = min(-df) + for max_ in [True, False]: + if max_: + attr = "highlight_max" + else: + df = -df + attr = "highlight_min" + result = getattr(df.style, attr)()._compute().ctx + assert result[(1, 1)] == css_seq + + result = getattr(df.style, attr)(color="green")._compute().ctx + assert result[(1, 1)] == [("background-color", "green")] + + result = getattr(df.style, attr)(subset="A")._compute().ctx + assert result[(1, 0)] == css_seq + + result = getattr(df.style, attr)(axis=0)._compute().ctx + expected = { + (1, 0): css_seq, + (1, 1): css_seq, + } + assert result == expected + + result = getattr(df.style, attr)(axis=1)._compute().ctx + expected = { + (0, 1): css_seq, + (1, 1): css_seq, + } + assert result == expected + + # separate since we can't negate the strs + df["C"] = ["a", "b"] + result = df.style.highlight_max()._compute().ctx + expected = {(1, 1): css_seq} + + result = df.style.highlight_min()._compute().ctx + expected = {(0, 0): css_seq} diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py new file mode 100644 index 0000000000000..f01e818e40b22 --- /dev/null +++ b/pandas/tests/io/formats/style/test_matplotlib.py @@ -0,0 +1,108 @@ +import numpy as np +import pytest + +from pandas import ( + DataFrame, + IndexSlice, + Series, +) + +pytest.importorskip("matplotlib") +pytest.importorskip("jinja2") + + +class TestStylerMatplotlibDep: + def test_background_gradient(self): + df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) + + for c_map in [None, "YlOrRd"]: + result = df.style.background_gradient(cmap=c_map)._compute().ctx + assert all("#" in x[0][1] for x in result.values()) + assert result[(0, 0)] == result[(0, 1)] + assert result[(1, 0)] == result[(1, 1)] + + result = df.style.background_gradient(subset=IndexSlice[1, "A"])._compute().ctx + + assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")] + + @pytest.mark.parametrize( + "cmap, expected", + [ + ( + "PuBu", + { + (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")], + (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")], + }, + ), + ( + "YlOrRd", + { + (4, 8): [("background-color", "#fd913e"), ("color", "#000000")], + (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")], + }, + ), + ( + None, + { + (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")], + (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")], + }, + ), + ], + ) + def test_text_color_threshold(self, cmap, expected): + df = DataFrame(np.arange(100).reshape(10, 10)) + result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx + for k in expected.keys(): + assert result[k] == expected[k] + + @pytest.mark.parametrize("text_color_threshold", [1.1, "1", -1, [2, 2]]) + def test_text_color_threshold_raises(self, text_color_threshold): + df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) + msg = "`text_color_threshold` must be a value from 0 to 1." + with pytest.raises(ValueError, match=msg): + df.style.background_gradient( + text_color_threshold=text_color_threshold + )._compute() + + def test_background_gradient_axis(self): + df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) + + low = [("background-color", "#f7fbff"), ("color", "#000000")] + high = [("background-color", "#08306b"), ("color", "#f1f1f1")] + mid = [("background-color", "#abd0e6"), ("color", "#000000")] + result = df.style.background_gradient(cmap="Blues", axis=0)._compute().ctx + assert result[(0, 0)] == low + assert result[(0, 1)] == low + assert result[(1, 0)] == high + assert result[(1, 1)] == high + + result = df.style.background_gradient(cmap="Blues", axis=1)._compute().ctx + assert result[(0, 0)] == low + assert result[(0, 1)] == high + assert result[(1, 0)] == low + assert result[(1, 1)] == high + + result = df.style.background_gradient(cmap="Blues", axis=None)._compute().ctx + assert result[(0, 0)] == low + assert result[(0, 1)] == mid + assert result[(1, 0)] == mid + assert result[(1, 1)] == high + + def test_background_gradient_vmin_vmax(self): + # GH 12145 + df = DataFrame(range(5)) + ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx + assert ctx[(0, 0)] == ctx[(1, 0)] + assert ctx[(4, 0)] == ctx[(3, 0)] + + def test_background_gradient_int64(self): + # GH 28869 + df1 = Series(range(3)).to_frame() + df2 = Series(range(3), dtype="Int64").to_frame() + ctx1 = df1.style.background_gradient()._compute().ctx + ctx2 = df2.style.background_gradient()._compute().ctx + assert ctx2[(0, 0)] == ctx1[(0, 0)] + assert ctx2[(1, 0)] == ctx1[(1, 0)] + assert ctx2[(2, 0)] == ctx1[(2, 0)] diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/style/test_style.py similarity index 69% rename from pandas/tests/io/formats/test_style.py rename to pandas/tests/io/formats/style/test_style.py index 66dc1cd4adddd..01ed234f6e248 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -5,8 +5,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import DataFrame import pandas._testing as tm @@ -20,19 +18,6 @@ ) -def bar_grad(a=None, b=None, c=None, d=None): - """Used in multiple tests to simplify formatting of expected result""" - ret = [("width", "10em"), ("height", "80%")] - if all(x is None for x in [a, b, c, d]): - return ret - return ret + [ - ( - "background", - f"linear-gradient(90deg,{','.join(x for x in [a, b, c, d] if x)})", - ) - ] - - class TestStyler: def setup_method(self, method): np.random.seed(24) @@ -517,392 +502,6 @@ def test_duplicate(self): ] assert result == expected - def test_bar_align_left(self): - df = DataFrame({"A": [0, 1, 2]}) - result = df.style.bar()._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (2, 0): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - } - assert result == expected - - result = df.style.bar(color="red", width=50)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad("red 25.0%", " transparent 25.0%"), - (2, 0): bar_grad("red 50.0%", " transparent 50.0%"), - } - assert result == expected - - df["C"] = ["a"] * len(df) - result = df.style.bar(color="red", width=50)._compute().ctx - assert result == expected - df["C"] = df["C"].astype("category") - result = df.style.bar(color="red", width=50)._compute().ctx - assert result == expected - - def test_bar_align_left_0points(self): - df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) - result = df.style.bar()._compute().ctx - expected = { - (0, 0): bar_grad(), - (0, 1): bar_grad(), - (0, 2): bar_grad(), - (1, 0): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (1, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (1, 2): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (2, 0): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - (2, 1): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - (2, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - } - assert result == expected - - result = df.style.bar(axis=1)._compute().ctx - expected = { - (0, 0): bar_grad(), - (0, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (0, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - (1, 0): bar_grad(), - (1, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (1, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - (2, 0): bar_grad(), - (2, 1): bar_grad("#d65f5f 50.0%", " transparent 50.0%"), - (2, 2): bar_grad("#d65f5f 100.0%", " transparent 100.0%"), - } - assert result == expected - - def test_bar_align_mid_pos_and_neg(self): - df = DataFrame({"A": [-10, 0, 20, 90]}) - result = df.style.bar(align="mid", color=["#d65f5f", "#5fba7d"])._compute().ctx - expected = { - (0, 0): bar_grad( - "#d65f5f 10.0%", - " transparent 10.0%", - ), - (1, 0): bar_grad(), - (2, 0): bar_grad( - " transparent 10.0%", - " #5fba7d 10.0%", - " #5fba7d 30.0%", - " transparent 30.0%", - ), - (3, 0): bar_grad( - " transparent 10.0%", - " #5fba7d 10.0%", - " #5fba7d 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_mid_all_pos(self): - df = DataFrame({"A": [10, 20, 50, 100]}) - - result = df.style.bar(align="mid", color=["#d65f5f", "#5fba7d"])._compute().ctx - - expected = { - (0, 0): bar_grad( - "#5fba7d 10.0%", - " transparent 10.0%", - ), - (1, 0): bar_grad( - "#5fba7d 20.0%", - " transparent 20.0%", - ), - (2, 0): bar_grad( - "#5fba7d 50.0%", - " transparent 50.0%", - ), - (3, 0): bar_grad( - "#5fba7d 100.0%", - " transparent 100.0%", - ), - } - - assert result == expected - - def test_bar_align_mid_all_neg(self): - df = DataFrame({"A": [-100, -60, -30, -20]}) - - result = df.style.bar(align="mid", color=["#d65f5f", "#5fba7d"])._compute().ctx - - expected = { - (0, 0): bar_grad( - "#d65f5f 100.0%", - " transparent 100.0%", - ), - (1, 0): bar_grad( - " transparent 40.0%", - " #d65f5f 40.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - (2, 0): bar_grad( - " transparent 70.0%", - " #d65f5f 70.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - (3, 0): bar_grad( - " transparent 80.0%", - " #d65f5f 80.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_zero_pos_and_neg(self): - # See https://github.com/pandas-dev/pandas/pull/14757 - df = DataFrame({"A": [-10, 0, 20, 90]}) - - result = ( - df.style.bar(align="zero", color=["#d65f5f", "#5fba7d"], width=90) - ._compute() - .ctx - ) - expected = { - (0, 0): bar_grad( - " transparent 40.0%", - " #d65f5f 40.0%", - " #d65f5f 45.0%", - " transparent 45.0%", - ), - (1, 0): bar_grad(), - (2, 0): bar_grad( - " transparent 45.0%", - " #5fba7d 45.0%", - " #5fba7d 55.0%", - " transparent 55.0%", - ), - (3, 0): bar_grad( - " transparent 45.0%", - " #5fba7d 45.0%", - " #5fba7d 90.0%", - " transparent 90.0%", - ), - } - assert result == expected - - def test_bar_align_left_axis_none(self): - df = DataFrame({"A": [0, 1], "B": [2, 4]}) - result = df.style.bar(axis=None)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - "#d65f5f 25.0%", - " transparent 25.0%", - ), - (0, 1): bar_grad( - "#d65f5f 50.0%", - " transparent 50.0%", - ), - (1, 1): bar_grad( - "#d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_zero_axis_none(self): - df = DataFrame({"A": [0, 1], "B": [-2, 4]}) - result = df.style.bar(align="zero", axis=None)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - " transparent 50.0%", - " #d65f5f 50.0%", - " #d65f5f 62.5%", - " transparent 62.5%", - ), - (0, 1): bar_grad( - " transparent 25.0%", - " #d65f5f 25.0%", - " #d65f5f 50.0%", - " transparent 50.0%", - ), - (1, 1): bar_grad( - " transparent 50.0%", - " #d65f5f 50.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_mid_axis_none(self): - df = DataFrame({"A": [0, 1], "B": [-2, 4]}) - result = df.style.bar(align="mid", axis=None)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - " transparent 33.3%", - " #d65f5f 33.3%", - " #d65f5f 50.0%", - " transparent 50.0%", - ), - (0, 1): bar_grad( - "#d65f5f 33.3%", - " transparent 33.3%", - ), - (1, 1): bar_grad( - " transparent 33.3%", - " #d65f5f 33.3%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_mid_vmin(self): - df = DataFrame({"A": [0, 1], "B": [-2, 4]}) - result = df.style.bar(align="mid", axis=None, vmin=-6)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - " transparent 60.0%", - " #d65f5f 60.0%", - " #d65f5f 70.0%", - " transparent 70.0%", - ), - (0, 1): bar_grad( - " transparent 40.0%", - " #d65f5f 40.0%", - " #d65f5f 60.0%", - " transparent 60.0%", - ), - (1, 1): bar_grad( - " transparent 60.0%", - " #d65f5f 60.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_mid_vmax(self): - df = DataFrame({"A": [0, 1], "B": [-2, 4]}) - result = df.style.bar(align="mid", axis=None, vmax=8)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - " transparent 20.0%", - " #d65f5f 20.0%", - " #d65f5f 30.0%", - " transparent 30.0%", - ), - (0, 1): bar_grad( - "#d65f5f 20.0%", - " transparent 20.0%", - ), - (1, 1): bar_grad( - " transparent 20.0%", - " #d65f5f 20.0%", - " #d65f5f 60.0%", - " transparent 60.0%", - ), - } - assert result == expected - - def test_bar_align_mid_vmin_vmax_wide(self): - df = DataFrame({"A": [0, 1], "B": [-2, 4]}) - result = df.style.bar(align="mid", axis=None, vmin=-3, vmax=7)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - " transparent 30.0%", - " #d65f5f 30.0%", - " #d65f5f 40.0%", - " transparent 40.0%", - ), - (0, 1): bar_grad( - " transparent 10.0%", - " #d65f5f 10.0%", - " #d65f5f 30.0%", - " transparent 30.0%", - ), - (1, 1): bar_grad( - " transparent 30.0%", - " #d65f5f 30.0%", - " #d65f5f 70.0%", - " transparent 70.0%", - ), - } - assert result == expected - - def test_bar_align_mid_vmin_vmax_clipping(self): - df = DataFrame({"A": [0, 1], "B": [-2, 4]}) - result = df.style.bar(align="mid", axis=None, vmin=-1, vmax=3)._compute().ctx - expected = { - (0, 0): bar_grad(), - (1, 0): bar_grad( - " transparent 25.0%", - " #d65f5f 25.0%", - " #d65f5f 50.0%", - " transparent 50.0%", - ), - (0, 1): bar_grad("#d65f5f 25.0%", " transparent 25.0%"), - (1, 1): bar_grad( - " transparent 25.0%", - " #d65f5f 25.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_mid_nans(self): - df = DataFrame({"A": [1, None], "B": [-1, 3]}) - result = df.style.bar(align="mid", axis=None)._compute().ctx - expected = { - (0, 0): bar_grad( - " transparent 25.0%", - " #d65f5f 25.0%", - " #d65f5f 50.0%", - " transparent 50.0%", - ), - (0, 1): bar_grad("#d65f5f 25.0%", " transparent 25.0%"), - (1, 1): bar_grad( - " transparent 25.0%", - " #d65f5f 25.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_align_zero_nans(self): - df = DataFrame({"A": [1, None], "B": [-1, 2]}) - result = df.style.bar(align="zero", axis=None)._compute().ctx - expected = { - (0, 0): bar_grad( - " transparent 50.0%", - " #d65f5f 50.0%", - " #d65f5f 75.0%", - " transparent 75.0%", - ), - (0, 1): bar_grad( - " transparent 25.0%", - " #d65f5f 25.0%", - " #d65f5f 50.0%", - " transparent 50.0%", - ), - (1, 1): bar_grad( - " transparent 50.0%", - " #d65f5f 50.0%", - " #d65f5f 100.0%", - " transparent 100.0%", - ), - } - assert result == expected - - def test_bar_bad_align_raises(self): - df = DataFrame({"A": [-100, -60, -30, -20]}) - msg = "`align` must be one of {'left', 'zero',' mid'}" - with pytest.raises(ValueError, match=msg): - df.style.bar(align="poorly", color=["#d65f5f", "#5fba7d"]) - def test_format_with_na_rep(self): # GH 21527 28358 df = DataFrame([[None, None], [1.1, 1.2]], columns=["A", "B"]) @@ -973,27 +572,6 @@ def test_format_with_bad_na_rep(self): with pytest.raises(TypeError, match=msg): df.style.format(None, na_rep=-1) - def test_highlight_null(self, null_color="red"): - df = DataFrame({"A": [0, np.nan]}) - result = df.style.highlight_null()._compute().ctx - expected = {(1, 0): [("background-color", "red")]} - assert result == expected - - def test_highlight_null_subset(self): - # GH 31345 - df = DataFrame({"A": [0, np.nan], "B": [0, np.nan]}) - result = ( - df.style.highlight_null(null_color="red", subset=["A"]) - .highlight_null(null_color="green", subset=["B"]) - ._compute() - .ctx - ) - expected = { - (1, 0): [("background-color", "red")], - (1, 1): [("background-color", "green")], - } - assert result == expected - def test_nonunique_raises(self): df = DataFrame([[1, 2]], columns=["A", "A"]) msg = "style is not supported for non-unique indices." @@ -1098,47 +676,6 @@ def test_trim(self): result = self.df.style.highlight_max().render() assert result.count("#") == len(self.df.columns) - def test_highlight_max(self): - df = DataFrame([[1, 2], [3, 4]], columns=["A", "B"]) - css_seq = [("background-color", "yellow")] - # max(df) = min(-df) - for max_ in [True, False]: - if max_: - attr = "highlight_max" - else: - df = -df - attr = "highlight_min" - result = getattr(df.style, attr)()._compute().ctx - assert result[(1, 1)] == css_seq - - result = getattr(df.style, attr)(color="green")._compute().ctx - assert result[(1, 1)] == [("background-color", "green")] - - result = getattr(df.style, attr)(subset="A")._compute().ctx - assert result[(1, 0)] == css_seq - - result = getattr(df.style, attr)(axis=0)._compute().ctx - expected = { - (1, 0): css_seq, - (1, 1): css_seq, - } - assert result == expected - - result = getattr(df.style, attr)(axis=1)._compute().ctx - expected = { - (0, 1): css_seq, - (1, 1): css_seq, - } - assert result == expected - - # separate since we can't negate the strs - df["C"] = ["a", "b"] - result = df.style.highlight_max()._compute().ctx - expected = {(1, 1): css_seq} - - result = df.style.highlight_min()._compute().ctx - expected = {(0, 0): css_seq} - def test_export(self): f = lambda x: "color: red" if x > 0 else "color: blue" g = lambda x, z: f"color: {z}" if x > 0 else f"color: {z}" @@ -1704,96 +1241,6 @@ def test_uuid_len_raises(self, len_): with pytest.raises(TypeError, match=msg): Styler(df, uuid_len=len_, cell_ids=False).render() - @pytest.mark.parametrize( - "ttips", - [ - DataFrame( - data=[["Min", "Max"], [np.nan, ""]], - columns=["A", "B"], - index=["a", "b"], - ), - DataFrame(data=[["Max", "Min"]], columns=["B", "A"], index=["a"]), - DataFrame( - data=[["Min", "Max", None]], columns=["A", "B", "C"], index=["a"] - ), - ], - ) - def test_tooltip_render(self, ttips): - # GH 21266 - df = DataFrame(data=[[0, 3], [1, 2]], columns=["A", "B"], index=["a", "b"]) - s = Styler(df, uuid_len=0).set_tooltips(ttips).render() - - # test tooltip table level class - assert "#T__ .pd-t {\n visibility: hidden;\n" in s - - # test 'Min' tooltip added - assert ( - "#T__ #T__row0_col0:hover .pd-t {\n visibility: visible;\n}\n" - + '#T__ #T__row0_col0 .pd-t::after {\n content: "Min";\n}' - in s - ) - assert ( - '<td id="T__row0_col0" class="data row0 col0" >0<span class="pd-t">' - + "</span></td>" - in s - ) - - # test 'Max' tooltip added - assert ( - "#T__ #T__row0_col1:hover .pd-t {\n visibility: visible;\n}\n" - + '#T__ #T__row0_col1 .pd-t::after {\n content: "Max";\n}' - in s - ) - assert ( - '<td id="T__row0_col1" class="data row0 col1" >3<span class="pd-t">' - + "</span></td>" - in s - ) - - def test_tooltip_reindex(self): - # GH 39317 - df = DataFrame( - data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]], columns=[0, 1, 2], index=[0, 1, 2] - ) - ttips = DataFrame( - data=[["Mi", "Ma"], ["Mu", "Mo"]], - columns=[0, 2], - index=[0, 2], - ) - s = Styler(df, uuid_len=0).set_tooltips(DataFrame(ttips)).render() - assert '#T__ #T__row0_col0 .pd-t::after {\n content: "Mi";\n}' in s - assert '#T__ #T__row0_col2 .pd-t::after {\n content: "Ma";\n}' in s - assert '#T__ #T__row2_col0 .pd-t::after {\n content: "Mu";\n}' in s - assert '#T__ #T__row2_col2 .pd-t::after {\n content: "Mo";\n}' in s - - def test_tooltip_ignored(self): - # GH 21266 - df = DataFrame(data=[[0, 1], [2, 3]]) - s = Styler(df).set_tooltips_class("pd-t").render() # no set_tooltips() - assert '<style type="text/css">\n</style>' in s - assert '<span class="pd-t"></span>' not in s - - def test_tooltip_class(self): - # GH 21266 - df = DataFrame(data=[[0, 1], [2, 3]]) - s = ( - Styler(df, uuid_len=0) - .set_tooltips(DataFrame([["tooltip"]])) - .set_tooltips_class(name="other-class", properties=[("color", "green")]) - .render() - ) - assert "#T__ .other-class {\n color: green;\n" in s - assert '#T__ #T__row0_col0 .other-class::after {\n content: "tooltip";\n' in s - - # GH 39563 - s = ( - Styler(df, uuid_len=0) - .set_tooltips(DataFrame([["tooltip"]])) - .set_tooltips_class(name="other-class", properties="color:green;color:red;") - .render() - ) - assert "#T__ .other-class {\n color: green;\n color: red;\n}" in s - def test_w3_html_format(self): s = ( Styler( @@ -1925,107 +1372,6 @@ def test_non_reducing_multi_slice_on_multiindex(self, slice_): tm.assert_frame_equal(result, expected) -@td.skip_if_no_mpl -class TestStylerMatplotlibDep: - def test_background_gradient(self): - df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) - - for c_map in [None, "YlOrRd"]: - result = df.style.background_gradient(cmap=c_map)._compute().ctx - assert all("#" in x[0][1] for x in result.values()) - assert result[(0, 0)] == result[(0, 1)] - assert result[(1, 0)] == result[(1, 1)] - - result = ( - df.style.background_gradient(subset=pd.IndexSlice[1, "A"])._compute().ctx - ) - - assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")] - - @pytest.mark.parametrize( - "cmap, expected", - [ - ( - "PuBu", - { - (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")], - (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")], - }, - ), - ( - "YlOrRd", - { - (4, 8): [("background-color", "#fd913e"), ("color", "#000000")], - (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")], - }, - ), - ( - None, - { - (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")], - (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")], - }, - ), - ], - ) - def test_text_color_threshold(self, cmap, expected): - df = DataFrame(np.arange(100).reshape(10, 10)) - result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx - for k in expected.keys(): - assert result[k] == expected[k] - - @pytest.mark.parametrize("text_color_threshold", [1.1, "1", -1, [2, 2]]) - def test_text_color_threshold_raises(self, text_color_threshold): - df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) - msg = "`text_color_threshold` must be a value from 0 to 1." - with pytest.raises(ValueError, match=msg): - df.style.background_gradient( - text_color_threshold=text_color_threshold - )._compute() - - @td.skip_if_no_mpl - def test_background_gradient_axis(self): - df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) - - low = [("background-color", "#f7fbff"), ("color", "#000000")] - high = [("background-color", "#08306b"), ("color", "#f1f1f1")] - mid = [("background-color", "#abd0e6"), ("color", "#000000")] - result = df.style.background_gradient(cmap="Blues", axis=0)._compute().ctx - assert result[(0, 0)] == low - assert result[(0, 1)] == low - assert result[(1, 0)] == high - assert result[(1, 1)] == high - - result = df.style.background_gradient(cmap="Blues", axis=1)._compute().ctx - assert result[(0, 0)] == low - assert result[(0, 1)] == high - assert result[(1, 0)] == low - assert result[(1, 1)] == high - - result = df.style.background_gradient(cmap="Blues", axis=None)._compute().ctx - assert result[(0, 0)] == low - assert result[(0, 1)] == mid - assert result[(1, 0)] == mid - assert result[(1, 1)] == high - - def test_background_gradient_vmin_vmax(self): - # GH 12145 - df = DataFrame(range(5)) - ctx = df.style.background_gradient(vmin=1, vmax=3)._compute().ctx - assert ctx[(0, 0)] == ctx[(1, 0)] - assert ctx[(4, 0)] == ctx[(3, 0)] - - def test_background_gradient_int64(self): - # GH 28869 - df1 = pd.Series(range(3)).to_frame() - df2 = pd.Series(range(3), dtype="Int64").to_frame() - ctx1 = df1.style.background_gradient()._compute().ctx - ctx2 = df2.style.background_gradient()._compute().ctx - assert ctx2[(0, 0)] == ctx1[(0, 0)] - assert ctx2[(1, 0)] == ctx1[(1, 0)] - assert ctx2[(2, 0)] == ctx1[(2, 0)] - - def test_block_names(): # catch accidental removal of a block expected = { diff --git a/pandas/tests/io/formats/style/test_tooltip.py b/pandas/tests/io/formats/style/test_tooltip.py new file mode 100644 index 0000000000000..7aebb6fadc7b1 --- /dev/null +++ b/pandas/tests/io/formats/style/test_tooltip.py @@ -0,0 +1,99 @@ +import numpy as np +import pytest + +from pandas import DataFrame + +pytest.importorskip("jinja2") +from pandas.io.formats.style import Styler + + +class TestStylerTooltip: + @pytest.mark.parametrize( + "ttips", + [ + DataFrame( + data=[["Min", "Max"], [np.nan, ""]], + columns=["A", "B"], + index=["a", "b"], + ), + DataFrame(data=[["Max", "Min"]], columns=["B", "A"], index=["a"]), + DataFrame( + data=[["Min", "Max", None]], columns=["A", "B", "C"], index=["a"] + ), + ], + ) + def test_tooltip_render(self, ttips): + # GH 21266 + df = DataFrame(data=[[0, 3], [1, 2]], columns=["A", "B"], index=["a", "b"]) + s = Styler(df, uuid_len=0).set_tooltips(ttips).render() + + # test tooltip table level class + assert "#T__ .pd-t {\n visibility: hidden;\n" in s + + # test 'Min' tooltip added + assert ( + "#T__ #T__row0_col0:hover .pd-t {\n visibility: visible;\n}\n" + + '#T__ #T__row0_col0 .pd-t::after {\n content: "Min";\n}' + in s + ) + assert ( + '<td id="T__row0_col0" class="data row0 col0" >0<span class="pd-t">' + + "</span></td>" + in s + ) + + # test 'Max' tooltip added + assert ( + "#T__ #T__row0_col1:hover .pd-t {\n visibility: visible;\n}\n" + + '#T__ #T__row0_col1 .pd-t::after {\n content: "Max";\n}' + in s + ) + assert ( + '<td id="T__row0_col1" class="data row0 col1" >3<span class="pd-t">' + + "</span></td>" + in s + ) + + def test_tooltip_reindex(self): + # GH 39317 + df = DataFrame( + data=[[0, 1, 2], [3, 4, 5], [6, 7, 8]], columns=[0, 1, 2], index=[0, 1, 2] + ) + ttips = DataFrame( + data=[["Mi", "Ma"], ["Mu", "Mo"]], + columns=[0, 2], + index=[0, 2], + ) + s = Styler(df, uuid_len=0).set_tooltips(DataFrame(ttips)).render() + assert '#T__ #T__row0_col0 .pd-t::after {\n content: "Mi";\n}' in s + assert '#T__ #T__row0_col2 .pd-t::after {\n content: "Ma";\n}' in s + assert '#T__ #T__row2_col0 .pd-t::after {\n content: "Mu";\n}' in s + assert '#T__ #T__row2_col2 .pd-t::after {\n content: "Mo";\n}' in s + + def test_tooltip_ignored(self): + # GH 21266 + df = DataFrame(data=[[0, 1], [2, 3]]) + s = Styler(df).set_tooltips_class("pd-t").render() # no set_tooltips() + assert '<style type="text/css">\n</style>' in s + assert '<span class="pd-t"></span>' not in s + + def test_tooltip_css_class(self): + # GH 21266 + df = DataFrame(data=[[0, 1], [2, 3]]) + s = ( + Styler(df, uuid_len=0) + .set_tooltips(DataFrame([["tooltip"]])) + .set_tooltips_class(name="other-class", properties=[("color", "green")]) + .render() + ) + assert "#T__ .other-class {\n color: green;\n" in s + assert '#T__ #T__row0_col0 .other-class::after {\n content: "tooltip";\n' in s + + # GH 39563 + s = ( + Styler(df, uuid_len=0) + .set_tooltips(DataFrame([["tooltip"]])) + .set_tooltips_class(name="other-class", properties="color:green;color:red;") + .render() + ) + assert "#T__ .other-class {\n color: green;\n color: red;\n}" in s
splits `test_style.py` to `style/test_style.py` and `style/test_builtins.py`, with the simple classification of being related to `core` functionality or added `extensions`.
https://api.github.com/repos/pandas-dev/pandas/pulls/39946
2021-02-20T23:25:44Z
2021-02-22T23:00:30Z
2021-02-22T23:00:30Z
2021-02-23T06:29:45Z
Change in astype leads to no longer casting to numpy string dtypes
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 388c5dbf6a7ee..3b7de3d2f1f3e 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -234,7 +234,7 @@ Other API changes ^^^^^^^^^^^^^^^^^ - Partially initialized :class:`CategoricalDtype` (i.e. those with ``categories=None`` objects will no longer compare as equal to fully initialized dtype objects. - Accessing ``_constructor_expanddim`` on a :class:`DataFrame` and ``_constructor_sliced`` on a :class:`Series` now raise an ``AttributeError``. Previously a ``NotImplementedError`` was raised (:issue:`38782`) -- +- :meth:`DataFrame.astype` and :meth:`Series.astype` for ``bytes`` no longer casting to numpy string dtypes but instead casting to ``object`` dtype (:issue:`39566`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 669bfe08d42b0..3b0542dcf30ac 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1268,7 +1268,7 @@ def soft_convert_objects( values = lib.maybe_convert_objects( values, convert_datetime=datetime, convert_timedelta=timedelta ) - except (OutOfBoundsDatetime, ValueError): + except OutOfBoundsDatetime: return values if numeric and is_object_dtype(values.dtype): diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 0e52ebf69137c..69642dc2398fd 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -287,7 +287,9 @@ def apply( if not ignore_failures: raise continue - # if not isinstance(applied, ExtensionArray): + if not isinstance(applied, ExtensionArray): + if issubclass(applied.dtype.type, (str, bytes)): + applied = np.array(applied, dtype=object) # # TODO not all EA operations return new EAs (eg astype) # applied = array(applied) result_arrays.append(applied) @@ -413,7 +415,10 @@ 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) + # if issubclass(dtype, (str, bytes)): + # dtype = "object" + y = self.apply("astype", dtype=dtype, copy=copy) # , errors=errors) + return y def convert( self, diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 1377928f71915..5d36724899831 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2219,7 +2219,7 @@ class ObjectBlock(Block): @classmethod def _maybe_coerce_values(cls, values): - if issubclass(values.dtype.type, str): + if issubclass(values.dtype.type, (str, bytes)): values = np.array(values, dtype=object) return values diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 35e958ff3a2b1..8031f03901b8b 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -644,7 +644,8 @@ def test_astype_dt64_to_string(self, frame_or_series, tz_naive_fixture, request) alt = obj.astype(str) assert np.all(alt.iloc[1:] == result.iloc[1:]) - def test_astype_bytes(self): - # GH#39474 - result = DataFrame(["foo", "bar", "baz"]).astype(bytes) - assert result.dtypes[0] == np.dtype("S3") + @pytest.mark.parametrize("dtype", [bytes, np.string_, np.bytes_]) + def test_astype_bytes(self, dtype): + # GH#39566 + result = DataFrame(["foo", "bar", "baz"]).astype(dtype) + assert result.dtypes[0] == "object" diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index a3785518c860d..df86ef3a5ab8b 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -344,10 +344,11 @@ def test_astype_unicode(self): reload(sys) sys.setdefaultencoding(former_encoding) - def test_astype_bytes(self): + @pytest.mark.parametrize("dtype", [bytes, np.string_, np.bytes_]) + def test_astype_bytes(self, dtype): # GH#39474 - result = Series(["foo", "bar", "baz"]).astype(bytes) - assert result.dtypes == np.dtype("S3") + result = Series(["foo", "bar", "baz"]).astype(dtype) + assert result.dtypes == "object" class TestAstypeCategorical:
- [x] closes #39566 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry @jreback as discussed we no longer cast to numpy string dtypes after this
https://api.github.com/repos/pandas-dev/pandas/pulls/39945
2021-02-20T22:40:20Z
2021-06-16T13:18:06Z
null
2023-04-27T19:52:25Z
Fix regression for setitem not aligning rhs with boolean indexer
diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index 5ed8fd84472c4..d305024909703 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -16,7 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`~DataFrame.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) -- +- Fixed regression in :meth:`DataFrame.__setitem__` not aligning :class:`DataFrame` on right-hand side for boolean indexer (:issue:`39931`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5b06059d4302c..131a96d10a6d0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3264,6 +3264,9 @@ def _setitem_array(self, key, value): key = check_bool_indexer(self.index, key) indexer = key.nonzero()[0] self._check_setitem_copy() + if isinstance(value, DataFrame): + # GH#39931 reindex since iloc does not align + value = value.reindex(self.index.take(indexer)) self.iloc[indexer] = value else: if isinstance(value, DataFrame): diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 6763113036de8..6a9d4e6b5ab3c 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -575,3 +575,12 @@ def test_setitem_boolean_mask(self, mask_type, float_frame): expected = df.copy() expected.values[np.array(mask)] = np.nan tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("indexer", [tm.setitem, tm.loc]) + def test_setitem_boolean_mask_aligning(self, indexer): + # GH#39931 + df = DataFrame({"a": [1, 4, 2, 3], "b": [5, 6, 7, 8]}) + expected = df.copy() + mask = df["a"] >= 3 + indexer(df)[mask] = indexer(df)[mask].sort_values("a") + tm.assert_frame_equal(df, expected)
- [x] closes #39931 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry reindexing solves the issue here before dispatching to iloc
https://api.github.com/repos/pandas-dev/pandas/pulls/39944
2021-02-20T22:22:10Z
2021-02-22T22:59:24Z
2021-02-22T22:59:23Z
2021-02-22T23:06:13Z
BUG: format multiple CSS selectors correctly
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 8deeb3cfae1d3..78caa3d0c15de 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -492,6 +492,7 @@ Other - :class:`Styler` rendered HTML output minor alterations to support w3 good code standard (:issue:`39626`) - Bug in :class:`Styler` where rendered HTML was missing a column class identifier for certain header cells (:issue:`39716`) - Bug in :meth:`Styler.background_gradient` where text-color was not determined correctly (:issue:`39888`) +- Bug in :class:`Styler` where multiple elements in CSS-selectors were not correctly added to ``table_styles`` (:issue:`39942`) - Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`) - Bug in :func:`pandas.util.show_versions` where console JSON output was not proper JSON (:issue:`39701`) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 854f41d6b4dc3..e50f5986098d3 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -19,6 +19,7 @@ Sequence, Tuple, Union, + cast, ) from uuid import uuid4 @@ -55,7 +56,10 @@ CSSPair = Tuple[str, Union[str, int, float]] CSSList = List[CSSPair] CSSProperties = Union[str, CSSList] -CSSStyles = List[Dict[str, CSSProperties]] +CSSStyles = List[Dict[str, CSSProperties]] # = List[CSSDict] +# class CSSDict(TypedDict): # available when TypedDict is valid in pandas +# selector: str +# props: CSSProperties try: from matplotlib import colors @@ -566,7 +570,7 @@ def _translate(self): "body": body, "uuid": uuid, "precision": precision, - "table_styles": table_styles, + "table_styles": _format_table_styles(table_styles), "caption": caption, "table_attributes": table_attr, } @@ -1904,25 +1908,14 @@ def _pseudo_css(self, uuid: str, name: str, row: int, col: int, text: str): ------- pseudo_css : List """ + selector_id = "#T_" + uuid + "row" + str(row) + "_col" + str(col) return [ { - "selector": "#T_" - + uuid - + "row" - + str(row) - + "_col" - + str(col) - + f":hover .{name}", + "selector": selector_id + f":hover .{name}", "props": [("visibility", "visible")], }, { - "selector": "#T_" - + uuid - + "row" - + str(row) - + "_col" - + str(col) - + f" .{name}::after", + "selector": selector_id + f" .{name}::after", "props": [("content", f'"{text}"')], }, ] @@ -2077,6 +2070,26 @@ def _maybe_convert_css_to_tuples(style: CSSProperties) -> CSSList: return style +def _format_table_styles(styles: CSSStyles) -> CSSStyles: + """ + looks for multiple CSS selectors and separates them: + [{'selector': 'td, th', 'props': 'a:v;'}] + ---> [{'selector': 'td', 'props': 'a:v;'}, + {'selector': 'th', 'props': 'a:v;'}] + """ + return [ + item + for sublist in [ + [ # this is a CSSDict when TypedDict is available to avoid cast. + {"selector": x, "props": style["props"]} + for x in cast(str, style["selector"]).split(",") + ] + for style in styles + ] + for item in sublist + ] + + def _non_reducing_slice(slice_): """ Ensure that a slice doesn't reduce to a Series or Scalar. diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 01ed234f6e248..f0d1090899043 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -626,6 +626,19 @@ def test_table_styles(self): result = " ".join(styler.render().split()) assert "th { foo: bar; }" in result + def test_table_styles_multiple(self): + ctx = self.df.style.set_table_styles( + [ + {"selector": "th,td", "props": "color:red;"}, + {"selector": "tr", "props": "color:green;"}, + ] + )._translate()["table_styles"] + assert ctx == [ + {"selector": "th", "props": [("color", "red")]}, + {"selector": "td", "props": [("color", "red")]}, + {"selector": "tr", "props": [("color", "green")]}, + ] + def test_maybe_convert_css_to_tuples(self): expected = [("a", "b"), ("c", "d e")] assert _maybe_convert_css_to_tuples("a:b;c:d e;") == expected
- [x] closes #34061 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry Fixes a bug that doesn't format multiple CSS elements in selectors properly.
https://api.github.com/repos/pandas-dev/pandas/pulls/39942
2021-02-20T20:53:06Z
2021-02-27T19:44:59Z
2021-02-27T19:44:58Z
2021-02-27T20:17:14Z
DOC: Updated convert_dtype of Series.apply
diff --git a/pandas/core/series.py b/pandas/core/series.py index a25178402cf6b..ea713e51e04c9 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4067,7 +4067,8 @@ def apply( Python function or NumPy ufunc to apply. convert_dtype : bool, default True Try to find better dtype for elementwise function results. If - False, leave as dtype=object. + False, leave as dtype=object. Note that the dtype is always + preserved for extension array dtypes, such as Categorical. args : tuple Positional arguments passed to func after the series value. **kwargs
- [x] closes #39580 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry This updates the docs for parameter convert_dtype in pandas.Series.apply and adds dtypes for which the original dtype is kept.
https://api.github.com/repos/pandas-dev/pandas/pulls/39941
2021-02-20T20:29:10Z
2021-04-25T17:54:03Z
2021-04-25T17:54:03Z
2021-06-12T10:22:48Z
BUG: Groupby ops on empty objects loses index, columns, dtypes
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c65502898195a..4378a164a2edd 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -439,6 +439,7 @@ Groupby/resample/rolling - Bug in :meth:`core.window.expanding.ExpandingGroupby.corr` and :meth:`core.window.expanding.ExpandingGroupby.cov` where 1 would be returned instead of ``np.nan`` when providing ``other`` that was longer than each group (:issue:`39591`) - Bug in :meth:`.GroupBy.mean`, :meth:`.GroupBy.median` and :meth:`DataFrame.pivot_table` not propagating metadata (:issue:`28283`) - Bug in :meth:`Series.rolling` and :meth:`DataFrame.rolling` not calculating window bounds correctly when window is an offset and dates are in descending order (:issue:`40002`) +- Bug in :class:`SeriesGroupBy` and :class:`DataFrameGroupBy` on an empty ``Series`` or ``DataFrame`` would lose index, columns, and/or data types when directly using the methods ``idxmax``, ``idxmin``, ``mad``, ``min``, ``max``, ``sum``, ``prod``, and ``skew`` or using them through ``apply``, ``aggregate``, or ``resample`` (:issue:`26411`) - Reshaping @@ -454,6 +455,7 @@ Reshaping - Bug in :meth:`DataFrame.sort_values` not reshaping index correctly after sorting on columns, when ``ignore_index=True`` (:issue:`39464`) - Bug in :meth:`DataFrame.append` returning incorrect dtypes with combinations of ``ExtensionDtype`` dtypes (:issue:`39454`) - Bug in :meth:`DataFrame.append` returning incorrect dtypes with combinations of ``datetime64`` and ``timedelta64`` dtypes (:issue:`39574`) +- Bug in :meth:`DataFrame.pivot_table` returning a ``MultiIndex`` for a single value when operating on and empty ``DataFrame`` (:issue:`13483`) Sparse ^^^^^^ diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index c1a277925de2a..b06adbd96874f 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -450,13 +450,19 @@ def _wrap_transformed_output( return result def _wrap_applied_output( - self, keys: Index, values: Optional[List[Any]], not_indexed_same: bool = False + self, + data: Series, + keys: Index, + values: Optional[List[Any]], + not_indexed_same: bool = False, ) -> FrameOrSeriesUnion: """ Wrap the output of SeriesGroupBy.apply into the expected result. Parameters ---------- + data : Series + Input data for groupby operation. keys : Index Keys of groups that Series was grouped by. values : Optional[List[Any]] @@ -471,7 +477,10 @@ def _wrap_applied_output( if len(keys) == 0: # GH #6265 return self.obj._constructor( - [], name=self._selection_name, index=keys, dtype=np.float64 + [], + name=self._selection_name, + index=self.grouper.result_index, + dtype=data.dtype, ) assert values is not None @@ -1229,9 +1238,13 @@ def _aggregate_item_by_item(self, func, *args, **kwargs) -> DataFrame: return self.obj._constructor(result, columns=result_columns) - def _wrap_applied_output(self, keys, values, not_indexed_same=False): + def _wrap_applied_output(self, data, keys, values, not_indexed_same=False): if len(keys) == 0: - return self.obj._constructor(index=keys) + result = self.obj._constructor( + index=self.grouper.result_index, columns=data.columns + ) + result = result.astype(data.dtypes.to_dict(), copy=False) + return result # GH12824 first_not_none = next(com.not_none(*values), None) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index e939c184d501a..b9310794d7caa 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -981,7 +981,7 @@ def _python_apply_general( keys, values, mutated = self.grouper.apply(f, data, self.axis) return self._wrap_applied_output( - keys, values, not_indexed_same=mutated or self.mutated + data, keys, values, not_indexed_same=mutated or self.mutated ) def _iterate_slices(self) -> Iterable[Series]: @@ -1058,7 +1058,7 @@ def _wrap_aggregated_output( def _wrap_transformed_output(self, output: Mapping[base.OutputKey, np.ndarray]): raise AbstractMethodError(self) - def _wrap_applied_output(self, keys, values, not_indexed_same: bool = False): + def _wrap_applied_output(self, data, keys, values, not_indexed_same: bool = False): raise AbstractMethodError(self) @final diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 8feb379a82ada..d0026d7acbe65 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -236,14 +236,8 @@ def __internal_pivot_table( ) # discard the top level - if ( - values_passed - and not values_multi - and not table.empty - and (table.columns.nlevels > 1) - ): - table = table[values[0]] - + if values_passed and not values_multi and table.columns.nlevels > 1: + table = table.droplevel(0, axis=1) if len(index) == 0 and len(columns) > 0: table = table.T @@ -650,7 +644,6 @@ def crosstab( **dict(zip(unique_colnames, columns)), } df = DataFrame(data, index=common_idx) - original_df_cols = df.columns if values is None: df["__dummy__"] = 0 @@ -660,7 +653,7 @@ def crosstab( kwargs = {"aggfunc": aggfunc} table = df.pivot_table( - ["__dummy__"], + "__dummy__", index=unique_rownames, columns=unique_colnames, margins=margins, @@ -669,12 +662,6 @@ def crosstab( **kwargs, ) - # GH18321, after pivoting, an extra top level of column index of `__dummy__` is - # created, and this extra level should not be included in the further steps - if not table.empty: - cols_diff = df.columns.difference(original_df_cols)[0] - table = table[cols_diff] - # Post-process if normalize is not False: table = _normalize( diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 92b7aefa6dd8c..f2f9cfee178d9 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -147,11 +147,13 @@ def test_agg_apply_corner(ts, tsframe): # DataFrame grouped = tsframe.groupby(tsframe["A"] * np.nan) exp_df = DataFrame( - columns=tsframe.columns, dtype=float, index=Index([], dtype=np.float64) + columns=tsframe.columns, + dtype=float, + index=Index([], name="A", dtype=np.float64), ) - tm.assert_frame_equal(grouped.sum(), exp_df, check_names=False) - tm.assert_frame_equal(grouped.agg(np.sum), exp_df, check_names=False) - tm.assert_frame_equal(grouped.apply(np.sum), exp_df.iloc[:, :0], check_names=False) + tm.assert_frame_equal(grouped.sum(), exp_df) + tm.assert_frame_equal(grouped.agg(np.sum), exp_df) + tm.assert_frame_equal(grouped.apply(np.sum), exp_df) def test_agg_grouping_is_list_tuple(ts): diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 4dce7e8553be4..6731790c89384 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -10,6 +10,7 @@ import pandas as pd from pandas import ( + Categorical, DataFrame, Grouper, Index, @@ -18,6 +19,7 @@ Timestamp, date_range, read_csv, + to_datetime, ) import pandas._testing as tm from pandas.core.base import SpecificationError @@ -1716,15 +1718,48 @@ def test_pivot_table_values_key_error(): ) -def test_empty_dataframe_groupby(): - # GH8093 - df = DataFrame(columns=["A", "B", "C"]) - - result = df.groupby("A").sum() - expected = DataFrame(columns=["B", "C"], dtype=np.float64) - expected.index.name = "A" - - tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize("columns", ["C", ["C"]]) +@pytest.mark.parametrize("keys", [["A"], ["A", "B"]]) +@pytest.mark.parametrize( + "values", + [ + [True], + [0], + [0.0], + ["a"], + [Categorical([0])], + [to_datetime(0)], + [date_range(0, 1, 1, tz="US/Eastern")], + [pd.array([0], dtype="Int64")], + ], +) +@pytest.mark.parametrize("method", ["attr", "agg", "apply"]) +@pytest.mark.parametrize( + "op", ["idxmax", "idxmin", "mad", "min", "max", "sum", "prod", "skew"] +) +def test_empty_groupby(columns, keys, values, method, op): + # GH8093 & GH26411 + + override_dtype = None + if isinstance(values[0], bool) and op in ("prod", "sum") and method != "apply": + # sum/product of bools is an integer + override_dtype = "int64" + + df = DataFrame([3 * values], columns=list("ABC")) + df = df.iloc[:0] + + gb = df.groupby(keys)[columns] + if method == "attr": + result = getattr(gb, op)() + else: + result = getattr(gb, method)(op) + + expected = df.set_index(keys)[columns] + if override_dtype is not None: + expected = expected.astype(override_dtype) + if len(keys) == 1: + expected.index.name = keys[0] + tm.assert_equal(result, expected) def test_tuple_as_grouping(): diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index a17ed44c4011a..50775b9ef3a47 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -10,6 +10,7 @@ from pandas import ( DataFrame, Series, + TimedeltaIndex, Timestamp, ) import pandas._testing as tm @@ -398,6 +399,18 @@ def test_resample_groupby_agg(): tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize("keys", [["a"], ["a", "b"]]) +def test_empty(keys): + # GH 26411 + df = pd.DataFrame([], columns=["a", "b"], index=TimedeltaIndex([])) + result = df.groupby(keys).resample(rule=pd.to_timedelta("00:00:01")).mean() + expected = DataFrame(columns=["a", "b"]).set_index(keys, drop=False) + if len(keys) == 1: + expected.index.name = keys[0] + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("consolidate", [True, False]) def test_resample_groupby_agg_object_dtype_all_nan(consolidate): # https://github.com/pandas-dev/pandas/issues/39329 diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 86cde3eee874d..1ecb408d49813 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -240,7 +240,10 @@ def test_crosstab_no_overlap(self): s2 = Series([4, 5, 6], index=[4, 5, 6]) actual = crosstab(s1, s2) - expected = DataFrame() + expected = DataFrame( + index=Index([], dtype="int64", name="row_0"), + columns=Index([], dtype="int64", name="col_0"), + ) tm.assert_frame_equal(actual, expected) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 19eba4305fdf6..8d2b4f2b325c2 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2040,7 +2040,7 @@ def test_pivot_table_aggfunc_scalar_dropna(self, dropna): tm.assert_frame_equal(result, expected) def test_pivot_table_empty_aggfunc(self): - # GH 9186 + # GH 9186 & GH 13483 df = DataFrame( { "A": [2, 2, 3, 3, 2], @@ -2050,7 +2050,8 @@ def test_pivot_table_empty_aggfunc(self): } ) result = df.pivot_table(index="A", columns="D", values="id", aggfunc=np.size) - expected = DataFrame() + expected = DataFrame(index=Index([], dtype="int64", name="A")) + expected.columns.name = "D" tm.assert_frame_equal(result, expected) def test_pivot_table_no_column_raises(self):
- [x] closes #26411 - [x] closes #13483 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39940
2021-02-20T20:27:40Z
2021-02-24T16:39:01Z
2021-02-24T16:39:00Z
2021-07-22T20:50:06Z
REF: share _maybe_coerce_values
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d12be7f94822c..1fc0329b2a78e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -17,7 +17,6 @@ from pandas._libs import ( Interval, - NaT, Period, Timestamp, algos as libalgos, @@ -45,6 +44,7 @@ maybe_downcast_numeric, maybe_downcast_to_dtype, maybe_upcast, + sanitize_to_nanoseconds, soft_convert_objects, ) from pandas.core.dtypes.common import ( @@ -72,6 +72,7 @@ from pandas.core.dtypes.missing import ( is_valid_na_for_dtype, isna, + na_value_for_dtype, ) import pandas.core.algorithms as algos @@ -95,11 +96,13 @@ DatetimeArray, ExtensionArray, PandasArray, - TimedeltaArray, ) from pandas.core.base import PandasObject import pandas.core.common as com -from pandas.core.construction import extract_array +from pandas.core.construction import ( + ensure_wrapped_if_datetimelike, + extract_array, +) from pandas.core.indexers import ( check_setitem_lengths, is_empty_indexer, @@ -2095,8 +2098,6 @@ class DatetimeLikeBlockMixin(NDArrayBackedExtensionBlock): is_numeric = False _can_hold_na = True - _dtype: np.dtype - _holder: Type[Union[DatetimeArray, TimedeltaArray]] @classmethod def _maybe_coerce_values(cls, values): @@ -2112,25 +2113,26 @@ def _maybe_coerce_values(cls, values): Returns ------- values : ndarray[datetime64ns/timedelta64ns] - - Overridden by DatetimeTZBlock. """ - if values.dtype != cls._dtype: - # non-nano we will convert to nano - if values.dtype.kind != cls._dtype.kind: - # caller is responsible for ensuring td64/dt64 dtype - raise TypeError(values.dtype) # pragma: no cover - - values = cls._holder._from_sequence(values)._data - - if isinstance(values, cls._holder): + values = extract_array(values, extract_numpy=True) + if isinstance(values, np.ndarray): + values = sanitize_to_nanoseconds(values) + elif isinstance(values.dtype, np.dtype): + # i.e. not datetime64tz values = values._data - assert isinstance(values, np.ndarray), type(values) return values def array_values(self): - return self._holder._simple_new(self.values) + return ensure_wrapped_if_datetimelike(self.values) + + @property + def _holder(self): + return type(self.array_values()) + + @property + def fill_value(self): + return na_value_for_dtype(self.dtype) def to_native_types(self, na_rep="NaT", **kwargs): """ convert to our native types format """ @@ -2142,9 +2144,6 @@ def to_native_types(self, na_rep="NaT", **kwargs): class DatetimeBlock(DatetimeLikeBlockMixin): __slots__ = () - fill_value = np.datetime64("NaT", "ns") - _dtype = fill_value.dtype - _holder = DatetimeArray def set_inplace(self, locs, values): """ @@ -2165,42 +2164,16 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): _can_hold_na = True is_numeric = False - _holder = DatetimeArray - internal_values = Block.internal_values _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types diff = DatetimeBlock.diff - fill_value = NaT where = DatetimeBlock.where putmask = DatetimeLikeBlockMixin.putmask fillna = DatetimeLikeBlockMixin.fillna array_values = ExtensionBlock.array_values - @classmethod - def _maybe_coerce_values(cls, values): - """ - Input validation for values passed to __init__. Ensure that - we have datetime64TZ, coercing if necessary. - - Parameters - ---------- - values : array-like - Must be convertible to datetime64 - - Returns - ------- - values : DatetimeArray - """ - if not isinstance(values, cls._holder): - values = cls._holder(values) - - if values.tz is None: - raise ValueError("cannot create a DatetimeTZBlock without a tz") - - return values - @property def is_view(self) -> bool: """ return a boolean if I am possibly a view """ @@ -2216,9 +2189,6 @@ def external_values(self): class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () - _holder = TimedeltaArray - fill_value = np.timedelta64("NaT", "ns") - _dtype = fill_value.dtype class ObjectBlock(Block):
Gets us within spittting distance of combining DTBlock/TDBlock (and not far from DT64TZBlock too)
https://api.github.com/repos/pandas-dev/pandas/pulls/39939
2021-02-20T18:21:04Z
2021-02-22T17:46:41Z
2021-02-22T17:46:41Z
2021-02-22T17:57:04Z
ENH: Add function to create DateOffset objects from offset aliases
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 2d4704ad3bda6..09d4fdadecbe9 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -4062,3 +4062,32 @@ cdef inline int _roll_qtrday(npy_datetimestruct* dts, # make sure to roll forward, so negate n += 1 return n + + +_alias_mapping = { + **{k: prefix_mapping.get(v.split("-")[0]) + for k, v in _lite_rule_alias.items() + if prefix_mapping.get(v.split("-")[0])}, + **prefix_mapping} + + +def offset(offset_alias: str, n: int = 1, **kwargs) -> BaseOffset: + """ + Given an offset alias (e.g., 'M'), periods number and the matching DateOffset + class arguments, return a new DateOffset object. + + Parameters + ---------- + offset_alias : str + Offset alias, a.k.a. frequency string, for the DateOffset object + to be created. E.g., 'Q' for QuarterEnd + n : int, default 1 + Number of periods to offset. + **kwargs + These parameters will be passed to the DateOffset object consructor. + + Returns + ------- + DateOffset + """ + return _alias_mapping[offset_alias](n, **kwargs) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index d36bea72908a3..d08c3b1259cb1 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -54,6 +54,7 @@ FY5253Quarter, LastWeekOfMonth, MonthBegin, + MonthEnd, Nano, Tick, Week, @@ -870,3 +871,11 @@ def test_dateoffset_immutable(attribute): msg = "DateOffset objects are immutable" with pytest.raises(AttributeError, match=msg): setattr(offset, attribute, 5) + + +def test_offset(): + assert offsets.offset("MS", 0) == MonthBegin(0) + assert offsets.offset("M", -2) == MonthEnd(-2) + assert offsets.offset("BQS") == BQuarterBegin() + assert offsets.offset("A", 3, month=2) == YearEnd(3, month=2) + assert offsets.offset("YS") == YearBegin(3, month=1)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39937
2021-02-20T15:16:06Z
2021-02-20T18:24:56Z
null
2021-02-20T18:31:28Z
ENH: Create script to set up a development environment using docker
diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst index bc0a3556b9ac1..c04ce33649345 100644 --- a/doc/source/development/contributing_environment.rst +++ b/doc/source/development/contributing_environment.rst @@ -24,7 +24,15 @@ Instead of manually setting up a development environment, you can use `Docker commands. pandas provides a ``DockerFile`` in the root directory to build a Docker image with a full pandas development environment. -**Docker Commands** +**Unix/macOS** + +There is a script to help you with this:: + + ./scripts/docker.sh + +When prompted, enter your Github username. + +**Windows** Pass your GitHub username in the ``DockerFile`` to use your own fork:: diff --git a/scripts/docker.sh b/scripts/docker.sh new file mode 100755 index 0000000000000..ea572cc717efb --- /dev/null +++ b/scripts/docker.sh @@ -0,0 +1,25 @@ +#!/bin/bash +# +# Set up a development environment with Docker. + +run_container () { + # Run a container and bind the local forked repo to it + docker run -it --rm -v "$(pwd)":/home/pandas-"$USER" pandas-"$USER"-env +} + +# Check if pandas image already exists +docker image ls | grep "pandas-$USER-env" &> /dev/null + +if [[ $? == 0 ]]; then + + run_container + +else + + # Pass the Github username as the build variable + read -rp "Github username: " gh_username + docker build --tag pandas-"$USER"-env --build-arg gh_username=$gh_username . + + run_container + +fi
This script will help the contributors with the process of setting up a docker container. So instead of manually passing the Github username in the Dockerfile and then running a couple of commands, you can run only this: ``` ./docker.sh ``` ...and enter the Github username when prompted. I think this can be good, right? Especially for the new users.
https://api.github.com/repos/pandas-dev/pandas/pulls/39936
2021-02-20T14:37:09Z
2021-09-08T02:41:40Z
null
2021-09-08T08:18:14Z
BUG: DataFrame.agg and apply with 'size' returns a scalar
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index c65502898195a..d1bf38588710b 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -323,6 +323,7 @@ Numeric - Bug in :meth:`DataFrame.rank` with ``np.inf`` and mixture of ``np.nan`` and ``np.inf`` (:issue:`32593`) - Bug in :meth:`DataFrame.rank` with ``axis=0`` and columns holding incomparable types raising ``IndexError`` (:issue:`38932`) - Bug in :func:`select_dtypes` different behavior between Windows and Linux with ``include="int"`` (:issue:`36569`) +- Bug in :meth:`DataFrame.apply` and :meth:`DataFrame.agg` when passed argument ``func="size"`` would operate on the entire ``DataFrame`` instead of rows or columns (:issue:`39934`) - Conversion diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 46b1e5b20ce3a..c7fa298b06a2f 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -159,6 +159,10 @@ def f(x): def index(self) -> Index: return self.obj.index + @property + def agg_axis(self) -> Index: + return self.obj._get_agg_axis(self.axis) + @abc.abstractmethod def apply(self) -> FrameOrSeriesUnion: pass @@ -541,17 +545,26 @@ def maybe_apply_str(self) -> Optional[FrameOrSeriesUnion]: f = self.f if not isinstance(f, str): return None + + obj = self.obj + + # TODO: GH 39993 - Avoid special-casing by replacing with lambda + if f == "size" and isinstance(obj, ABCDataFrame): + # Special-cased because DataFrame.size returns a single scalar + value = obj.shape[self.axis] + return obj._constructor_sliced(value, index=self.agg_axis, name="size") + # Support for `frame.transform('method')` # Some methods (shift, etc.) require the axis argument, others # don't, so inspect and insert if necessary. - func = getattr(self.obj, f, None) + func = getattr(obj, f, None) if callable(func): sig = inspect.getfullargspec(func) if "axis" in sig.args: self.kwargs["axis"] = self.axis elif self.axis != 0: raise ValueError(f"Operation {f} does not support axis=1") - return self.obj._try_aggregate_string_function(f, *self.args, **self.kwargs) + return obj._try_aggregate_string_function(f, *self.args, **self.kwargs) def maybe_apply_multiple(self) -> Optional[FrameOrSeriesUnion]: """ @@ -613,10 +626,6 @@ def values(self): def dtypes(self) -> Series: return self.obj.dtypes - @property - def agg_axis(self) -> Index: - return self.obj._get_agg_axis(self.axis) - def apply(self) -> FrameOrSeriesUnion: """ compute the results """ # dispatch to agg diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index 083c34ce4b63f..c5d0b215ff4d8 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1415,11 +1415,21 @@ def test_non_callable_aggregates(how): tm.assert_series_equal(result, expected) - # Just a string attribute arg same as calling df.arg - result = getattr(df, how)("size") - expected = df.size - assert result == expected +@pytest.mark.parametrize("how", ["agg", "apply"]) +def test_size_as_str(how, axis): + # GH 39934 + df = DataFrame( + {"A": [None, 2, 3], "B": [1.0, np.nan, 3.0], "C": ["foo", None, "bar"]} + ) + # Just a string attribute arg same as calling df.arg + # on the columns + result = getattr(df, how)("size", axis=axis) + if axis == 0 or axis == "index": + expected = Series(df.shape[0], index=df.columns, name="size") + else: + expected = Series(df.shape[1], index=df.index, name="size") + tm.assert_series_equal(result, expected) def test_agg_listlike_result():
- [x] closes #39934 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39935
2021-02-20T14:18:49Z
2021-02-24T16:32:19Z
2021-02-24T16:32:19Z
2021-06-16T16:07:41Z
Grammatically update the readme file
diff --git a/README.md b/README.md index d928195bf2a10..65bbfc0c79e08 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ----------------- -# pandas: powerful Python data analysis toolkit +# pandas: is a powerful Python data analysis toolkit [![PyPI Latest Release](https://img.shields.io/pypi/v/pandas.svg)](https://pypi.org/project/pandas/) [![Conda Latest Release](https://anaconda.org/conda-forge/pandas/badges/version.svg)](https://anaconda.org/anaconda/pandas/) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3509134.svg)](https://doi.org/10.5281/zenodo.3509134) @@ -20,16 +20,14 @@ ## What is it? -**pandas** is a Python package that provides fast, flexible, and expressive data +**pandas** is a Python package that provides fast, flexible, and expressive data structures designed to make working with "relational" or "labeled" data both -easy and intuitive. It aims to be the fundamental high-level building block for -doing practical, **real world** data analysis in Python. Additionally, it has -the broader goal of becoming **the most powerful and flexible open source data -analysis / manipulation tool available in any language**. It is already well on -its way towards this goal. + easy and intuitive. It aims to be the fundamental high-level building block for + doing practical, **real-world** data analysis in Python. Additionally, it has + the broader goal of becoming **the most powerful and flexible open-source data analysis/manipulation tool available in any language**. It is already well on its way towards this goal.l. ## Main Features -Here are just a few of the things that pandas does well: +Here are just a few of the things that pandas do well: - Easy handling of [**missing data**][missing-data] (represented as `NaN`, `NA`, or `NaT`) in floating point as well as non-floating point data @@ -114,7 +112,7 @@ dependencies above. Cython can be installed from PyPI: pip install cython ``` -In the `pandas` directory (same one where you found this file after +In the `pandas` directory (the same one where you found this file after cloning the git repo), execute: ```sh
Small grammatical update the readme file
https://api.github.com/repos/pandas-dev/pandas/pulls/39933
2021-02-20T13:47:14Z
2021-02-20T14:09:00Z
null
2021-02-20T14:09:00Z
DOC: updated wrong type hint for pandas.Series.droplevel
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a32ae7090ef8b..1b7c02cd7a05b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -737,9 +737,10 @@ def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: ).__finalize__(self, method="swapaxes") @final + @doc(klass=_shared_doc_kwargs["klass"]) def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: """ - Return DataFrame with requested index / column level(s) removed. + Return {klass} with requested index / column level(s) removed. .. versionadded:: 0.24.0 @@ -750,7 +751,7 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: If list-like, elements must be names or positional indexes of levels. - axis : {0 or 'index', 1 or 'columns'}, default 0 + axis : {{0 or 'index', 1 or 'columns'}}, default 0 Axis along which the level(s) is removed: * 0 or 'index': remove level(s) in column. @@ -758,8 +759,8 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: Returns ------- - DataFrame - DataFrame with requested index / column level(s) removed. + {klass} + {klass} with requested index / column level(s) removed. Examples --------
- [x] closes #39907 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39932
2021-02-20T13:29:25Z
2021-02-20T18:16:15Z
2021-02-20T18:16:14Z
2021-02-20T18:16:27Z
ENH: add a gradient map to background gradient
diff --git a/doc/source/_static/style/bg_ax0.png b/doc/source/_static/style/bg_ax0.png new file mode 100644 index 0000000000000..1767d34136a02 Binary files /dev/null and b/doc/source/_static/style/bg_ax0.png differ diff --git a/doc/source/_static/style/bg_axNone.png b/doc/source/_static/style/bg_axNone.png new file mode 100644 index 0000000000000..8882c6f689773 Binary files /dev/null and b/doc/source/_static/style/bg_axNone.png differ diff --git a/doc/source/_static/style/bg_axNone_gmap.png b/doc/source/_static/style/bg_axNone_gmap.png new file mode 100644 index 0000000000000..bdd2b55e8c6b4 Binary files /dev/null and b/doc/source/_static/style/bg_axNone_gmap.png differ diff --git a/doc/source/_static/style/bg_axNone_lowhigh.png b/doc/source/_static/style/bg_axNone_lowhigh.png new file mode 100644 index 0000000000000..c37a707e73692 Binary files /dev/null and b/doc/source/_static/style/bg_axNone_lowhigh.png differ diff --git a/doc/source/_static/style/bg_axNone_vminvmax.png b/doc/source/_static/style/bg_axNone_vminvmax.png new file mode 100644 index 0000000000000..4ca958de15ec3 Binary files /dev/null and b/doc/source/_static/style/bg_axNone_vminvmax.png differ diff --git a/doc/source/_static/style/bg_gmap.png b/doc/source/_static/style/bg_gmap.png new file mode 100644 index 0000000000000..039ff6b78958e Binary files /dev/null and b/doc/source/_static/style/bg_gmap.png differ diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 5e95cd6e5ee10..3a7f938f70338 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -186,6 +186,7 @@ Other enhancements - :meth:`.Styler.apply` now more consistently accepts ndarray function returns, i.e. in all cases for ``axis`` is ``0, 1 or None`` (:issue:`39359`) - :meth:`.Styler.apply` and :meth:`.Styler.applymap` now raise errors if wrong format CSS is passed on render (:issue:`39660`) - :meth:`.Styler.format` adds keyword argument ``escape`` for optional HTML escaping (:issue:`40437`) +- :meth:`.Styler.background_gradient` now allows the ability to supply a specific gradient map (:issue:`22727`) - :meth:`.Styler.clear` now clears :attr:`Styler.hidden_index` and :attr:`Styler.hidden_columns` as well (:issue:`40484`) - Builtin highlighting methods in :class:`Styler` have a more consistent signature and css customisability (:issue:`40242`) - :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index ba17e44fc66e0..267606461f003 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -43,7 +43,10 @@ from pandas.api.types import is_list_like from pandas.core import generic import pandas.core.common as com -from pandas.core.frame import DataFrame +from pandas.core.frame import ( + DataFrame, + Series, +) from pandas.core.generic import NDFrame from pandas.core.indexes.api import Index @@ -179,7 +182,7 @@ def __init__( escape: bool = False, ): # validate ordered args - if isinstance(data, pd.Series): + if isinstance(data, Series): data = data.to_frame() if not isinstance(data, DataFrame): raise TypeError("``data`` must be a Series or DataFrame") @@ -1438,21 +1441,27 @@ def background_gradient( text_color_threshold: float = 0.408, vmin: float | None = None, vmax: float | None = None, + gmap: Sequence | None = None, ) -> Styler: """ Color the background in a gradient style. The background color is determined according - to the data in each column (optionally row). Requires matplotlib. + to the data in each column, row or frame, or by a given + gradient map. Requires matplotlib. Parameters ---------- cmap : str or colormap Matplotlib colormap. low : float - Compress the range by the low. + Compress the color range at the low end. This is a multiple of the data + range to extend below the minimum; good values usually in [0, 1], + defaults to 0. high : float - Compress the range by the high. + Compress the color range at the high end. This is a multiple of the data + range to extend above the maximum; good values usually in [0, 1], + defaults to 0. axis : {0 or 'index', 1 or 'columns', None}, default 0 Apply to each column (``axis=0`` or ``'index'``), to each row (``axis=1`` or ``'columns'``), or to the entire DataFrame at once @@ -1460,45 +1469,108 @@ def background_gradient( subset : IndexSlice A valid slice for ``data`` to limit the style application to. text_color_threshold : float or int - Luminance threshold for determining text color. Facilitates text - visibility across varying background colors. From 0 to 1. - 0 = all text is dark colored, 1 = all text is light colored. + Luminance threshold for determining text color in [0, 1]. Facilitates text + visibility across varying background colors. All text is dark if 0, and + light if 1, defaults to 0.408. .. versionadded:: 0.24.0 vmin : float, optional Minimum data value that corresponds to colormap minimum value. - When None (default): the minimum value of the data will be used. + If not specified the minimum value of the data (or gmap) will be used. .. versionadded:: 1.0.0 vmax : float, optional Maximum data value that corresponds to colormap maximum value. - When None (default): the maximum value of the data will be used. + If not specified the maximum value of the data (or gmap) will be used. .. versionadded:: 1.0.0 + gmap : array-like, optional + Gradient map for determining the background colors. If not supplied + will use the underlying data from rows, columns or frame. If given as an + ndarray or list-like must be an identical shape to the underlying data + considering ``axis`` and ``subset``. If given as DataFrame or Series must + have same index and column labels considering ``axis`` and ``subset``. + If supplied, ``vmin`` and ``vmax`` should be given relative to this + gradient map. + + .. versionadded:: 1.3.0 + Returns ------- self : Styler - Raises - ------ - ValueError - If ``text_color_threshold`` is not a value from 0 to 1. - Notes ----- - Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the - text legible by not using the entire range of the color map. The range - of the data is extended by ``low * (x.max() - x.min())`` and ``high * - (x.max() - x.min())`` before normalizing. + When using ``low`` and ``high`` the range + of the gradient, given by the data if ``gmap`` is not given or by ``gmap``, + is extended at the low end effectively by + `map.min - low * map.range` and at the high end by + `map.max + high * map.range` before the colors are normalized and determined. + + If combining with ``vmin`` and ``vmax`` the `map.min`, `map.max` and + `map.range` are replaced by values according to the values derived from + ``vmin`` and ``vmax``. + + This method will preselect numeric columns and ignore non-numeric columns + unless a ``gmap`` is supplied in which case no preselection occurs. + + Examples + -------- + >>> df = pd.DataFrame({ + ... 'City': ['Stockholm', 'Oslo', 'Copenhagen'], + ... 'Temp (c)': [21.6, 22.4, 24.5], + ... 'Rain (mm)': [5.0, 13.3, 0.0], + ... 'Wind (m/s)': [3.2, 3.1, 6.7] + ... }) + + Shading the values column-wise, with ``axis=0``, preselecting numeric columns + + >>> df.style.background_gradient(axis=0) + + .. figure:: ../../_static/style/bg_ax0.png + + Shading all values collectively using ``axis=None`` + + >>> df.style.background_gradient(axis=None) + + .. figure:: ../../_static/style/bg_axNone.png + + Compress the color map from the both ``low`` and ``high`` ends + + >>> df.style.background_gradient(axis=None, low=0.75, high=1.0) + + .. figure:: ../../_static/style/bg_axNone_lowhigh.png + + Manually setting ``vmin`` and ``vmax`` gradient thresholds + + >>> df.style.background_gradient(axis=None, vmin=6.7, vmax=21.6) + + .. figure:: ../../_static/style/bg_axNone_vminvmax.png + + Setting a ``gmap`` and applying to all columns with another ``cmap`` + + >>> df.style.background_gradient(axis=0, gmap=df['Temp (c)'], cmap='YlOrRd') + + .. figure:: ../../_static/style/bg_gmap.png + + Setting the gradient map for a dataframe (i.e. ``axis=None``), we need to + explicitly state ``subset`` to match the ``gmap`` shape + + >>> gmap = np.array([[1,2,3], [2,3,4], [3,4,5]]) + >>> df.style.background_gradient(axis=None, gmap=gmap, + ... cmap='YlOrRd', subset=['Temp (c)', 'Rain (mm)', 'Wind (m/s)'] + ... ) + + .. figure:: ../../_static/style/bg_axNone_gmap.png """ - if subset is None: + if subset is None and gmap is None: subset = self.data.select_dtypes(include=np.number).columns self.apply( - self._background_gradient, + _background_gradient, cmap=cmap, subset=subset, axis=axis, @@ -1507,75 +1579,10 @@ def background_gradient( text_color_threshold=text_color_threshold, vmin=vmin, vmax=vmax, + gmap=gmap, ) return self - @staticmethod - def _background_gradient( - s, - cmap="PuBu", - low: float = 0, - high: float = 0, - text_color_threshold: float = 0.408, - vmin: float | None = None, - vmax: float | None = None, - ): - """ - Color background in a range according to the data. - """ - if ( - not isinstance(text_color_threshold, (float, int)) - or not 0 <= text_color_threshold <= 1 - ): - msg = "`text_color_threshold` must be a value from 0 to 1." - raise ValueError(msg) - - with _mpl(Styler.background_gradient) as (plt, colors): - smin = np.nanmin(s.to_numpy()) if vmin is None else vmin - smax = np.nanmax(s.to_numpy()) if vmax is None else vmax - rng = smax - smin - # extend lower / upper bounds, compresses color range - norm = colors.Normalize(smin - (rng * low), smax + (rng * high)) - # matplotlib colors.Normalize modifies inplace? - # https://github.com/matplotlib/matplotlib/issues/5427 - rgbas = plt.cm.get_cmap(cmap)(norm(s.to_numpy(dtype=float))) - - def relative_luminance(rgba) -> float: - """ - Calculate relative luminance of a color. - - The calculation adheres to the W3C standards - (https://www.w3.org/WAI/GL/wiki/Relative_luminance) - - Parameters - ---------- - color : rgb or rgba tuple - - Returns - ------- - float - The relative luminance as a value from 0 to 1 - """ - r, g, b = ( - x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 - for x in rgba[:3] - ) - return 0.2126 * r + 0.7152 * g + 0.0722 * b - - def css(rgba) -> str: - dark = relative_luminance(rgba) < text_color_threshold - text_color = "#f1f1f1" if dark else "#000000" - return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};" - - if s.ndim == 1: - return [css(rgba) for rgba in rgbas] - else: - return DataFrame( - [[css(rgba) for rgba in row] for row in rgbas], - index=s.index, - columns=s.columns, - ) - def set_properties(self, subset=None, **kwargs) -> Styler: """ Set defined CSS-properties to each ``<td>`` HTML element within the given @@ -2346,3 +2353,119 @@ def pred(part) -> bool: else: slice_ = [part if pred(part) else [part] for part in slice_] return tuple(slice_) + + +def _validate_apply_axis_arg( + arg: FrameOrSeries | Sequence | np.ndarray, + arg_name: str, + dtype: Any | None, + data: FrameOrSeries, +) -> np.ndarray: + """ + For the apply-type methods, ``axis=None`` creates ``data`` as DataFrame, and for + ``axis=[1,0]`` it creates a Series. Where ``arg`` is expected as an element + of some operator with ``data`` we must make sure that the two are compatible shapes, + or raise. + + Parameters + ---------- + arg : sequence, Series or DataFrame + the user input arg + arg_name : string + name of the arg for use in error messages + dtype : numpy dtype, optional + forced numpy dtype if given + data : Series or DataFrame + underling subset of Styler data on which operations are performed + + Returns + ------- + ndarray + """ + dtype = {"dtype": dtype} if dtype else {} + # raise if input is wrong for axis: + if isinstance(arg, Series) and isinstance(data, DataFrame): + raise ValueError( + f"'{arg_name}' is a Series but underlying data for operations " + f"is a DataFrame since 'axis=None'" + ) + elif isinstance(arg, DataFrame) and isinstance(data, Series): + raise ValueError( + f"'{arg_name}' is a DataFrame but underlying data for " + f"operations is a Series with 'axis in [0,1]'" + ) + elif isinstance(arg, (Series, DataFrame)): # align indx / cols to data + arg = arg.reindex_like(data, method=None).to_numpy(**dtype) + else: + arg = np.asarray(arg, **dtype) + assert isinstance(arg, np.ndarray) # mypy requirement + if arg.shape != data.shape: # check valid input + raise ValueError( + f"supplied '{arg_name}' is not correct shape for data over " + f"selected 'axis': got {arg.shape}, " + f"expected {data.shape}" + ) + return arg + + +def _background_gradient( + data, + cmap="PuBu", + low: float = 0, + high: float = 0, + text_color_threshold: float = 0.408, + vmin: float | None = None, + vmax: float | None = None, + gmap: Sequence | np.ndarray | FrameOrSeries | None = None, +): + """ + Color background in a range according to the data or a gradient map + """ + if gmap is None: # the data is used the gmap + gmap = data.to_numpy(dtype=float) + else: # else validate gmap against the underlying data + gmap = _validate_apply_axis_arg(gmap, "gmap", float, data) + + with _mpl(Styler.background_gradient) as (plt, colors): + smin = np.nanmin(gmap) if vmin is None else vmin + smax = np.nanmax(gmap) if vmax is None else vmax + rng = smax - smin + # extend lower / upper bounds, compresses color range + norm = colors.Normalize(smin - (rng * low), smax + (rng * high)) + rgbas = plt.cm.get_cmap(cmap)(norm(gmap)) + + def relative_luminance(rgba) -> float: + """ + Calculate relative luminance of a color. + + The calculation adheres to the W3C standards + (https://www.w3.org/WAI/GL/wiki/Relative_luminance) + + Parameters + ---------- + color : rgb or rgba tuple + + Returns + ------- + float + The relative luminance as a value from 0 to 1 + """ + r, g, b = ( + x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 + for x in rgba[:3] + ) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + def css(rgba) -> str: + dark = relative_luminance(rgba) < text_color_threshold + text_color = "#f1f1f1" if dark else "#000000" + return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};" + + if data.ndim == 1: + return [css(rgba) for rgba in rgbas] + else: + return DataFrame( + [[css(rgba) for rgba in row] for row in rgbas], + index=data.index, + columns=data.columns, + ) diff --git a/pandas/tests/io/formats/style/test_matplotlib.py b/pandas/tests/io/formats/style/test_matplotlib.py index f01e818e40b22..f0158711664ce 100644 --- a/pandas/tests/io/formats/style/test_matplotlib.py +++ b/pandas/tests/io/formats/style/test_matplotlib.py @@ -57,15 +57,6 @@ def test_text_color_threshold(self, cmap, expected): for k in expected.keys(): assert result[k] == expected[k] - @pytest.mark.parametrize("text_color_threshold", [1.1, "1", -1, [2, 2]]) - def test_text_color_threshold_raises(self, text_color_threshold): - df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) - msg = "`text_color_threshold` must be a value from 0 to 1." - with pytest.raises(ValueError, match=msg): - df.style.background_gradient( - text_color_threshold=text_color_threshold - )._compute() - def test_background_gradient_axis(self): df = DataFrame([[1, 2], [2, 4]], columns=["A", "B"]) @@ -106,3 +97,131 @@ def test_background_gradient_int64(self): assert ctx2[(0, 0)] == ctx1[(0, 0)] assert ctx2[(1, 0)] == ctx1[(1, 0)] assert ctx2[(2, 0)] == ctx1[(2, 0)] + + @pytest.mark.parametrize( + "axis, gmap, expected", + [ + ( + 0, + [1, 2], + { + (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 0): [("background-color", "#023858"), ("color", "#f1f1f1")], + (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + }, + ), + ( + 1, + [1, 2], + { + (0, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (0, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + }, + ), + ( + None, + np.array([[2, 1], [1, 2]]), + { + (0, 0): [("background-color", "#023858"), ("color", "#f1f1f1")], + (1, 0): [("background-color", "#fff7fb"), ("color", "#000000")], + (0, 1): [("background-color", "#fff7fb"), ("color", "#000000")], + (1, 1): [("background-color", "#023858"), ("color", "#f1f1f1")], + }, + ), + ], + ) + def test_background_gradient_gmap_array(self, axis, gmap, expected): + # tests when gmap is given as a sequence and converted to ndarray + df = DataFrame([[0, 0], [0, 0]]) + result = df.style.background_gradient(axis=axis, gmap=gmap)._compute().ctx + assert result == expected + + @pytest.mark.parametrize( + "gmap, axis", [([1, 2, 3], 0), ([1, 2], 1), (np.array([[1, 2], [1, 2]]), None)] + ) + def test_background_gradient_gmap_array_raises(self, gmap, axis): + # test when gmap as converted ndarray is bad shape + df = DataFrame([[0, 0, 0], [0, 0, 0]]) + msg = "supplied 'gmap' is not correct shape" + with pytest.raises(ValueError, match=msg): + df.style.background_gradient(gmap=gmap, axis=axis)._compute() + + @pytest.mark.parametrize( + "gmap", + [ + DataFrame( # reverse the columns + [[2, 1], [1, 2]], columns=["B", "A"], index=["X", "Y"] + ), + DataFrame( # reverse the index + [[2, 1], [1, 2]], columns=["A", "B"], index=["Y", "X"] + ), + DataFrame( # reverse the index and columns + [[1, 2], [2, 1]], columns=["B", "A"], index=["Y", "X"] + ), + DataFrame( # add unnecessary columns + [[1, 2, 3], [2, 1, 3]], columns=["A", "B", "C"], index=["X", "Y"] + ), + DataFrame( # add unnecessary index + [[1, 2], [2, 1], [3, 3]], columns=["A", "B"], index=["X", "Y", "Z"] + ), + ], + ) + @pytest.mark.parametrize( + "subset, exp_gmap", # exp_gmap is underlying map DataFrame should conform to + [ + (None, [[1, 2], [2, 1]]), + (["A"], [[1], [2]]), # slice only column "A" in data and gmap + (["B", "A"], [[2, 1], [1, 2]]), # reverse the columns in data + (IndexSlice["X", :], [[1, 2]]), # slice only index "X" in data and gmap + (IndexSlice[["Y", "X"], :], [[2, 1], [1, 2]]), # reverse the index in data + ], + ) + def test_background_gradient_gmap_dataframe_align(self, gmap, subset, exp_gmap): + # test gmap given as DataFrame that it aligns to the the data including subset + df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"]) + + expected = df.style.background_gradient(axis=None, gmap=exp_gmap, subset=subset) + result = df.style.background_gradient(axis=None, gmap=gmap, subset=subset) + assert expected._compute().ctx == result._compute().ctx + + @pytest.mark.parametrize( + "gmap, axis, exp_gmap", + [ + (Series([2, 1], index=["Y", "X"]), 0, [[1, 1], [2, 2]]), # revrse the index + (Series([2, 1], index=["B", "A"]), 1, [[1, 2], [1, 2]]), # revrse the cols + (Series([1, 2, 3], index=["X", "Y", "Z"]), 0, [[1, 1], [2, 2]]), # add idx + (Series([1, 2, 3], index=["A", "B", "C"]), 1, [[1, 2], [1, 2]]), # add col + ], + ) + def test_background_gradient_gmap_series_align(self, gmap, axis, exp_gmap): + # test gmap given as Series that it aligns to the the data including subset + df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"]) + + expected = df.style.background_gradient(axis=None, gmap=exp_gmap)._compute() + result = df.style.background_gradient(axis=axis, gmap=gmap)._compute() + assert expected.ctx == result.ctx + + @pytest.mark.parametrize( + "gmap, axis", + [ + (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 1), + (DataFrame([[1, 2], [2, 1]], columns=["A", "B"], index=["X", "Y"]), 0), + ], + ) + def test_background_gradient_gmap_wrong_dataframe(self, gmap, axis): + # test giving a gmap in DataFrame but with wrong axis + df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"]) + msg = "'gmap' is a DataFrame but underlying data for operations is a Series" + with pytest.raises(ValueError, match=msg): + df.style.background_gradient(gmap=gmap, axis=axis)._compute() + + def test_background_gradient_gmap_wrong_series(self): + # test giving a gmap in Series form but with wrong axis + df = DataFrame([[0, 0], [0, 0]], columns=["A", "B"], index=["X", "Y"]) + msg = "'gmap' is a Series but underlying data for operations is a DataFrame" + gmap = Series([1, 2], index=["X", "Y"]) + with pytest.raises(ValueError, match=msg): + df.style.background_gradient(gmap=gmap, axis=None)._compute()
closes #22727 closes #28901 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry A very minor extension to the code and adding one argument gives the function a lot more scope: ![Screen Shot 2021-02-20 at 14 04 14](https://user-images.githubusercontent.com/24256554/108596326-a0779180-7384-11eb-97f5-60ea0a23bda1.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/39930
2021-02-20T12:39:29Z
2021-04-08T22:16:44Z
2021-04-08T22:16:44Z
2021-04-09T05:28:01Z
Updated read_html to add option
diff --git a/pandas/io/html.py b/pandas/io/html.py index 7541e5d62fd1e..45c4f37059787 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -172,6 +172,10 @@ class _HtmlFrameParser: displayed_only : bool Whether or not items with "display:none" should be ignored + + remove_whitespace : bool + Whether table row values should have all whitespace replaced with a space. + .. versionadded:: 1.3.0 Attributes ---------- @@ -190,6 +194,10 @@ class _HtmlFrameParser: displayed_only : bool Whether or not items with "display:none" should be ignored + + remove_whitespace : bool + Whether table row values should have all whitespace replaced with a space + .. versionadded:: 1.3.0 Notes ----- @@ -207,12 +215,13 @@ class _HtmlFrameParser: functionality. """ - def __init__(self, io, match, attrs, encoding, displayed_only): + def __init__(self, io, match, attrs, encoding, displayed_only, remove_whitespace): self.io = io self.match = match self.attrs = attrs self.encoding = encoding self.displayed_only = displayed_only + self.remove_whitespace = remove_whitespace def parse_tables(self): """ @@ -466,7 +475,10 @@ def _expand_colspan_rowspan(self, rows): index += 1 # Append the text from this <td>, colspan times - text = _remove_whitespace(self._text_getter(td)) + if self.remove_whitespace: + text = _remove_whitespace(self._text_getter(td)) + else: + text = self._text_getter(td) rowspan = int(self._attr_getter(td, "rowspan") or 1) colspan = int(self._attr_getter(td, "colspan") or 1) @@ -896,14 +908,14 @@ def _validate_flavor(flavor): return flavor -def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs): +def _parse(flavor, io, match, attrs, encoding, displayed_only, remove_whitespace, **kwargs): flavor = _validate_flavor(flavor) compiled_match = re.compile(match) # you can pass a compiled regex here retained = None for flav in flavor: parser = _parser_dispatch(flav) - p = parser(io, compiled_match, attrs, encoding, displayed_only) + p = parser(io, compiled_match, attrs, encoding, displayed_only, remove_whitespace) try: tables = p.parse_tables() @@ -954,6 +966,7 @@ def read_html( na_values=None, keep_default_na: bool = True, displayed_only: bool = True, + remove_whitespace: bool = True, ) -> List[DataFrame]: r""" Read HTML tables into a ``list`` of ``DataFrame`` objects. @@ -1045,6 +1058,10 @@ def read_html( displayed_only : bool, default True Whether elements with "display: none" should be parsed. + + remove_whitespace : bool, default True + Whether table row values should have all whitespace replaced with a space. + .. versionadded:: 1.3.0 Returns ------- @@ -1114,4 +1131,5 @@ def read_html( na_values=na_values, keep_default_na=keep_default_na, displayed_only=displayed_only, + remove_whitespace=remove_whitespace, )
Adds optional boolean parameter "remove_whitespace" to skip the remove_whitespace functionality. Defaults to true to support backwards compatibility. See https://github.com/pandas-dev/pandas/issues/24766 - [ x ] closes #24766 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39925
2021-02-20T04:41:01Z
2021-06-08T18:50:19Z
null
2021-06-08T18:50:20Z
REF: De-duplicate ExtensionIndex._validate_fill_value
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index b2c67ae2f0a00..afbddefae5e72 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -627,12 +627,6 @@ def insert(self, loc: int, item): result._data._freq = self._get_insert_freq(loc, item) return result - def _validate_fill_value(self, value): - """ - Convert value to be insertable to ndarray. - """ - return self._data._validate_setitem_value(value) - # -------------------------------------------------------------------- # Join/Set Methods diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 0097959245686..f1418869713d6 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -4,6 +4,7 @@ from typing import ( List, TypeVar, + Union, ) import numpy as np @@ -25,7 +26,7 @@ ABCSeries, ) -from pandas.core.arrays import ExtensionArray +from pandas.core.arrays import IntervalArray from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.indexers import deprecate_ndim_indexing from pandas.core.indexes.base import Index @@ -216,7 +217,7 @@ class ExtensionIndex(Index): # The base class already passes through to _data: # size, __len__, dtype - _data: ExtensionArray + _data: Union[IntervalArray, NDArrayBackedExtensionArray] __eq__ = _make_wrapped_comparison_op("__eq__") __ne__ = _make_wrapped_comparison_op("__ne__") @@ -240,8 +241,7 @@ def __getitem__(self, key): return type(self)(result, name=self.name) # Unpack to ndarray for MPL compat - # error: "ExtensionArray" has no attribute "_data" - result = result._data # type: ignore[attr-defined] + result = result._ndarray # Includes cases where we get a 2D ndarray back for MPL compat deprecate_ndim_indexing(result) @@ -276,6 +276,12 @@ def insert(self, loc: int, item): # ExtensionIndex subclasses must override Index.insert raise AbstractMethodError(self) + def _validate_fill_value(self, value): + """ + Convert value to be insertable to underlying array. + """ + return self._data._validate_setitem_value(value) + def _get_unique_index(self): if self.is_unique: return self diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c2fabfc332b23..ace9b5b592900 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1036,9 +1036,6 @@ def func(self, other, sort=sort): # -------------------------------------------------------------------- - def _validate_fill_value(self, value): - return self._data._validate_setitem_value(value) - @property def _is_all_dates(self) -> bool: """
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39923
2021-02-20T03:35:00Z
2021-02-21T17:26:47Z
2021-02-21T17:26:47Z
2021-02-21T17:29:14Z
BENCH: collect isin asvs
diff --git a/asv_bench/benchmarks/algos/__init__.py b/asv_bench/benchmarks/algos/__init__.py new file mode 100644 index 0000000000000..97c9ab09b9c6b --- /dev/null +++ b/asv_bench/benchmarks/algos/__init__.py @@ -0,0 +1,12 @@ +""" +algos/ directory is intended for individual functions from core.algorithms + +In many cases these algorithms are reachable in multiple ways: + algos.foo(x, y) + Series(x).foo(y) + Index(x).foo(y) + pd.array(x).foo(y) + +In most cases we profile the Series variant directly, trusting the performance +of the others to be highly correlated. +""" diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py new file mode 100644 index 0000000000000..5d81d9d0d45a3 --- /dev/null +++ b/asv_bench/benchmarks/algos/isin.py @@ -0,0 +1,317 @@ +import numpy as np + +from pandas.compat.numpy import np_version_under1p20 + +from pandas import ( + Categorical, + NaT, + Series, + date_range, +) + + +class IsIn: + + params = [ + "int64", + "uint64", + "object", + "Int64", + "boolean", + "bool", + "datetime64[ns]", + "category[object]", + "category[int]", + ] + param_names = ["dtype"] + + def setup(self, dtype): + N = 10000 + + self.mismatched = [NaT.to_datetime64()] * 2 + + if dtype in ["boolean", "bool"]: + self.series = Series(np.random.randint(0, 2, N)).astype(dtype) + self.values = [True, False] + + elif dtype == "datetime64[ns]": + # Note: values here is much larger than non-dt64ns cases + + # dti has length=115777 + dti = date_range(start="2015-10-26", end="2016-01-01", freq="50s") + self.series = Series(dti) + self.values = self.series._values[::3] + self.mismatched = [1, 2] + + elif dtype in ["category[object]", "category[int]"]: + # Note: sizes are different in this case than others + np.random.seed(1234) + + n = 5 * 10 ** 5 + sample_size = 100 + + arr = list(np.random.randint(0, n // 10, size=n)) + if dtype == "category[object]": + arr = [f"s{i:04d}" for i in arr] + + self.values = np.random.choice(arr, sample_size) + self.series = Series(arr).astype("category") + + else: + self.series = Series(np.random.randint(1, 10, N)).astype(dtype) + self.values = [1, 2] + + self.cat_values = Categorical(self.values) + + def time_isin(self, dtype): + self.series.isin(self.values) + + def time_isin_categorical(self, dtype): + self.series.isin(self.cat_values) + + def time_isin_empty(self, dtype): + self.series.isin([]) + + def time_isin_mismatched_dtype(self, dtype): + self.series.isin(self.mismatched) + + +class IsinAlmostFullWithRandomInt: + params = [ + [np.float64, np.int64, np.uint64, np.object_], + range(10, 21), + ["inside", "outside"], + ] + param_names = ["dtype", "exponent", "title"] + + def setup(self, dtype, exponent, title): + M = 3 * 2 ** (exponent - 2) + # 0.77-the maximal share of occupied buckets + np.random.seed(42) + self.series = Series(np.random.randint(0, M, M)).astype(dtype) + + values = np.random.randint(0, M, M).astype(dtype) + if title == "inside": + self.values = values + elif title == "outside": + self.values = values + M + else: + raise ValueError(title) + + def time_isin(self, dtype, exponent, title): + self.series.isin(self.values) + + +class IsinWithRandomFloat: + params = [ + [np.float64, np.object], + [ + 1_300, + 2_000, + 7_000, + 8_000, + 70_000, + 80_000, + 750_000, + 900_000, + ], + ["inside", "outside"], + ] + param_names = ["dtype", "size", "title"] + + def setup(self, dtype, size, title): + np.random.seed(42) + self.values = np.random.rand(size) + self.series = Series(self.values).astype(dtype) + np.random.shuffle(self.values) + + if title == "outside": + self.values = self.values + 0.1 + + def time_isin(self, dtype, size, title): + self.series.isin(self.values) + + +class IsinWithArangeSorted: + params = [ + [np.float64, np.int64, np.uint64, np.object], + [ + 1_000, + 2_000, + 8_000, + 100_000, + 1_000_000, + ], + ] + param_names = ["dtype", "size"] + + def setup(self, dtype, size): + self.series = Series(np.arange(size)).astype(dtype) + self.values = np.arange(size).astype(dtype) + + def time_isin(self, dtype, size): + self.series.isin(self.values) + + +class IsinWithArange: + params = [ + [np.float64, np.int64, np.uint64, np.object], + [ + 1_000, + 2_000, + 8_000, + ], + [-2, 0, 2], + ] + param_names = ["dtype", "M", "offset_factor"] + + def setup(self, dtype, M, offset_factor): + offset = int(M * offset_factor) + np.random.seed(42) + tmp = Series(np.random.randint(offset, M + offset, 10 ** 6)) + self.series = tmp.astype(dtype) + self.values = np.arange(M).astype(dtype) + + def time_isin(self, dtype, M, offset_factor): + self.series.isin(self.values) + + +class IsInFloat64: + + params = [ + [np.float64, "Float64"], + ["many_different_values", "few_different_values", "only_nans_values"], + ] + param_names = ["dtype", "title"] + + def setup(self, dtype, title): + N_many = 10 ** 5 + N_few = 10 ** 6 + self.series = Series([1, 2], dtype=dtype) + + if title == "many_different_values": + # runtime is dominated by creation of the lookup-table + self.values = np.arange(N_many, dtype=np.float64) + elif title == "few_different_values": + # runtime is dominated by creation of the lookup-table + self.values = np.zeros(N_few, dtype=np.float64) + elif title == "only_nans_values": + # runtime is dominated by creation of the lookup-table + self.values = np.full(N_few, np.nan, dtype=np.float64) + else: + raise ValueError(title) + + def time_isin(self, dtype, title): + self.series.isin(self.values) + + +class IsInForObjects: + """ + A subset of the cartesian product of cases have special motivations: + + "nans" x "nans" + if nan-objects are different objects, + this has the potential to trigger O(n^2) running time + + "short" x "long" + running time dominated by the preprocessing + + "long" x "short" + running time dominated by look-up + + "long" x "long" + no dominating part + + "long_floats" x "long_floats" + because of nans floats are special + no dominating part + + """ + + variants = ["nans", "short", "long", "long_floats"] + + params = [variants, variants] + param_names = ["series_type", "vals_type"] + + def setup(self, series_type, vals_type): + N_many = 10 ** 5 + + if series_type == "nans": + ser_vals = np.full(10 ** 4, np.nan) + elif series_type == "short": + ser_vals = np.arange(2) + elif series_type == "long": + ser_vals = np.arange(N_many) + elif series_type == "long_floats": + ser_vals = np.arange(N_many, dtype=np.float_) + + self.series = Series(ser_vals).astype(object) + + if vals_type == "nans": + values = np.full(10 ** 4, np.nan) + elif vals_type == "short": + values = np.arange(2) + elif vals_type == "long": + values = np.arange(N_many) + elif vals_type == "long_floats": + values = np.arange(N_many, dtype=np.float_) + + self.values = values.astype(object) + + def time_isin(self, series_type, vals_type): + self.series.isin(self.values) + + +class IsInLongSeriesLookUpDominates: + params = [ + ["int64", "int32", "float64", "float32", "object", "Int64", "Float64"], + [5, 1000], + ["random_hits", "random_misses", "monotone_hits", "monotone_misses"], + ] + param_names = ["dtype", "MaxNumber", "series_type"] + + def setup(self, dtype, MaxNumber, series_type): + N = 10 ** 7 + + if not np_version_under1p20 and dtype in ("Int64", "Float64"): + raise NotImplementedError + + if series_type == "random_hits": + np.random.seed(42) + array = np.random.randint(0, MaxNumber, N) + if series_type == "random_misses": + np.random.seed(42) + array = np.random.randint(0, MaxNumber, N) + MaxNumber + if series_type == "monotone_hits": + array = np.repeat(np.arange(MaxNumber), N // MaxNumber) + if series_type == "monotone_misses": + array = np.arange(N) + MaxNumber + + self.series = Series(array).astype(dtype) + self.values = np.arange(MaxNumber).astype(dtype) + + def time_isin(self, dtypes, MaxNumber, series_type): + self.series.isin(self.values) + + +class IsInLongSeriesValuesDominate: + params = [ + ["int64", "int32", "float64", "float32", "object", "Int64", "Float64"], + ["random", "monotone"], + ] + param_names = ["dtype", "series_type"] + + def setup(self, dtype, series_type): + N = 10 ** 7 + if series_type == "random": + np.random.seed(42) + vals = np.random.randint(0, 10 * N, N) + if series_type == "monotone": + vals = np.arange(N) + + self.values = vals.astype(dtype) + M = 10 ** 6 + 1 + self.series = Series(np.arange(M)).astype(dtype) + + def time_isin(self, dtypes, series_type): + self.series.isin(self.values) diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 4e32b6e496929..268f25c3d12e3 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -220,25 +220,6 @@ def time_rank_int_cat_ordered(self): self.s_int_cat_ordered.rank() -class Isin: - - params = ["object", "int64"] - param_names = ["dtype"] - - def setup(self, dtype): - np.random.seed(1234) - n = 5 * 10 ** 5 - sample_size = 100 - arr = list(np.random.randint(0, n // 10, size=n)) - if dtype == "object": - arr = [f"s{i:04d}" for i in arr] - self.sample = np.random.choice(arr, sample_size) - self.series = pd.Series(arr).astype("category") - - def time_isin_categorical(self, dtype): - self.series.isin(self.sample) - - class IsMonotonic: def setup(self): N = 1000 diff --git a/asv_bench/benchmarks/hash_functions.py b/asv_bench/benchmarks/hash_functions.py index 3743882b936e2..394433f7c8f99 100644 --- a/asv_bench/benchmarks/hash_functions.py +++ b/asv_bench/benchmarks/hash_functions.py @@ -3,28 +3,6 @@ import pandas as pd -class IsinAlmostFullWithRandomInt: - params = [ - [np.float64, np.int64, np.uint64, np.object], - range(10, 21), - ] - param_names = ["dtype", "exponent"] - - def setup(self, dtype, exponent): - M = 3 * 2 ** (exponent - 2) - # 0.77-the maximal share of occupied buckets - np.random.seed(42) - self.s = pd.Series(np.random.randint(0, M, M)).astype(dtype) - self.values = np.random.randint(0, M, M).astype(dtype) - self.values_outside = self.values + M - - def time_isin(self, dtype, exponent): - self.s.isin(self.values) - - def time_isin_outside(self, dtype, exponent): - self.s.isin(self.values_outside) - - class UniqueForLargePyObjectInts: def setup(self): lst = [x << 32 for x in range(5000)] @@ -34,80 +12,6 @@ def time_unique(self): pd.unique(self.arr) -class IsinWithRandomFloat: - params = [ - [np.float64, np.object], - [ - 1_300, - 2_000, - 7_000, - 8_000, - 70_000, - 80_000, - 750_000, - 900_000, - ], - ] - param_names = ["dtype", "M"] - - def setup(self, dtype, M): - np.random.seed(42) - self.values = np.random.rand(M) - self.s = pd.Series(self.values).astype(dtype) - np.random.shuffle(self.values) - self.values_outside = self.values + 0.1 - - def time_isin(self, dtype, M): - self.s.isin(self.values) - - def time_isin_outside(self, dtype, M): - self.s.isin(self.values_outside) - - -class IsinWithArangeSorted: - params = [ - [np.float64, np.int64, np.uint64, np.object], - [ - 1_000, - 2_000, - 8_000, - 100_000, - 1_000_000, - ], - ] - param_names = ["dtype", "M"] - - def setup(self, dtype, M): - self.s = pd.Series(np.arange(M)).astype(dtype) - self.values = np.arange(M).astype(dtype) - - def time_isin(self, dtype, M): - self.s.isin(self.values) - - -class IsinWithArange: - params = [ - [np.float64, np.int64, np.uint64, np.object], - [ - 1_000, - 2_000, - 8_000, - ], - [-2, 0, 2], - ] - param_names = ["dtype", "M", "offset_factor"] - - def setup(self, dtype, M, offset_factor): - offset = int(M * offset_factor) - np.random.seed(42) - tmp = pd.Series(np.random.randint(offset, M + offset, 10 ** 6)) - self.s = tmp.astype(dtype) - self.values = np.arange(M).astype(dtype) - - def time_isin(self, dtype, M, offset_factor): - self.s.isin(self.values) - - class Float64GroupIndex: # GH28303 def setup(self): diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index a6bffb1585f2a..d05a28e0873d0 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -2,10 +2,7 @@ import numpy as np -from pandas.compat.numpy import np_version_under1p20 - from pandas import ( - Categorical, NaT, Series, date_range, @@ -30,169 +27,6 @@ def time_constructor(self, data): Series(data=self.data, index=self.idx) -class IsIn: - - params = ["int64", "uint64", "object", "Int64"] - param_names = ["dtype"] - - def setup(self, dtype): - N = 10000 - self.s = Series(np.random.randint(1, 10, N)).astype(dtype) - self.values = [1, 2] - - def time_isin(self, dtypes): - self.s.isin(self.values) - - -class IsInBoolean: - - params = ["boolean", "bool"] - param_names = ["dtype"] - - def setup(self, dtype): - N = 10000 - self.s = Series(np.random.randint(0, 2, N)).astype(dtype) - self.values = [True, False] - - def time_isin(self, dtypes): - self.s.isin(self.values) - - -class IsInDatetime64: - def setup(self): - dti = date_range( - start=datetime(2015, 10, 26), end=datetime(2016, 1, 1), freq="50s" - ) - self.ser = Series(dti) - self.subset = self.ser._values[::3] - self.cat_subset = Categorical(self.subset) - - def time_isin(self): - self.ser.isin(self.subset) - - def time_isin_cat_values(self): - self.ser.isin(self.cat_subset) - - def time_isin_mismatched_dtype(self): - self.ser.isin([1, 2]) - - def time_isin_empty(self): - self.ser.isin([]) - - -class IsInFloat64: - - params = [np.float64, "Float64"] - param_names = ["dtype"] - - def setup(self, dtype): - N_many = 10 ** 5 - N_few = 10 ** 6 - self.small = Series([1, 2], dtype=dtype) - self.many_different_values = np.arange(N_many, dtype=np.float64) - self.few_different_values = np.zeros(N_few, dtype=np.float64) - self.only_nans_values = np.full(N_few, np.nan, dtype=np.float64) - - def time_isin_many_different(self, dtypes): - # runtime is dominated by creation of the lookup-table - self.small.isin(self.many_different_values) - - def time_isin_few_different(self, dtypes): - # runtime is dominated by creation of the lookup-table - self.small.isin(self.few_different_values) - - def time_isin_nan_values(self, dtypes): - # runtime is dominated by creation of the lookup-table - self.small.isin(self.few_different_values) - - -class IsInForObjects: - def setup(self): - self.s_nans = Series(np.full(10 ** 4, np.nan)).astype(object) - self.vals_nans = np.full(10 ** 4, np.nan).astype(object) - self.s_short = Series(np.arange(2)).astype(object) - self.s_long = Series(np.arange(10 ** 5)).astype(object) - self.vals_short = np.arange(2).astype(object) - self.vals_long = np.arange(10 ** 5).astype(object) - # because of nans floats are special: - self.s_long_floats = Series(np.arange(10 ** 5, dtype=np.float_)).astype(object) - self.vals_long_floats = np.arange(10 ** 5, dtype=np.float_).astype(object) - - def time_isin_nans(self): - # if nan-objects are different objects, - # this has the potential to trigger O(n^2) running time - self.s_nans.isin(self.vals_nans) - - def time_isin_short_series_long_values(self): - # running time dominated by the preprocessing - self.s_short.isin(self.vals_long) - - def time_isin_long_series_short_values(self): - # running time dominated by look-up - self.s_long.isin(self.vals_short) - - def time_isin_long_series_long_values(self): - # no dominating part - self.s_long.isin(self.vals_long) - - def time_isin_long_series_long_values_floats(self): - # no dominating part - self.s_long_floats.isin(self.vals_long_floats) - - -class IsInLongSeriesLookUpDominates: - params = [ - ["int64", "int32", "float64", "float32", "object", "Int64", "Float64"], - [5, 1000], - ["random_hits", "random_misses", "monotone_hits", "monotone_misses"], - ] - param_names = ["dtype", "MaxNumber", "series_type"] - - def setup(self, dtype, MaxNumber, series_type): - N = 10 ** 7 - - if not np_version_under1p20 and dtype in ("Int64", "Float64"): - raise NotImplementedError - - if series_type == "random_hits": - np.random.seed(42) - array = np.random.randint(0, MaxNumber, N) - if series_type == "random_misses": - np.random.seed(42) - array = np.random.randint(0, MaxNumber, N) + MaxNumber - if series_type == "monotone_hits": - array = np.repeat(np.arange(MaxNumber), N // MaxNumber) - if series_type == "monotone_misses": - array = np.arange(N) + MaxNumber - self.series = Series(array).astype(dtype) - self.values = np.arange(MaxNumber).astype(dtype) - - def time_isin(self, dtypes, MaxNumber, series_type): - self.series.isin(self.values) - - -class IsInLongSeriesValuesDominate: - params = [ - ["int64", "int32", "float64", "float32", "object", "Int64", "Float64"], - ["random", "monotone"], - ] - param_names = ["dtype", "series_type"] - - def setup(self, dtype, series_type): - N = 10 ** 7 - if series_type == "random": - np.random.seed(42) - vals = np.random.randint(0, 10 * N, N) - if series_type == "monotone": - vals = np.arange(N) - self.values = vals.astype(dtype) - M = 10 ** 6 + 1 - self.series = Series(np.arange(M)).astype(dtype) - - def time_isin(self, dtypes, series_type): - self.series.isin(self.values) - - class NSort: params = ["first", "last", "all"]
Pushes these as far towards parametrization as I can get them. We end up adding a few cases, dropping none. Decides on a policy to benchmark Series.isin and leave the others alone (see `algos/__init__.py`)
https://api.github.com/repos/pandas-dev/pandas/pulls/39922
2021-02-20T00:15:21Z
2021-02-21T17:27:47Z
2021-02-21T17:27:47Z
2021-02-21T17:37:28Z
TYP: create a Frequency alias in _typing
diff --git a/pandas/_typing.py b/pandas/_typing.py index 074b57054c0d1..c50d532f40dd7 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -64,6 +64,7 @@ from pandas.core.window.rolling import BaseWindow from pandas.io.formats.format import EngFormatter + from pandas.tseries.offsets import DateOffset else: # typing.final does not exist until py38 final = lambda x: x @@ -110,6 +111,7 @@ Suffixes = Tuple[str, str] Ordered = Optional[bool] JSONSerializable = Optional[Union[PythonScalar, List, Dict]] +Frequency = Union[str, "DateOffset"] Axes = Collection[Any] # dtypes diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3fe330f659513..3c872bdedbc02 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -63,6 +63,7 @@ FloatFormatType, FormattersType, FrameOrSeriesUnion, + Frequency, IndexKeyFunc, IndexLabel, Level, @@ -4678,7 +4679,11 @@ def _replace_columnwise( @doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"]) def shift( - self, periods=1, freq=None, axis: Axis = 0, fill_value=lib.no_default + self, + periods=1, + freq: Optional[Frequency] = None, + axis: Axis = 0, + fill_value=lib.no_default, ) -> DataFrame: axis = self._get_axis_number(axis) @@ -9499,7 +9504,7 @@ def quantile( @doc(NDFrame.asfreq, **_shared_doc_kwargs) def asfreq( self, - freq, + freq: Frequency, method=None, how: Optional[str] = None, normalize: bool = False, @@ -9545,7 +9550,11 @@ def resample( ) def to_timestamp( - self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True + self, + freq: Optional[Frequency] = None, + how: str = "start", + axis: Axis = 0, + copy: bool = True, ) -> DataFrame: """ Cast to DatetimeIndex of timestamps, at *beginning* of period. @@ -9578,7 +9587,9 @@ def to_timestamp( setattr(new_obj, axis_name, new_ax) return new_obj - def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> DataFrame: + def to_period( + self, freq: Optional[Frequency] = None, axis: Axis = 0, copy: bool = True + ) -> DataFrame: """ Convert DataFrame from DatetimeIndex to PeriodIndex.
- [ ] closes #xxxx - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Spinning off a piece of #38416
https://api.github.com/repos/pandas-dev/pandas/pulls/39919
2021-02-19T21:29:43Z
2021-02-21T17:56:08Z
2021-02-21T17:56:08Z
2021-02-21T17:56:15Z
BENCH: collect low-dependency asvs
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index 65e52e03c43c7..823daa2e31529 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -2,8 +2,6 @@ import numpy as np -from pandas._libs import lib - import pandas as pd from .pandas_vb_common import tm @@ -16,19 +14,6 @@ pass -class MaybeConvertObjects: - def setup(self): - N = 10 ** 5 - - data = list(range(N)) - data[0] = pd.NaT - data = np.array(data) - self.data = data - - def time_maybe_convert_objects(self): - lib.maybe_convert_objects(self.data) - - class Factorize: params = [ diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py index 9c7b107b478d4..d4366c42f96aa 100644 --- a/asv_bench/benchmarks/attrs_caching.py +++ b/asv_bench/benchmarks/attrs_caching.py @@ -3,11 +3,6 @@ import pandas as pd from pandas import DataFrame -try: - from pandas.util import cache_readonly -except ImportError: - from pandas.util.decorators import cache_readonly - try: from pandas.core.construction import extract_array except ImportError: @@ -53,17 +48,4 @@ def time_extract_array_numpy(self, dtype): extract_array(self.series, extract_numpy=True) -class CacheReadonly: - def setup(self): - class Foo: - @cache_readonly - def prop(self): - return 5 - - self.obj = Foo() - - def time_cache_readonly(self): - self.obj.prop - - from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py index 9209e851289bb..c561b80ed1ca6 100644 --- a/asv_bench/benchmarks/dtypes.py +++ b/asv_bench/benchmarks/dtypes.py @@ -13,7 +13,6 @@ from .pandas_vb_common import ( datetime_dtypes, extension_dtypes, - lib, numeric_dtypes, string_dtypes, ) @@ -49,27 +48,6 @@ def time_pandas_dtype_invalid(self, dtype): pass -class InferDtypes: - param_names = ["dtype"] - data_dict = { - "np-object": np.array([1] * 100000, dtype="O"), - "py-object": [1] * 100000, - "np-null": np.array([1] * 50000 + [np.nan] * 50000), - "py-null": [1] * 50000 + [None] * 50000, - "np-int": np.array([1] * 100000, dtype=int), - "np-floating": np.array([1.0] * 100000, dtype=float), - "empty": [], - "bytes": [b"a"] * 100000, - } - params = list(data_dict.keys()) - - def time_infer_skipna(self, dtype): - lib.infer_dtype(self.data_dict[dtype], skipna=True) - - def time_infer(self, dtype): - lib.infer_dtype(self.data_dict[dtype], skipna=False) - - class SelectDtypes: params = [ diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index 410668ca3c7cf..459046d2decfb 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -125,6 +125,7 @@ def time_take1d(self, dtype): class ParallelKth: + # This depends exclusively on code in _libs/, could go in libs.py number = 1 repeat = 5 diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py index 44a22dfa77791..30ef7f63dc0dc 100644 --- a/asv_bench/benchmarks/indexing_engines.py +++ b/asv_bench/benchmarks/indexing_engines.py @@ -1,3 +1,10 @@ +""" +Benchmarks in this fiel depend exclusively on code in _libs/ + +If a PR does not edit anything in _libs, it is very unlikely that benchmarks +in this file will be affected. +""" + import numpy as np from pandas._libs import index as libindex diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py index b6808ace629db..0aa924dabd469 100644 --- a/asv_bench/benchmarks/inference.py +++ b/asv_bench/benchmarks/inference.py @@ -1,8 +1,20 @@ +""" +The functions benchmarked in this file depend _almost_ exclusively on +_libs, but not in a way that is easy to formalize. + +If a PR does not change anything in pandas/_libs/ or pandas/core/tools/, then +it is likely that these benchmarks will be unaffected. +""" + import numpy as np from pandas import ( + NaT, Series, + date_range, + to_datetime, to_numeric, + to_timedelta, ) from .pandas_vb_common import ( @@ -69,6 +81,9 @@ def time_downcast(self, dtype, downcast): class MaybeConvertNumeric: + # maybe_convert_numeric depends _exclusively_ on _libs, could + # go in benchmarks/libs.py + def setup_cache(self): N = 10 ** 6 arr = np.repeat([2 ** 63], N) + np.arange(N).astype("uint64") @@ -81,4 +96,205 @@ def time_convert(self, data): lib.maybe_convert_numeric(data, set(), coerce_numeric=False) +class MaybeConvertObjects: + # maybe_convert_objects depends _almost_ exclusively on _libs, but + # does have some run-time imports from outside of _libs + + def setup(self): + N = 10 ** 5 + + data = list(range(N)) + data[0] = NaT + data = np.array(data) + self.data = data + + def time_maybe_convert_objects(self): + lib.maybe_convert_objects(self.data) + + +class ToDatetimeFromIntsFloats: + def setup(self): + self.ts_sec = Series(range(1521080307, 1521685107), dtype="int64") + self.ts_sec_float = self.ts_sec.astype("float64") + + self.ts_nanosec = 1_000_000 * self.ts_sec + self.ts_nanosec_float = self.ts_nanosec.astype("float64") + + # speed of int64 and float64 paths should be comparable + + def time_nanosec_int64(self): + to_datetime(self.ts_nanosec, unit="ns") + + def time_nanosec_float64(self): + to_datetime(self.ts_nanosec_float, unit="ns") + + def time_sec_int64(self): + to_datetime(self.ts_sec, unit="s") + + def time_sec_float64(self): + to_datetime(self.ts_sec_float, unit="s") + + +class ToDatetimeYYYYMMDD: + def setup(self): + rng = date_range(start="1/1/2000", periods=10000, freq="D") + self.stringsD = Series(rng.strftime("%Y%m%d")) + + def time_format_YYYYMMDD(self): + to_datetime(self.stringsD, format="%Y%m%d") + + +class ToDatetimeCacheSmallCount: + + params = ([True, False], [50, 500, 5000, 100000]) + param_names = ["cache", "count"] + + def setup(self, cache, count): + rng = date_range(start="1/1/1971", periods=count) + self.unique_date_strings = rng.strftime("%Y-%m-%d").tolist() + + def time_unique_date_strings(self, cache, count): + to_datetime(self.unique_date_strings, cache=cache) + + +class ToDatetimeISO8601: + def setup(self): + rng = date_range(start="1/1/2000", periods=20000, freq="H") + self.strings = rng.strftime("%Y-%m-%d %H:%M:%S").tolist() + self.strings_nosep = rng.strftime("%Y%m%d %H:%M:%S").tolist() + self.strings_tz_space = [ + x.strftime("%Y-%m-%d %H:%M:%S") + " -0800" for x in rng + ] + + def time_iso8601(self): + to_datetime(self.strings) + + def time_iso8601_nosep(self): + to_datetime(self.strings_nosep) + + def time_iso8601_format(self): + to_datetime(self.strings, format="%Y-%m-%d %H:%M:%S") + + def time_iso8601_format_no_sep(self): + to_datetime(self.strings_nosep, format="%Y%m%d %H:%M:%S") + + def time_iso8601_tz_spaceformat(self): + to_datetime(self.strings_tz_space) + + +class ToDatetimeNONISO8601: + def setup(self): + N = 10000 + half = N // 2 + ts_string_1 = "March 1, 2018 12:00:00+0400" + ts_string_2 = "March 1, 2018 12:00:00+0500" + self.same_offset = [ts_string_1] * N + self.diff_offset = [ts_string_1] * half + [ts_string_2] * half + + def time_same_offset(self): + to_datetime(self.same_offset) + + def time_different_offset(self): + to_datetime(self.diff_offset) + + +class ToDatetimeFormatQuarters: + def setup(self): + self.s = Series(["2Q2005", "2Q05", "2005Q1", "05Q1"] * 10000) + + def time_infer_quarter(self): + to_datetime(self.s) + + +class ToDatetimeFormat: + def setup(self): + N = 100000 + self.s = Series(["19MAY11", "19MAY11:00:00:00"] * N) + self.s2 = self.s.str.replace(":\\S+$", "") + + self.same_offset = ["10/11/2018 00:00:00.045-07:00"] * N + self.diff_offset = [ + f"10/11/2018 00:00:00.045-0{offset}:00" for offset in range(10) + ] * (N // 10) + + def time_exact(self): + to_datetime(self.s2, format="%d%b%y") + + def time_no_exact(self): + to_datetime(self.s, format="%d%b%y", exact=False) + + def time_same_offset(self): + to_datetime(self.same_offset, format="%m/%d/%Y %H:%M:%S.%f%z") + + def time_different_offset(self): + to_datetime(self.diff_offset, format="%m/%d/%Y %H:%M:%S.%f%z") + + def time_same_offset_to_utc(self): + to_datetime(self.same_offset, format="%m/%d/%Y %H:%M:%S.%f%z", utc=True) + + def time_different_offset_to_utc(self): + to_datetime(self.diff_offset, format="%m/%d/%Y %H:%M:%S.%f%z", utc=True) + + +class ToDatetimeCache: + + params = [True, False] + param_names = ["cache"] + + def setup(self, cache): + N = 10000 + self.unique_numeric_seconds = list(range(N)) + self.dup_numeric_seconds = [1000] * N + self.dup_string_dates = ["2000-02-11"] * N + self.dup_string_with_tz = ["2000-02-11 15:00:00-0800"] * N + + def time_unique_seconds_and_unit(self, cache): + to_datetime(self.unique_numeric_seconds, unit="s", cache=cache) + + def time_dup_seconds_and_unit(self, cache): + to_datetime(self.dup_numeric_seconds, unit="s", cache=cache) + + def time_dup_string_dates(self, cache): + to_datetime(self.dup_string_dates, cache=cache) + + def time_dup_string_dates_and_format(self, cache): + to_datetime(self.dup_string_dates, format="%Y-%m-%d", cache=cache) + + def time_dup_string_tzoffset_dates(self, cache): + to_datetime(self.dup_string_with_tz, cache=cache) + + +class ToTimedelta: + def setup(self): + self.ints = np.random.randint(0, 60, size=10000) + self.str_days = [] + self.str_seconds = [] + for i in self.ints: + self.str_days.append(f"{i} days") + self.str_seconds.append(f"00:00:{i:02d}") + + def time_convert_int(self): + to_timedelta(self.ints, unit="s") + + def time_convert_string_days(self): + to_timedelta(self.str_days) + + def time_convert_string_seconds(self): + to_timedelta(self.str_seconds) + + +class ToTimedeltaErrors: + + params = ["coerce", "ignore"] + param_names = ["errors"] + + def setup(self, errors): + ints = np.random.randint(0, 60, size=10000) + self.arr = [f"{i} days" for i in ints] + self.arr[-1] = "apple" + + def time_convert(self, errors): + to_timedelta(self.arr, errors=errors) + + from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/libs.py b/asv_bench/benchmarks/libs.py index f5c2397945cea..4e3f938a33eb1 100644 --- a/asv_bench/benchmarks/libs.py +++ b/asv_bench/benchmarks/libs.py @@ -1,10 +1,14 @@ """ Benchmarks for code in pandas/_libs, excluding pandas/_libs/tslibs, -which has its own directory +which has its own directory. + +If a PR does not edit anything in _libs/, then it is unlikely that thes +benchmarks will be affected. """ import numpy as np from pandas._libs.lib import ( + infer_dtype, is_list_like, is_scalar, ) @@ -14,6 +18,17 @@ NaT, ) +from .pandas_vb_common import ( + lib, + tm, +) + +try: + from pandas.util import cache_readonly +except ImportError: + from pandas.util.decorators import cache_readonly + + # TODO: share with something in pd._testing? scalars = [ 0, @@ -40,3 +55,52 @@ def time_is_list_like(self, param): def time_is_scalar(self, param): is_scalar(param) + + +class FastZip: + def setup(self): + N = 10000 + K = 10 + key1 = tm.makeStringIndex(N).values.repeat(K) + key2 = tm.makeStringIndex(N).values.repeat(K) + col_array = np.vstack([key1, key2, np.random.randn(N * K)]) + col_array2 = col_array.copy() + col_array2[:, :10000] = np.nan + self.col_array_list = list(col_array) + + def time_lib_fast_zip(self): + lib.fast_zip(self.col_array_list) + + +class InferDtype: + param_names = ["dtype"] + data_dict = { + "np-object": np.array([1] * 100000, dtype="O"), + "py-object": [1] * 100000, + "np-null": np.array([1] * 50000 + [np.nan] * 50000), + "py-null": [1] * 50000 + [None] * 50000, + "np-int": np.array([1] * 100000, dtype=int), + "np-floating": np.array([1.0] * 100000, dtype=float), + "empty": [], + "bytes": [b"a"] * 100000, + } + params = list(data_dict.keys()) + + def time_infer_dtype_skipna(self, dtype): + infer_dtype(self.data_dict[dtype], skipna=True) + + def time_infer_dtype(self, dtype): + infer_dtype(self.data_dict[dtype], skipna=False) + + +class CacheReadonly: + def setup(self): + class Foo: + @cache_readonly + def prop(self): + return 5 + + self.obj = Foo() + + def time_cache_readonly(self): + self.obj.prop diff --git a/asv_bench/benchmarks/reindex.py b/asv_bench/benchmarks/reindex.py index 65392f2cea65b..5181b983c9f7a 100644 --- a/asv_bench/benchmarks/reindex.py +++ b/asv_bench/benchmarks/reindex.py @@ -9,10 +9,7 @@ period_range, ) -from .pandas_vb_common import ( - lib, - tm, -) +from .pandas_vb_common import tm class Reindex: @@ -155,19 +152,4 @@ def time_align_series_irregular_string(self): self.x + self.y -class LibFastZip: - def setup(self): - N = 10000 - K = 10 - key1 = tm.makeStringIndex(N).values.repeat(K) - key2 = tm.makeStringIndex(N).values.repeat(K) - col_array = np.vstack([key1, key2, np.random.randn(N * K)]) - col_array2 = col_array.copy() - col_array2[:, :10000] = np.nan - self.col_array_list = list(col_array) - - def time_lib_fast_zip(self): - lib.fast_zip(self.col_array_list) - - from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/timedelta.py b/asv_bench/benchmarks/timedelta.py index 9e221ee030e6d..cb0e4455e1a56 100644 --- a/asv_bench/benchmarks/timedelta.py +++ b/asv_bench/benchmarks/timedelta.py @@ -3,49 +3,13 @@ benchmarks.tslibs.timedelta for benchmarks that rely only on tslibs. """ -import numpy as np - from pandas import ( DataFrame, Series, timedelta_range, - to_timedelta, ) -class ToTimedelta: - def setup(self): - self.ints = np.random.randint(0, 60, size=10000) - self.str_days = [] - self.str_seconds = [] - for i in self.ints: - self.str_days.append(f"{i} days") - self.str_seconds.append(f"00:00:{i:02d}") - - def time_convert_int(self): - to_timedelta(self.ints, unit="s") - - def time_convert_string_days(self): - to_timedelta(self.str_days) - - def time_convert_string_seconds(self): - to_timedelta(self.str_seconds) - - -class ToTimedeltaErrors: - - params = ["coerce", "ignore"] - param_names = ["errors"] - - def setup(self, errors): - ints = np.random.randint(0, 60, size=10000) - self.arr = [f"{i} days" for i in ints] - self.arr[-1] = "apple" - - def time_convert(self, errors): - to_timedelta(self.arr, errors=errors) - - class DatetimeAccessor: def setup_cache(self): N = 100000 diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index 94498e54f0f06..51081db86b76e 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -9,7 +9,6 @@ date_range, period_range, timedelta_range, - to_datetime, ) from pandas.tseries.frequencies import infer_freq @@ -102,7 +101,7 @@ def time_reest_datetimeindex(self, tz): class InferFreq: - + # This depends mostly on code in _libs/, tseries/, and core.algos.unique params = [None, "D", "B"] param_names = ["freq"] @@ -273,158 +272,6 @@ def time_lookup_and_cleanup(self): self.ts.index._cleanup() -class ToDatetimeFromIntsFloats: - def setup(self): - self.ts_sec = Series(range(1521080307, 1521685107), dtype="int64") - self.ts_sec_float = self.ts_sec.astype("float64") - - self.ts_nanosec = 1_000_000 * self.ts_sec - self.ts_nanosec_float = self.ts_nanosec.astype("float64") - - # speed of int64 and float64 paths should be comparable - - def time_nanosec_int64(self): - to_datetime(self.ts_nanosec, unit="ns") - - def time_nanosec_float64(self): - to_datetime(self.ts_nanosec_float, unit="ns") - - def time_sec_int64(self): - to_datetime(self.ts_sec, unit="s") - - def time_sec_float64(self): - to_datetime(self.ts_sec_float, unit="s") - - -class ToDatetimeYYYYMMDD: - def setup(self): - rng = date_range(start="1/1/2000", periods=10000, freq="D") - self.stringsD = Series(rng.strftime("%Y%m%d")) - - def time_format_YYYYMMDD(self): - to_datetime(self.stringsD, format="%Y%m%d") - - -class ToDatetimeCacheSmallCount: - - params = ([True, False], [50, 500, 5000, 100000]) - param_names = ["cache", "count"] - - def setup(self, cache, count): - rng = date_range(start="1/1/1971", periods=count) - self.unique_date_strings = rng.strftime("%Y-%m-%d").tolist() - - def time_unique_date_strings(self, cache, count): - to_datetime(self.unique_date_strings, cache=cache) - - -class ToDatetimeISO8601: - def setup(self): - rng = date_range(start="1/1/2000", periods=20000, freq="H") - self.strings = rng.strftime("%Y-%m-%d %H:%M:%S").tolist() - self.strings_nosep = rng.strftime("%Y%m%d %H:%M:%S").tolist() - self.strings_tz_space = [ - x.strftime("%Y-%m-%d %H:%M:%S") + " -0800" for x in rng - ] - - def time_iso8601(self): - to_datetime(self.strings) - - def time_iso8601_nosep(self): - to_datetime(self.strings_nosep) - - def time_iso8601_format(self): - to_datetime(self.strings, format="%Y-%m-%d %H:%M:%S") - - def time_iso8601_format_no_sep(self): - to_datetime(self.strings_nosep, format="%Y%m%d %H:%M:%S") - - def time_iso8601_tz_spaceformat(self): - to_datetime(self.strings_tz_space) - - -class ToDatetimeNONISO8601: - def setup(self): - N = 10000 - half = N // 2 - ts_string_1 = "March 1, 2018 12:00:00+0400" - ts_string_2 = "March 1, 2018 12:00:00+0500" - self.same_offset = [ts_string_1] * N - self.diff_offset = [ts_string_1] * half + [ts_string_2] * half - - def time_same_offset(self): - to_datetime(self.same_offset) - - def time_different_offset(self): - to_datetime(self.diff_offset) - - -class ToDatetimeFormatQuarters: - def setup(self): - self.s = Series(["2Q2005", "2Q05", "2005Q1", "05Q1"] * 10000) - - def time_infer_quarter(self): - to_datetime(self.s) - - -class ToDatetimeFormat: - def setup(self): - N = 100000 - self.s = Series(["19MAY11", "19MAY11:00:00:00"] * N) - self.s2 = self.s.str.replace(":\\S+$", "") - - self.same_offset = ["10/11/2018 00:00:00.045-07:00"] * N - self.diff_offset = [ - f"10/11/2018 00:00:00.045-0{offset}:00" for offset in range(10) - ] * (N // 10) - - def time_exact(self): - to_datetime(self.s2, format="%d%b%y") - - def time_no_exact(self): - to_datetime(self.s, format="%d%b%y", exact=False) - - def time_same_offset(self): - to_datetime(self.same_offset, format="%m/%d/%Y %H:%M:%S.%f%z") - - def time_different_offset(self): - to_datetime(self.diff_offset, format="%m/%d/%Y %H:%M:%S.%f%z") - - def time_same_offset_to_utc(self): - to_datetime(self.same_offset, format="%m/%d/%Y %H:%M:%S.%f%z", utc=True) - - def time_different_offset_to_utc(self): - to_datetime(self.diff_offset, format="%m/%d/%Y %H:%M:%S.%f%z", utc=True) - - -class ToDatetimeCache: - - params = [True, False] - param_names = ["cache"] - - def setup(self, cache): - N = 10000 - self.unique_numeric_seconds = list(range(N)) - self.dup_numeric_seconds = [1000] * N - self.dup_string_dates = ["2000-02-11"] * N - self.dup_string_with_tz = ["2000-02-11 15:00:00-0800"] * N - - def time_unique_seconds_and_unit(self, cache): - to_datetime(self.unique_numeric_seconds, unit="s", cache=cache) - - def time_dup_seconds_and_unit(self, cache): - to_datetime(self.dup_numeric_seconds, unit="s", cache=cache) - - def time_dup_string_dates(self, cache): - to_datetime(self.dup_string_dates, cache=cache) - - def time_dup_string_dates_and_format(self, cache): - to_datetime(self.dup_string_dates, format="%Y-%m-%d", cache=cache) - - def time_dup_string_tzoffset_dates(self, cache): - to_datetime(self.dup_string_with_tz, cache=cache) - - class DatetimeAccessor: params = [None, "US/Eastern", "UTC", dateutil.tz.tzutc()]
The idea here is to collect benchmarks in such a way that we can say "This PR doesn't change code in files [...] -> We can skip running asvs in files [...]". (putting together a POC script to automate a bit of this) There is a cost to refactoring benchmarks, since we have to re-run the new benchmarks on older commits (and im not sure if that happens automatically or if some human intervention is needed cc @TomAugspurger ?). On the flip side, this is the kind of problem that we can throw hardware at, so I don't worry about it that much. Still, the bar for merging is higher than it would be for non-benchmark refactors. With that in mind, the other refactors I'm looking at: 1) We have benchmarks for e.g. `isin` scattered around, benchmarking `[algos.isin(x, y), pd.array(x).isin(y), Index(s).isin(y), Series(x).isin(y)]`. I'd like to collect these in one place and parametrize them. 2) Similar for Index methods, we have a lot of similar benchmarks for different index subclasses that id like to collect+parametrize.
https://api.github.com/repos/pandas-dev/pandas/pulls/39917
2021-02-19T20:12:35Z
2021-03-01T13:56:08Z
2021-03-01T13:56:08Z
2021-03-01T15:46:49Z
ENH: Implement unary operators for FloatingArray class
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index cbe53edaf12b5..f9aa92cd1a159 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -70,6 +70,7 @@ Other enhancements - :meth:`Series.loc.__getitem__` and :meth:`Series.loc.__setitem__` with :class:`MultiIndex` now raising helpful error message when indexer has too many dimensions (:issue:`35349`) - :meth:`pandas.read_stata` and :class:`StataReader` support reading data from compressed files. - Add support for parsing ``ISO 8601``-like timestamps with negative signs to :meth:`pandas.Timedelta` (:issue:`37172`) +- Add support for unary operators in :class:`FloatingArray` (:issue:`38749`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index b16b4b3ae856a..61d63d2eed6e9 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -315,15 +315,6 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): ) super().__init__(values, mask, copy=copy) - def __neg__(self): - return type(self)(-self._data, self._mask.copy()) - - def __pos__(self): - return self - - def __abs__(self): - return type(self)(np.abs(self._data), self._mask.copy()) - @classmethod def _from_sequence( cls, scalars, *, dtype: Optional[Dtype] = None, copy: bool = False diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index 57017e44a66e9..0dd98c5e3d3f2 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -199,3 +199,12 @@ def reconstruct(x): return tuple(reconstruct(x) for x in result) else: return reconstruct(result) + + def __neg__(self): + return type(self)(-self._data, self._mask.copy()) + + def __pos__(self): + return self + + def __abs__(self): + return type(self)(abs(self._data), self._mask.copy()) diff --git a/pandas/tests/arrays/floating/test_arithmetic.py b/pandas/tests/arrays/floating/test_arithmetic.py index 7ba4da8a5ede9..e674b49a99bd4 100644 --- a/pandas/tests/arrays/floating/test_arithmetic.py +++ b/pandas/tests/arrays/floating/test_arithmetic.py @@ -180,3 +180,24 @@ def test_cross_type_arithmetic(): result = df.A + df.B expected = pd.Series([2, np.nan, np.nan], dtype="Float64") tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "source, neg_target, abs_target", + [ + ([1.1, 2.2, 3.3], [-1.1, -2.2, -3.3], [1.1, 2.2, 3.3]), + ([1.1, 2.2, None], [-1.1, -2.2, None], [1.1, 2.2, None]), + ([-1.1, 0.0, 1.1], [1.1, 0.0, -1.1], [1.1, 0.0, 1.1]), + ], +) +def test_unary_float_operators(float_ea_dtype, source, neg_target, abs_target): + # GH38794 + dtype = float_ea_dtype + arr = pd.array(source, dtype=dtype) + neg_result, pos_result, abs_result = -arr, +arr, abs(arr) + neg_target = pd.array(neg_target, dtype=dtype) + abs_target = pd.array(abs_target, dtype=dtype) + + tm.assert_extension_array_equal(neg_result, neg_target) + tm.assert_extension_array_equal(pos_result, arr) + tm.assert_extension_array_equal(abs_result, abs_target) diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 0c1b10f66a73b..2eb88b669bcb1 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -284,36 +284,22 @@ def test_reduce_to_float(op): @pytest.mark.parametrize( - "source, target", + "source, neg_target, abs_target", [ - ([1, 2, 3], [-1, -2, -3]), - ([1, 2, None], [-1, -2, None]), - ([-1, 0, 1], [1, 0, -1]), + ([1, 2, 3], [-1, -2, -3], [1, 2, 3]), + ([1, 2, None], [-1, -2, None], [1, 2, None]), + ([-1, 0, 1], [1, 0, -1], [1, 0, 1]), ], ) -def test_unary_minus_nullable_int(any_signed_nullable_int_dtype, source, target): +def test_unary_int_operators( + any_signed_nullable_int_dtype, source, neg_target, abs_target +): dtype = any_signed_nullable_int_dtype arr = pd.array(source, dtype=dtype) - result = -arr - expected = pd.array(target, dtype=dtype) - tm.assert_extension_array_equal(result, expected) - - -@pytest.mark.parametrize("source", [[1, 2, 3], [1, 2, None], [-1, 0, 1]]) -def test_unary_plus_nullable_int(any_signed_nullable_int_dtype, source): - dtype = any_signed_nullable_int_dtype - expected = pd.array(source, dtype=dtype) - result = +expected - tm.assert_extension_array_equal(result, expected) + neg_result, pos_result, abs_result = -arr, +arr, abs(arr) + neg_target = pd.array(neg_target, dtype=dtype) + abs_target = pd.array(abs_target, dtype=dtype) - -@pytest.mark.parametrize( - "source, target", - [([1, 2, 3], [1, 2, 3]), ([1, -2, None], [1, 2, None]), ([-1, 0, 1], [1, 0, 1])], -) -def test_abs_nullable_int(any_signed_nullable_int_dtype, source, target): - dtype = any_signed_nullable_int_dtype - s = pd.array(source, dtype=dtype) - result = abs(s) - expected = pd.array(target, dtype=dtype) - tm.assert_extension_array_equal(result, expected) + tm.assert_extension_array_equal(neg_result, neg_target) + tm.assert_extension_array_equal(pos_result, arr) + tm.assert_extension_array_equal(abs_result, abs_target) diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py index 1fc7f824c6daa..adb52fce17f8b 100644 --- a/pandas/tests/arrays/masked/test_arithmetic.py +++ b/pandas/tests/arrays/masked/test_arithmetic.py @@ -165,12 +165,14 @@ def test_error_len_mismatch(data, all_arithmetic_operators): @pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"]) -@pytest.mark.parametrize( - "values, dtype", [([1, 2, 3], "Int64"), ([True, False, True], "boolean")] -) -def test_unary_op_does_not_propagate_mask(op, values, dtype): +def test_unary_op_does_not_propagate_mask(data, op, request): # https://github.com/pandas-dev/pandas/issues/39943 - s = pd.Series(values, dtype=dtype) + data, _ = data + if data.dtype in ["Float32", "Float64"] and op == "__invert__": + request.node.add_marker( + pytest.mark.xfail(reason="invert is not implemented for float ea dtypes") + ) + s = pd.Series(data) result = getattr(s, op)() expected = result.copy(deep=True) s[0] = None diff --git a/pandas/tests/series/test_unary.py b/pandas/tests/series/test_unary.py index 40d5e56203c6c..67bb89b42a56d 100644 --- a/pandas/tests/series/test_unary.py +++ b/pandas/tests/series/test_unary.py @@ -18,40 +18,35 @@ def test_invert(self): tm.assert_series_equal(-(ser < 0), ~(ser < 0)) @pytest.mark.parametrize( - "source, target", + "source, neg_target, abs_target", [ - ([1, 2, 3], [-1, -2, -3]), - ([1, 2, None], [-1, -2, None]), - ([-1, 0, 1], [1, 0, -1]), + ([1, 2, 3], [-1, -2, -3], [1, 2, 3]), + ([1, 2, None], [-1, -2, None], [1, 2, None]), ], ) - def test_unary_minus_nullable_int( - self, any_signed_nullable_int_dtype, source, target + def test_all_numeric_unary_operators( + self, any_nullable_numeric_dtype, source, neg_target, abs_target ): - dtype = any_signed_nullable_int_dtype + # GH38794 + dtype = any_nullable_numeric_dtype ser = Series(source, dtype=dtype) - result = -ser - expected = Series(target, dtype=dtype) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("source", [[1, 2, 3], [1, 2, None], [-1, 0, 1]]) - def test_unary_plus_nullable_int(self, any_signed_nullable_int_dtype, source): - dtype = any_signed_nullable_int_dtype - expected = Series(source, dtype=dtype) - result = +expected - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize( - "source, target", - [ - ([1, 2, 3], [1, 2, 3]), - ([1, -2, None], [1, 2, None]), - ([-1, 0, 1], [1, 0, 1]), - ], - ) - def test_abs_nullable_int(self, any_signed_nullable_int_dtype, source, target): - dtype = any_signed_nullable_int_dtype - ser = Series(source, dtype=dtype) - result = abs(ser) - expected = Series(target, dtype=dtype) - tm.assert_series_equal(result, expected) + neg_result, pos_result, abs_result = -ser, +ser, abs(ser) + if dtype.startswith("U"): + neg_target = -Series(source, dtype=dtype) + else: + neg_target = Series(neg_target, dtype=dtype) + + abs_target = Series(abs_target, dtype=dtype) + + tm.assert_series_equal(neg_result, neg_target) + tm.assert_series_equal(pos_result, ser) + tm.assert_series_equal(abs_result, abs_target) + + @pytest.mark.parametrize("op", ["__neg__", "__abs__"]) + def test_unary_float_op_mask(self, float_ea_dtype, op): + dtype = float_ea_dtype + ser = Series([1.1, 2.2, 3.3], dtype=dtype) + result = getattr(ser, op)() + target = result.copy(deep=True) + ser[0] = None + tm.assert_series_equal(result, target)
- [ ] closes #38749 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39916
2021-02-19T20:02:42Z
2021-02-28T08:38:16Z
2021-02-28T08:38:16Z
2021-02-28T15:59:21Z
[ArrowStringArray] API: StringDtype parameterized by storage (python or pyarrow)
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index aecc609df574e..e48a2060a3b34 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -23,12 +23,12 @@ class Factorize: "int", "uint", "float", - "string", + "object", "datetime64[ns]", "datetime64[ns, tz]", "Int64", "boolean", - "string_arrow", + "string[pyarrow]", ], ] param_names = ["unique", "sort", "dtype"] @@ -36,28 +36,25 @@ class Factorize: def setup(self, unique, sort, dtype): N = 10 ** 5 string_index = tm.makeStringIndex(N) - try: - from pandas.core.arrays.string_arrow import ArrowStringDtype - - string_arrow = pd.array(string_index, dtype=ArrowStringDtype()) - except ImportError: - string_arrow = None - - if dtype == "string_arrow" and not string_arrow: - raise NotImplementedError + string_arrow = None + if dtype == "string[pyarrow]": + try: + string_arrow = pd.array(string_index, dtype="string[pyarrow]") + except ImportError: + raise NotImplementedError data = { "int": pd.Int64Index(np.arange(N)), "uint": pd.UInt64Index(np.arange(N)), "float": pd.Float64Index(np.random.randn(N)), - "string": string_index, + "object": string_index, "datetime64[ns]": pd.date_range("2011-01-01", freq="H", periods=N), "datetime64[ns, tz]": pd.date_range( "2011-01-01", freq="H", periods=N, tz="Asia/Tokyo" ), "Int64": pd.array(np.arange(N), dtype="Int64"), "boolean": pd.array(np.random.randint(0, 2, N), dtype="boolean"), - "string_arrow": string_arrow, + "string[pyarrow]": string_arrow, }[dtype] if not unique: data = data.repeat(5) diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py index 44245295beafc..4b58981694014 100644 --- a/asv_bench/benchmarks/algos/isin.py +++ b/asv_bench/benchmarks/algos/isin.py @@ -25,8 +25,8 @@ class IsIn: "category[object]", "category[int]", "str", - "string", - "arrow_string", + "string[python]", + "string[pyarrow]", ] param_names = ["dtype"] @@ -62,9 +62,7 @@ def setup(self, dtype): self.values = np.random.choice(arr, sample_size) self.series = Series(arr).astype("category") - elif dtype in ["str", "string", "arrow_string"]: - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - + elif dtype in ["str", "string[python]", "string[pyarrow]"]: try: self.series = Series(tm.makeStringIndex(N), dtype=dtype) except ImportError: diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py index 2e109e59c1c6d..32fbf4e6c7de3 100644 --- a/asv_bench/benchmarks/strings.py +++ b/asv_bench/benchmarks/strings.py @@ -12,12 +12,10 @@ class Dtypes: - params = ["str", "string", "arrow_string"] + params = ["str", "string[python]", "string[pyarrow]"] param_names = ["dtype"] def setup(self, dtype): - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - try: self.s = Series(tm.makeStringIndex(10 ** 5), dtype=dtype) except ImportError: diff --git a/doc/source/reference/arrays.rst b/doc/source/reference/arrays.rst index 43e2509469488..c6fda85b0486d 100644 --- a/doc/source/reference/arrays.rst +++ b/doc/source/reference/arrays.rst @@ -480,6 +480,7 @@ we recommend using :class:`StringDtype` (with the alias ``"string"``). :template: autosummary/class_without_autosummary.rst arrays.StringArray + arrays.ArrowStringArray .. autosummary:: :toctree: api/ diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index ce613fd78c1e1..c2f25b389c9eb 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -171,6 +171,58 @@ a copy will no longer be made (:issue:`32960`) The default behavior when not passing ``copy`` will remain unchanged, i.e. a copy will be made. +.. _whatsnew_130.arrow_string: + +PyArrow backed string data type +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +We've enhanced the :class:`StringDtype`, an extension type dedicated to string data. +(:issue:`39908`) + +It is now possible to specify a ``storage`` keyword option to :class:`StringDtype`. Use +pandas options or specify the dtype using ``dtype='string[pyarrow]'`` to allow the +StringArray to be backed by a PyArrow array instead of a NumPy array of Python objects. + +The PyArrow backed StringArray requires pyarrow 1.0.0 or greater to be installed. + +.. warning:: + + ``string[pyarrow]`` is currently considered experimental. The implementation + and parts of the API may change without warning. + +.. ipython:: python + + pd.Series(['abc', None, 'def'], dtype=pd.StringDtype(storage="pyarrow")) + +You can use the alias ``"string[pyarrow]"`` as well. + +.. ipython:: python + + s = pd.Series(['abc', None, 'def'], dtype="string[pyarrow]") + s + +You can also create a PyArrow backed string array using pandas options. + +.. ipython:: python + + with pd.option_context("string_storage", "pyarrow"): + s = pd.Series(['abc', None, 'def'], dtype="string") + s + +The usual string accessor methods work. Where appropriate, the return type of the Series +or columns of a DataFrame will also have string dtype. + +.. ipython:: python + + s.str.upper() + s.str.split('b', expand=True).dtypes + +String accessor methods returning integers will return a value with :class:`Int64Dtype` + +.. ipython:: python + + s.str.count("a") + Centered Datetime-Like Rolling Windows ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 96d010b487a79..1942e07d1b562 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -48,6 +48,7 @@ TimedeltaArray, ) from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin +from pandas.core.arrays.string_ import StringDtype from pandas.io.formats.printing import pprint_thing @@ -638,12 +639,20 @@ def raise_assert_detail(obj, message, left, right, diff=None, index_values=None) if isinstance(left, np.ndarray): left = pprint_thing(left) - elif is_categorical_dtype(left) or isinstance(left, PandasDtype): + elif ( + is_categorical_dtype(left) + or isinstance(left, PandasDtype) + or isinstance(left, StringDtype) + ): left = repr(left) if isinstance(right, np.ndarray): right = pprint_thing(right) - elif is_categorical_dtype(right) or isinstance(right, PandasDtype): + elif ( + is_categorical_dtype(right) + or isinstance(right, PandasDtype) + or isinstance(right, StringDtype) + ): right = repr(right) msg += f""" diff --git a/pandas/arrays/__init__.py b/pandas/arrays/__init__.py index 0fa070b6e4fc4..89d362eb77e68 100644 --- a/pandas/arrays/__init__.py +++ b/pandas/arrays/__init__.py @@ -4,6 +4,7 @@ See :ref:`extending.extension-types` for more. """ from pandas.core.arrays import ( + ArrowStringArray, BooleanArray, Categorical, DatetimeArray, @@ -18,6 +19,7 @@ ) __all__ = [ + "ArrowStringArray", "BooleanArray", "Categorical", "DatetimeArray", diff --git a/pandas/conftest.py b/pandas/conftest.py index 329023ed7ba6a..e106f7f425fa0 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1120,9 +1120,9 @@ def string_dtype(request): @pytest.fixture( params=[ - "string", + "string[python]", pytest.param( - "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0") + "string[pyarrow]", marks=td.skip_if_no("pyarrow", min_version="1.0.0") ), ] ) @@ -1130,14 +1130,32 @@ def nullable_string_dtype(request): """ Parametrized fixture for string dtypes. - * 'string' - * 'arrow_string' + * 'string[python]' + * 'string[pyarrow]' + """ + return request.param + + +@pytest.fixture( + params=[ + "python", + pytest.param("pyarrow", marks=td.skip_if_no("pyarrow", min_version="1.0.0")), + ] +) +def string_storage(request): """ - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 + Parametrized fixture for pd.options.mode.string_storage. + * 'python' + * 'pyarrow' + """ return request.param +# Alias so we can test with cartesian product of string_storage +string_storage2 = string_storage + + @pytest.fixture(params=tm.BYTES_DTYPES) def bytes_dtype(request): """ @@ -1163,9 +1181,9 @@ def object_dtype(request): @pytest.fixture( params=[ "object", - "string", + "string[python]", pytest.param( - "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0") + "string[pyarrow]", marks=td.skip_if_no("pyarrow", min_version="1.0.0") ), ] ) @@ -1173,11 +1191,9 @@ def any_string_dtype(request): """ Parametrized fixture for string dtypes. * 'object' - * 'string' - * 'arrow_string' + * 'string[python]' + * 'string[pyarrow]' """ - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - return request.param diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index 22f15ca9650db..e301e82a0ee75 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -17,12 +17,14 @@ ) from pandas.core.arrays.sparse import SparseArray from pandas.core.arrays.string_ import StringArray +from pandas.core.arrays.string_arrow import ArrowStringArray from pandas.core.arrays.timedeltas import TimedeltaArray __all__ = [ "ExtensionArray", "ExtensionOpsMixin", "ExtensionScalarOpsMixin", + "ArrowStringArray", "BaseMaskedArray", "BooleanArray", "Categorical", diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index ab1dadf4d2dfa..8d150c8f6ad3d 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -1,9 +1,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import ( + TYPE_CHECKING, + Any, +) import numpy as np +from pandas._config import get_option + from pandas._libs import ( lib, missing as libmissing, @@ -14,6 +19,7 @@ Scalar, type_t, ) +from pandas.compat import pa_version_under1p0 from pandas.compat.numpy import function as nv from pandas.core.dtypes.base import ( @@ -37,6 +43,7 @@ IntegerArray, PandasArray, ) +from pandas.core.arrays.base import ExtensionArray from pandas.core.arrays.floating import FloatingDtype from pandas.core.arrays.integer import _IntegerDtype from pandas.core.construction import extract_array @@ -62,6 +69,11 @@ class StringDtype(ExtensionDtype): In particular, StringDtype.na_value may change to no longer be ``numpy.nan``. + Parameters + ---------- + storage : {"python", "pyarrow"}, optional + If not given, the value of ``pd.options.mode.string_storage``. + Attributes ---------- None @@ -73,20 +85,93 @@ class StringDtype(ExtensionDtype): Examples -------- >>> pd.StringDtype() - StringDtype + string[python] + + >>> pd.StringDtype(storage="pyarrow") + string[pyarrow] """ name = "string" #: StringDtype.na_value uses pandas.NA na_value = libmissing.NA + _metadata = ("storage",) + + def __init__(self, storage=None): + if storage is None: + storage = get_option("mode.string_storage") + if storage not in {"python", "pyarrow"}: + raise ValueError( + f"Storage must be 'python' or 'pyarrow'. Got {storage} instead." + ) + if storage == "pyarrow" and pa_version_under1p0: + raise ImportError( + "pyarrow>=1.0.0 is required for PyArrow backed StringArray." + ) + + self.storage = storage @property def type(self) -> type[str]: return str @classmethod - def construct_array_type(cls) -> type_t[StringArray]: + def construct_from_string(cls, string): + """ + Construct a StringDtype from a string. + + Parameters + ---------- + string : str + The type of the name. The storage type will be taking from `string`. + Valid options and their storage types are + + ========================== ============================================== + string result storage + ========================== ============================================== + ``'string'`` pd.options.mode.string_storage, default python + ``'string[python]'`` python + ``'string[pyarrow]'`` pyarrow + ========================== ============================================== + + Returns + ------- + StringDtype + + Raise + ----- + TypeError + If the string is not a valid option. + + """ + if not isinstance(string, str): + raise TypeError( + f"'construct_from_string' expects a string, got {type(string)}" + ) + if string == "string": + return cls() + elif string == "string[python]": + return cls(storage="python") + elif string == "string[pyarrow]": + return cls(storage="pyarrow") + else: + raise TypeError(f"Cannot construct a '{cls.__name__}' from '{string}'") + + def __eq__(self, other: Any) -> bool: + if isinstance(other, str) and other == "string": + return True + return super().__eq__(other) + + def __hash__(self) -> int: + # custom __eq__ so have to override __hash__ + return super().__hash__() + + # https://github.com/pandas-dev/pandas/issues/36126 + # error: Signature of "construct_array_type" incompatible with supertype + # "ExtensionDtype" + def construct_array_type( # type: ignore[override] + self, + ) -> type_t[BaseStringArray]: """ Return the array type associated with this dtype. @@ -94,30 +179,44 @@ def construct_array_type(cls) -> type_t[StringArray]: ------- type """ - return StringArray + from pandas.core.arrays.string_arrow import ArrowStringArray + + if self.storage == "python": + return StringArray + else: + return ArrowStringArray + + def __repr__(self): + return f"string[{self.storage}]" - def __repr__(self) -> str: - return "StringDtype" + def __str__(self): + return self.name def __from_arrow__( self, array: pyarrow.Array | pyarrow.ChunkedArray - ) -> StringArray: + ) -> BaseStringArray: """ Construct StringArray from pyarrow Array/ChunkedArray. """ - import pyarrow + if self.storage == "pyarrow": + from pandas.core.arrays.string_arrow import ArrowStringArray - if isinstance(array, pyarrow.Array): - chunks = [array] + return ArrowStringArray(array) else: - # pyarrow.ChunkedArray - chunks = array.chunks - results = [] - for arr in chunks: - # using _from_sequence to ensure None is converted to NA - str_arr = StringArray._from_sequence(np.array(arr)) - results.append(str_arr) + import pyarrow + + if isinstance(array, pyarrow.Array): + chunks = [array] + else: + # pyarrow.ChunkedArray + chunks = array.chunks + + results = [] + for arr in chunks: + # using _from_sequence to ensure None is converted to NA + str_arr = StringArray._from_sequence(np.array(arr)) + results.append(str_arr) if results: return StringArray._concat_same_type(results) @@ -125,7 +224,11 @@ def __from_arrow__( return StringArray(np.array([], dtype="object")) -class StringArray(PandasArray): +class BaseStringArray(ExtensionArray): + pass + + +class StringArray(BaseStringArray, PandasArray): """ Extension array for string data. @@ -210,7 +313,7 @@ def __init__(self, values, copy=False): super().__init__(values, copy=copy) # error: Incompatible types in assignment (expression has type "StringDtype", # variable has type "PandasDtype") - NDArrayBacked.__init__(self, self._ndarray, StringDtype()) + NDArrayBacked.__init__(self, self._ndarray, StringDtype(storage="python")) if not isinstance(values, type(self)): self._validate() @@ -226,8 +329,9 @@ def _validate(self): @classmethod def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy=False): - if dtype: - assert dtype == "string" + if dtype and not (isinstance(dtype, str) and dtype == "string"): + dtype = pandas_dtype(dtype) + assert isinstance(dtype, StringDtype) and dtype.storage == "python" from pandas.core.arrays.masked import BaseMaskedArray @@ -247,7 +351,7 @@ def _from_sequence(cls, scalars, *, dtype: Dtype | None = None, copy=False): # Manually creating new array avoids the validation step in the __init__, so is # faster. Refactor need for validation? new_string_array = cls.__new__(cls) - NDArrayBacked.__init__(new_string_array, result, StringDtype()) + NDArrayBacked.__init__(new_string_array, result, StringDtype(storage="python")) return new_string_array @@ -416,7 +520,7 @@ def _str_map( from pandas.arrays import BooleanArray if dtype is None: - dtype = StringDtype() + dtype = StringDtype(storage="python") if na_value is None: na_value = self.dtype.na_value diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 3cf471e381da9..ab8599f0f05ba 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -11,16 +11,12 @@ import numpy as np -from pandas._libs import ( - lib, - missing as libmissing, -) +from pandas._libs import lib from pandas._typing import ( Dtype, NpDtype, PositionalIndexer, Scalar, - type_t, ) from pandas.compat import ( pa_version_under1p0, @@ -43,7 +39,6 @@ is_string_dtype, pandas_dtype, ) -from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.missing import isna from pandas.core import missing @@ -52,7 +47,10 @@ from pandas.core.arrays.boolean import BooleanDtype from pandas.core.arrays.integer import Int64Dtype from pandas.core.arrays.numeric import NumericDtype -from pandas.core.arrays.string_ import StringDtype +from pandas.core.arrays.string_ import ( + BaseStringArray, + StringDtype, +) from pandas.core.indexers import ( check_array_indexer, validate_indices, @@ -86,99 +84,12 @@ def _chk_pyarrow_available() -> None: raise ImportError(msg) -@register_extension_dtype -class ArrowStringDtype(StringDtype): - """ - Extension dtype for string data in a ``pyarrow.ChunkedArray``. - - .. versionadded:: 1.2.0 - - .. warning:: - - ArrowStringDtype is considered experimental. The implementation and - parts of the API may change without warning. - - Attributes - ---------- - None - - Methods - ------- - None - - Examples - -------- - >>> from pandas.core.arrays.string_arrow import ArrowStringDtype - >>> ArrowStringDtype() - ArrowStringDtype - """ - - name = "arrow_string" - - #: StringDtype.na_value uses pandas.NA - na_value = libmissing.NA - - def __init__(self): - _chk_pyarrow_available() - - @property - def type(self) -> type[str]: - return str - - @classmethod - def construct_array_type(cls) -> type_t[ArrowStringArray]: # type: ignore[override] - """ - Return the array type associated with this dtype. - - Returns - ------- - type - """ - return ArrowStringArray - - def __hash__(self) -> int: - return hash("ArrowStringDtype") - - def __repr__(self) -> str: - return "ArrowStringDtype" - - def __from_arrow__( # type: ignore[override] - self, array: pa.Array | pa.ChunkedArray - ) -> ArrowStringArray: - """ - Construct StringArray from pyarrow Array/ChunkedArray. - """ - return ArrowStringArray(array) - - def __eq__(self, other) -> bool: - """Check whether 'other' is equal to self. - - By default, 'other' is considered equal if - * it's a string matching 'self.name'. - * it's an instance of this type. - - Parameters - ---------- - other : Any - - Returns - ------- - bool - """ - if isinstance(other, ArrowStringDtype): - return True - elif isinstance(other, str) and other == "arrow_string": - return True - else: - return False - - # TODO: Inherit directly from BaseStringArrayMethods. Currently we inherit from # ObjectStringArrayMixin because we want to have the object-dtype based methods as # fallback for the ones that pyarrow doesn't yet support -class ArrowStringArray(OpsMixin, ExtensionArray, ObjectStringArrayMixin): +class ArrowStringArray(OpsMixin, BaseStringArray, ObjectStringArrayMixin): """ Extension array for string data in a ``pyarrow.ChunkedArray``. @@ -216,14 +127,14 @@ class ArrowStringArray(OpsMixin, ExtensionArray, ObjectStringArrayMixin): Examples -------- - >>> pd.array(['This is', 'some text', None, 'data.'], dtype="arrow_string") + >>> pd.array(['This is', 'some text', None, 'data.'], dtype="string[pyarrow]") <ArrowStringArray> ['This is', 'some text', <NA>, 'data.'] - Length: 4, dtype: arrow_string + Length: 4, dtype: string """ def __init__(self, values): - self._dtype = ArrowStringDtype() + self._dtype = StringDtype(storage="pyarrow") if isinstance(values, pa.Array): self._data = pa.chunked_array([values]) elif isinstance(values, pa.ChunkedArray): @@ -242,6 +153,10 @@ def _from_sequence(cls, scalars, dtype: Dtype | None = None, copy: bool = False) _chk_pyarrow_available() + if dtype and not (isinstance(dtype, str) and dtype == "string"): + dtype = pandas_dtype(dtype) + assert isinstance(dtype, StringDtype) and dtype.storage == "pyarrow" + if isinstance(scalars, BaseMaskedArray): # avoid costly conversion to object dtype in ensure_string_array and # numerical issues with Float32Dtype @@ -261,9 +176,9 @@ def _from_sequence_of_strings( return cls._from_sequence(strings, dtype=dtype, copy=copy) @property - def dtype(self) -> ArrowStringDtype: + def dtype(self) -> StringDtype: """ - An instance of 'ArrowStringDtype'. + An instance of 'string[pyarrow]'. """ return self._dtype @@ -761,7 +676,8 @@ def astype(self, dtype, copy=True): # ------------------------------------------------------------------------ # String methods interface - _str_na_value = ArrowStringDtype.na_value + # error: Cannot determine type of 'na_value' + _str_na_value = StringDtype.na_value # type: ignore[has-type] def _str_map( self, f, na_value=None, dtype: Dtype | None = None, convert: bool = True diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 0db0c5a57207d..27b898782fbef 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -526,6 +526,19 @@ def use_inf_as_na_cb(key): ) +string_storage_doc = """ +: string + The default storage for StringDtype. +""" + +with cf.config_prefix("mode"): + cf.register_option( + "string_storage", + "python", + string_storage_doc, + validator=is_one_of_factory(["python", "pyarrow"]), + ) + # Set up the io.excel specific reader configuration. reader_engine_doc = """ : string diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 330902b402324..379495eaa48d5 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -109,18 +109,22 @@ def array( Currently, pandas will infer an extension dtype for sequences of - ============================== ===================================== + ============================== ======================================= Scalar Type Array Type - ============================== ===================================== + ============================== ======================================= :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray` :class:`pandas.Period` :class:`pandas.arrays.PeriodArray` :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray` :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray` :class:`int` :class:`pandas.arrays.IntegerArray` :class:`float` :class:`pandas.arrays.FloatingArray` - :class:`str` :class:`pandas.arrays.StringArray` + :class:`str` :class:`pandas.arrays.StringArray` or + :class:`pandas.arrays.ArrowStringArray` :class:`bool` :class:`pandas.arrays.BooleanArray` - ============================== ===================================== + ============================== ======================================= + + The ExtensionArray created when the scalar type is :class:`str` is determined by + ``pd.options.mode.string_storage`` if the dtype is not explicitly given. For all other cases, NumPy's usual inference rules will be used. @@ -236,6 +240,14 @@ def array( ['a', <NA>, 'c'] Length: 3, dtype: string + >>> with pd.option_context("string_storage", "pyarrow"): + ... arr = pd.array(["a", None, "c"]) + ... + >>> arr + <ArrowStringArray> + ['a', <NA>, 'c'] + Length: 3, dtype: string + >>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] @@ -289,9 +301,9 @@ def array( IntervalArray, PandasArray, PeriodArray, - StringArray, TimedeltaArray, ) + from pandas.core.arrays.string_ import StringDtype if lib.is_scalar(data): msg = f"Cannot pass scalar '{data}' to 'pandas.array'." @@ -332,7 +344,8 @@ def array( return TimedeltaArray._from_sequence(data, copy=copy) elif inferred_dtype == "string": - return StringArray._from_sequence(data, copy=copy) + # StringArray/ArrowStringArray depending on pd.options.mode.string_storage + return StringDtype().construct_array_type()._from_sequence(data, copy=copy) elif inferred_dtype == "integer": return IntegerArray._from_sequence(data, copy=copy) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 4abb5d98202f6..f432cd27d1269 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -419,18 +419,14 @@ def maybe_cast_to_extension_array( ------- ExtensionArray or obj """ - from pandas.core.arrays.string_ import StringArray - from pandas.core.arrays.string_arrow import ArrowStringArray + from pandas.core.arrays.string_ import BaseStringArray assert isinstance(cls, type), f"must pass a type: {cls}" assertion_msg = f"must pass a subclass of ExtensionArray: {cls}" assert issubclass(cls, ABCExtensionArray), assertion_msg # Everything can be converted to StringArrays, but we may not want to convert - if ( - issubclass(cls, (StringArray, ArrowStringArray)) - and lib.infer_dtype(obj) != "string" - ): + if issubclass(cls, BaseStringArray) and lib.infer_dtype(obj) != "string": return obj try: diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 7643019ff8c55..aa867ae4dd401 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -3080,7 +3080,7 @@ def _result_dtype(arr): from pandas.core.arrays.string_ import StringDtype if isinstance(arr.dtype, StringDtype): - return arr.dtype.name + return arr.dtype else: return object diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 7ce4abe904f3b..02bdb7f181583 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -173,8 +173,7 @@ def scalar_rep(x): return self._str_map(scalar_rep, dtype=str) else: - from pandas.core.arrays.string_ import StringArray - from pandas.core.arrays.string_arrow import ArrowStringArray + from pandas.core.arrays.string_ import BaseStringArray def rep(x, r): if x is libmissing.NA: @@ -186,7 +185,7 @@ def rep(x, r): repeats = np.asarray(repeats, dtype=object) result = libops.vec_binop(np.asarray(self), repeats, rep) - if isinstance(self, (StringArray, ArrowStringArray)): + if isinstance(self, BaseStringArray): # Not going through map, so we have to do this here. result = type(self)._from_sequence(result) return result diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index c9533e239abe0..5731f02430a9d 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -14,37 +14,17 @@ import pandas as pd import pandas._testing as tm -from pandas.core.arrays.string_arrow import ( - ArrowStringArray, - ArrowStringDtype, -) - -skip_if_no_pyarrow = td.skip_if_no("pyarrow", min_version="1.0.0") - - -@pytest.fixture( - params=["string", pytest.param("arrow_string", marks=skip_if_no_pyarrow)] -) -def dtype(request): - return request.param +from pandas.core.arrays.string_arrow import ArrowStringArray @pytest.fixture -def dtype_object(dtype): - if dtype == "string": - return pd.StringDtype - else: - return ArrowStringDtype +def dtype(string_storage): + return pd.StringDtype(storage=string_storage) -@pytest.fixture( - params=[ - pd.arrays.StringArray, - pytest.param(ArrowStringArray, marks=skip_if_no_pyarrow), - ] -) -def cls(request): - return request.param +@pytest.fixture +def cls(dtype): + return dtype.construct_array_type() def test_repr(dtype): @@ -52,11 +32,11 @@ def test_repr(dtype): expected = " A\n0 a\n1 <NA>\n2 b" assert repr(df) == expected - expected = f"0 a\n1 <NA>\n2 b\nName: A, dtype: {dtype}" + expected = "0 a\n1 <NA>\n2 b\nName: A, dtype: string" assert repr(df.A) == expected - arr_name = "ArrowStringArray" if dtype == "arrow_string" else "StringArray" - expected = f"<{arr_name}>\n['a', <NA>, 'b']\nLength: 3, dtype: {dtype}" + arr_name = "ArrowStringArray" if dtype.storage == "pyarrow" else "StringArray" + expected = f"<{arr_name}>\n['a', <NA>, 'b']\nLength: 3, dtype: string" assert repr(df.A.array) == expected @@ -94,7 +74,7 @@ def test_setitem_with_scalar_string(dtype): def test_astype_roundtrip(dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = "ValueError: Could not convert object to NumPy datetime" mark = pytest.mark.xfail(reason=reason, raises=ValueError) request.node.add_marker(mark) @@ -115,7 +95,7 @@ def test_astype_roundtrip(dtype, request): def test_add(dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = ( "unsupported operand type(s) for +: 'ArrowStringArray' and " "'ArrowStringArray'" @@ -143,7 +123,7 @@ def test_add(dtype, request): def test_add_2d(dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = "Failed: DID NOT RAISE <class 'ValueError'>" mark = pytest.mark.xfail(raises=None, reason=reason) request.node.add_marker(mark) @@ -159,7 +139,7 @@ def test_add_2d(dtype, request): def test_add_sequence(dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = "unsupported operand type(s) for +: 'ArrowStringArray' and 'list'" mark = pytest.mark.xfail(raises=TypeError, reason=reason) request.node.add_marker(mark) @@ -177,7 +157,7 @@ def test_add_sequence(dtype, request): def test_mul(dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = "unsupported operand type(s) for *: 'ArrowStringArray' and 'int'" mark = pytest.mark.xfail(raises=TypeError, reason=reason) request.node.add_marker(mark) @@ -258,7 +238,7 @@ def test_comparison_methods_scalar_not_string(all_compare_operators, dtype, requ def test_comparison_methods_array(all_compare_operators, dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": mark = pytest.mark.xfail( raises=AssertionError, reason="left is not an ExtensionArray" ) @@ -366,7 +346,7 @@ def test_reduce(skipna, dtype): @pytest.mark.parametrize("method", ["min", "max"]) @pytest.mark.parametrize("skipna", [True, False]) def test_min_max(method, skipna, dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = "'ArrowStringArray' object has no attribute 'max'" mark = pytest.mark.xfail(raises=AttributeError, reason=reason) request.node.add_marker(mark) @@ -383,7 +363,7 @@ def test_min_max(method, skipna, dtype, request): @pytest.mark.parametrize("method", ["min", "max"]) @pytest.mark.parametrize("box", [pd.Series, pd.array]) def test_min_max_numpy(method, box, dtype, request): - if dtype == "arrow_string": + if dtype.storage == "pyarrow": if box is pd.array: raises = TypeError reason = "'<=' not supported between instances of 'str' and 'NoneType'" @@ -413,7 +393,7 @@ def test_reduce_missing(skipna, dtype): def test_fillna_args(dtype, request): # GH 37987 - if dtype == "arrow_string": + if dtype.storage == "pyarrow": reason = ( "Regex pattern \"Cannot set non-string value '1' into " "a StringArray.\" does not match 'Scalar must be NA or str'" @@ -444,14 +424,14 @@ def test_arrow_array(dtype): data = pd.array(["a", "b", "c"], dtype=dtype) arr = pa.array(data) expected = pa.array(list(data), type=pa.string(), from_pandas=True) - if dtype == "arrow_string": + if dtype.storage == "pyarrow": expected = pa.chunked_array(expected) assert arr.equals(expected) @td.skip_if_no("pyarrow") -def test_arrow_roundtrip(dtype, dtype_object): +def test_arrow_roundtrip(dtype, string_storage2): # roundtrip possible from arrow 1.0.0 import pyarrow as pa @@ -459,15 +439,17 @@ def test_arrow_roundtrip(dtype, dtype_object): df = pd.DataFrame({"a": data}) table = pa.table(df) assert table.field("a").type == "string" - result = table.to_pandas() - assert isinstance(result["a"].dtype, dtype_object) - tm.assert_frame_equal(result, df) + with pd.option_context("string_storage", string_storage2): + result = table.to_pandas() + assert isinstance(result["a"].dtype, pd.StringDtype) + expected = df.astype(f"string[{string_storage2}]") + tm.assert_frame_equal(result, expected) # ensure the missing value is represented by NA and not np.nan or None assert result.loc[2, "a"] is pd.NA @td.skip_if_no("pyarrow") -def test_arrow_load_from_zero_chunks(dtype, dtype_object): +def test_arrow_load_from_zero_chunks(dtype, string_storage2): # GH-41040 import pyarrow as pa @@ -477,9 +459,11 @@ def test_arrow_load_from_zero_chunks(dtype, dtype_object): assert table.field("a").type == "string" # Instantiate the same table with no chunks at all table = pa.table([pa.chunked_array([], type=pa.string())], schema=table.schema) - result = table.to_pandas() - assert isinstance(result["a"].dtype, dtype_object) - tm.assert_frame_equal(result, df) + with pd.option_context("string_storage", string_storage2): + result = table.to_pandas() + assert isinstance(result["a"].dtype, pd.StringDtype) + expected = df.astype(f"string[{string_storage2}]") + tm.assert_frame_equal(result, expected) def test_value_counts_na(dtype): @@ -523,10 +507,10 @@ def test_use_inf_as_na(values, expected, dtype): tm.assert_frame_equal(result, expected) -def test_memory_usage(dtype, request): +def test_memory_usage(dtype): # GH 33963 - if dtype == "arrow_string": + if dtype.storage == "pyarrow": pytest.skip("not applicable") series = pd.Series(["a", "b", "c"], dtype=dtype) diff --git a/pandas/tests/arrays/string_/test_string_arrow.py b/pandas/tests/arrays/string_/test_string_arrow.py index 3db8333798e36..c3f951adf7f89 100644 --- a/pandas/tests/arrays/string_/test_string_arrow.py +++ b/pandas/tests/arrays/string_/test_string_arrow.py @@ -5,16 +5,47 @@ from pandas.compat import pa_version_under1p0 -from pandas.core.arrays.string_arrow import ( - ArrowStringArray, - ArrowStringDtype, +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays.string_ import ( + StringArray, + StringDtype, ) +from pandas.core.arrays.string_arrow import ArrowStringArray - -@pytest.mark.skipif( +skip_if_no_pyarrow = pytest.mark.skipif( pa_version_under1p0, reason="pyarrow>=1.0.0 is required for PyArrow backed StringArray", ) + + +@skip_if_no_pyarrow +def test_eq_all_na(): + a = pd.array([pd.NA, pd.NA], dtype=StringDtype("pyarrow")) + result = a == a + expected = pd.array([pd.NA, pd.NA], dtype="boolean") + tm.assert_extension_array_equal(result, expected) + + +def test_config(string_storage): + with pd.option_context("string_storage", string_storage): + assert StringDtype().storage == string_storage + result = pd.array(["a", "b"]) + assert result.dtype.storage == string_storage + + expected = ( + StringDtype(string_storage).construct_array_type()._from_sequence(["a", "b"]) + ) + tm.assert_equal(result, expected) + + +def test_config_bad_storage_raises(): + msg = re.escape("Value must be one of python|pyarrow") + with pytest.raises(ValueError, match=msg): + pd.options.mode.string_storage = "foo" + + +@skip_if_no_pyarrow @pytest.mark.parametrize("chunked", [True, False]) @pytest.mark.parametrize("array", ["numpy", "pyarrow"]) def test_constructor_not_string_type_raises(array, chunked): @@ -37,6 +68,55 @@ def test_constructor_not_string_type_raises(array, chunked): ArrowStringArray(arr) +@skip_if_no_pyarrow +def test_from_sequence_wrong_dtype_raises(): + with pd.option_context("string_storage", "python"): + ArrowStringArray._from_sequence(["a", None, "c"], dtype="string") + + with pd.option_context("string_storage", "pyarrow"): + ArrowStringArray._from_sequence(["a", None, "c"], dtype="string") + + with pytest.raises(AssertionError, match=None): + ArrowStringArray._from_sequence(["a", None, "c"], dtype="string[python]") + + ArrowStringArray._from_sequence(["a", None, "c"], dtype="string[pyarrow]") + + with pytest.raises(AssertionError, match=None): + with pd.option_context("string_storage", "python"): + ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) + + with pd.option_context("string_storage", "pyarrow"): + ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) + + with pytest.raises(AssertionError, match=None): + ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype("python")) + + ArrowStringArray._from_sequence(["a", None, "c"], dtype=StringDtype("pyarrow")) + + with pd.option_context("string_storage", "python"): + StringArray._from_sequence(["a", None, "c"], dtype="string") + + with pd.option_context("string_storage", "pyarrow"): + StringArray._from_sequence(["a", None, "c"], dtype="string") + + StringArray._from_sequence(["a", None, "c"], dtype="string[python]") + + with pytest.raises(AssertionError, match=None): + StringArray._from_sequence(["a", None, "c"], dtype="string[pyarrow]") + + with pd.option_context("string_storage", "python"): + StringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) + + with pytest.raises(AssertionError, match=None): + with pd.option_context("string_storage", "pyarrow"): + StringArray._from_sequence(["a", None, "c"], dtype=StringDtype()) + + StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("python")) + + with pytest.raises(AssertionError, match=None): + StringArray._from_sequence(["a", None, "c"], dtype=StringDtype("pyarrow")) + + @pytest.mark.skipif( not pa_version_under1p0, reason="pyarrow is installed", @@ -45,7 +125,7 @@ def test_pyarrow_not_installed_raises(): msg = re.escape("pyarrow>=1.0.0 is required for PyArrow backed StringArray") with pytest.raises(ImportError, match=msg): - ArrowStringDtype() + StringDtype(storage="pyarrow") with pytest.raises(ImportError, match=msg): ArrowStringArray([]) diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index bfe588883d9f3..61d56df485ab1 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -18,7 +18,6 @@ IntegerArray, IntervalArray, SparseArray, - StringArray, TimedeltaArray, ) from pandas.core.arrays import ( @@ -132,8 +131,16 @@ ([1, None], "Int16", pd.array([1, None], dtype="Int16")), (pd.Series([1, 2]), None, PandasArray(np.array([1, 2], dtype=np.int64))), # String - (["a", None], "string", StringArray._from_sequence(["a", None])), - (["a", None], pd.StringDtype(), StringArray._from_sequence(["a", None])), + ( + ["a", None], + "string", + pd.StringDtype().construct_array_type()._from_sequence(["a", None]), + ), + ( + ["a", None], + pd.StringDtype(), + pd.StringDtype().construct_array_type()._from_sequence(["a", None]), + ), # Boolean ([True, None], "boolean", BooleanArray._from_sequence([True, None])), ([True, None], pd.BooleanDtype(), BooleanArray._from_sequence([True, None])), @@ -253,8 +260,14 @@ def test_array_copy(): ([1, 2.0], FloatingArray._from_sequence([1.0, 2.0])), ([1, np.nan, 2.0], FloatingArray._from_sequence([1.0, None, 2.0])), # string - (["a", "b"], StringArray._from_sequence(["a", "b"])), - (["a", None], StringArray._from_sequence(["a", None])), + ( + ["a", "b"], + pd.StringDtype().construct_array_type()._from_sequence(["a", "b"]), + ), + ( + ["a", None], + pd.StringDtype().construct_array_type()._from_sequence(["a", None]), + ), # Boolean ([True, False], BooleanArray._from_sequence([True, False])), ([True, None], BooleanArray._from_sequence([True, None])), diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index c6f8efe7b939e..0bd10b36a8b5c 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -298,7 +298,7 @@ def test_searchsorted(self): assert result == 10 @pytest.mark.parametrize("box", [None, "index", "series"]) - def test_searchsorted_castable_strings(self, arr1d, box, request): + def test_searchsorted_castable_strings(self, arr1d, box, request, string_storage): if isinstance(arr1d, DatetimeArray): tz = arr1d.tz ts1, ts2 = arr1d[1:3] @@ -341,14 +341,17 @@ def test_searchsorted_castable_strings(self, arr1d, box, request): ): arr.searchsorted("foo") - with pytest.raises( - TypeError, - match=re.escape( - f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', " - "or array of those. Got 'StringArray' instead." - ), - ): - arr.searchsorted([str(arr[1]), "baz"]) + arr_type = "StringArray" if string_storage == "python" else "ArrowStringArray" + + with pd.option_context("string_storage", string_storage): + with pytest.raises( + TypeError, + match=re.escape( + f"value should be a '{arr1d._scalar_type.__name__}', 'NaT', " + f"or array of those. Got '{arr_type}' instead." + ), + ): + arr.searchsorted([str(arr[1]), "baz"]) def test_getitem_near_implementation_bounds(self): # We only check tz-naive for DTA bc the bounds are slightly different diff --git a/pandas/tests/extension/arrow/test_string.py b/pandas/tests/extension/arrow/test_string.py index 23a07b2031bf5..67a62978aa1bc 100644 --- a/pandas/tests/extension/arrow/test_string.py +++ b/pandas/tests/extension/arrow/test_string.py @@ -2,12 +2,11 @@ import pandas as pd -pytest.importorskip("pyarrow", minversion="0.13.0") - -from pandas.tests.extension.arrow.arrays import ArrowStringDtype # isort:skip +pytest.importorskip("pyarrow", minversion="1.0.0") def test_constructor_from_list(): # GH 27673 - result = pd.Series(["E"], dtype=ArrowStringDtype()) - assert isinstance(result.dtype, ArrowStringDtype) + result = pd.Series(["E"], dtype=pd.StringDtype(storage="pyarrow")) + assert isinstance(result.dtype, pd.StringDtype) + assert result.dtype.storage == "pyarrow" diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index 99a5666926e10..9c59c79f677de 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -48,16 +48,14 @@ def test_astype_str(self, data): @pytest.mark.parametrize( "nullable_string_dtype", [ - "string", + "string[python]", pytest.param( - "arrow_string", marks=td.skip_if_no("pyarrow", min_version="1.0.0") + "string[pyarrow]", marks=td.skip_if_no("pyarrow", min_version="1.0.0") ), ], ) def test_astype_string(self, data, nullable_string_dtype): # GH-33465 - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - result = pd.Series(data[:5]).astype(nullable_string_dtype) expected = pd.Series([str(x) for x in data[:5]], dtype=nullable_string_dtype) self.assert_series_equal(result, expected) diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index 49aee76e10f6a..3d0edb70d1ced 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -18,16 +18,13 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas.core.arrays.string_ import StringDtype -from pandas.core.arrays.string_arrow import ArrowStringDtype from pandas.tests.extension import base def split_array(arr): - if not isinstance(arr.dtype, ArrowStringDtype): + if arr.dtype.storage != "pyarrow": pytest.skip("chunked array n/a") def _split_array(arr): @@ -49,16 +46,9 @@ def chunked(request): return request.param -@pytest.fixture( - params=[ - StringDtype, - pytest.param( - ArrowStringDtype, marks=td.skip_if_no("pyarrow", min_version="1.0.0") - ), - ] -) -def dtype(request): - return request.param() +@pytest.fixture +def dtype(string_storage): + return StringDtype(storage=string_storage) @pytest.fixture @@ -104,24 +94,28 @@ def data_for_grouping(dtype, chunked): class TestDtype(base.BaseDtypeTests): - pass + def test_eq_with_str(self, dtype): + assert dtype == f"string[{dtype.storage}]" + super().test_eq_with_str(dtype) class TestInterface(base.BaseInterfaceTests): def test_view(self, data, request): - if isinstance(data.dtype, ArrowStringDtype): + if data.dtype.storage == "pyarrow": mark = pytest.mark.xfail(reason="not implemented") request.node.add_marker(mark) super().test_view(data) class TestConstructors(base.BaseConstructorsTests): - pass + def test_from_dtype(self, data): + # base test uses string representation of dtype + pass class TestReshaping(base.BaseReshapingTests): - def test_transpose(self, data, dtype, request): - if isinstance(dtype, ArrowStringDtype): + def test_transpose(self, data, request): + if data.dtype.storage == "pyarrow": mark = pytest.mark.xfail(reason="not implemented") request.node.add_marker(mark) super().test_transpose(data) @@ -132,8 +126,8 @@ class TestGetitem(base.BaseGetitemTests): class TestSetitem(base.BaseSetitemTests): - def test_setitem_preserves_views(self, data, dtype, request): - if isinstance(dtype, ArrowStringDtype): + def test_setitem_preserves_views(self, data, request): + if data.dtype.storage == "pyarrow": mark = pytest.mark.xfail(reason="not implemented") request.node.add_marker(mark) super().test_setitem_preserves_views(data) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 1583b3f91bea2..881f8db305240 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -584,10 +584,10 @@ def test_astype_empty_dtype_dict(self): @pytest.mark.parametrize( "data, dtype", [ - (["x", "y", "z"], "string"), + (["x", "y", "z"], "string[python]"), pytest.param( ["x", "y", "z"], - "arrow_string", + "string[pyarrow]", marks=td.skip_if_no("pyarrow", min_version="1.0.0"), ), (["x", "y", "z"], "category"), @@ -598,8 +598,6 @@ def test_astype_empty_dtype_dict(self): @pytest.mark.parametrize("errors", ["raise", "ignore"]) def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors): # https://github.com/pandas-dev/pandas/issues/35471 - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - df = DataFrame(Series(data, dtype=dtype)) if errors == "ignore": expected = df diff --git a/pandas/tests/frame/methods/test_convert_dtypes.py b/pandas/tests/frame/methods/test_convert_dtypes.py index dd7bf0aada449..a2d539d784d3c 100644 --- a/pandas/tests/frame/methods/test_convert_dtypes.py +++ b/pandas/tests/frame/methods/test_convert_dtypes.py @@ -9,7 +9,7 @@ class TestConvertDtypes: @pytest.mark.parametrize( "convert_integer, expected", [(False, np.dtype("int32")), (True, "Int32")] ) - def test_convert_dtypes(self, convert_integer, expected): + def test_convert_dtypes(self, convert_integer, expected, string_storage): # Specific types are tested in tests/series/test_dtypes.py # Just check that it works for DataFrame here df = pd.DataFrame( @@ -18,11 +18,12 @@ def test_convert_dtypes(self, convert_integer, expected): "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")), } ) - result = df.convert_dtypes(True, True, convert_integer, False) + with pd.option_context("string_storage", string_storage): + result = df.convert_dtypes(True, True, convert_integer, False) expected = pd.DataFrame( { "a": pd.Series([1, 2, 3], dtype=expected), - "b": pd.Series(["x", "y", "z"], dtype="string"), + "b": pd.Series(["x", "y", "z"], dtype=f"string[{string_storage}]"), } ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index ae6425cd93ac5..d100c584b698a 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -810,12 +810,11 @@ def test_additional_extension_arrays(self, pa): check_round_trip(df, pa) @td.skip_if_no("pyarrow", min_version="1.0.0") - def test_pyarrow_backed_string_array(self, pa): + def test_pyarrow_backed_string_array(self, pa, string_storage): # test ArrowStringArray supported through the __arrow_array__ protocol - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - - df = pd.DataFrame({"a": pd.Series(["a", None, "c"], dtype="arrow_string")}) - check_round_trip(df, pa, expected=df) + df = pd.DataFrame({"a": pd.Series(["a", None, "c"], dtype="string[pyarrow]")}) + with pd.option_context("string_storage", string_storage): + check_round_trip(df, pa, expected=df.astype(f"string[{string_storage}]")) @td.skip_if_no("pyarrow") def test_additional_extension_types(self, pa): diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index ffaecf1576364..99a7ba910eb74 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -249,10 +249,10 @@ def test_td64_series_astype_object(self): @pytest.mark.parametrize( "data, dtype", [ - (["x", "y", "z"], "string"), + (["x", "y", "z"], "string[python]"), pytest.param( ["x", "y", "z"], - "arrow_string", + "string[pyarrow]", marks=td.skip_if_no("pyarrow", min_version="1.0.0"), ), (["x", "y", "z"], "category"), @@ -263,9 +263,6 @@ def test_td64_series_astype_object(self): @pytest.mark.parametrize("errors", ["raise", "ignore"]) def test_astype_ignores_errors_for_extension_dtypes(self, data, dtype, errors): # https://github.com/pandas-dev/pandas/issues/35471 - - from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 - ser = Series(data, dtype=dtype) if errors == "ignore": expected = ser diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py index 9a64877cb92ff..d9d6641d54237 100644 --- a/pandas/tests/series/methods/test_update.py +++ b/pandas/tests/series/methods/test_update.py @@ -11,7 +11,6 @@ Timestamp, ) import pandas._testing as tm -from pandas.core.arrays.string_arrow import ArrowStringDtype # noqa: F401 class TestUpdate: @@ -87,12 +86,12 @@ def test_update_from_non_series(self, series, other, expected): @pytest.mark.parametrize( "data, other, expected, dtype", [ - (["a", None], [None, "b"], ["a", "b"], "string"), + (["a", None], [None, "b"], ["a", "b"], "string[python]"), pytest.param( ["a", None], [None, "b"], ["a", "b"], - "arrow_string", + "string[pyarrow]", marks=td.skip_if_no("pyarrow", min_version="1.0.0"), ), ([1, None], [None, 2], [1, 2], "Int64"), diff --git a/pandas/tests/strings/test_api.py b/pandas/tests/strings/test_api.py index ec8b5bfa11ad5..6cbf2dd606692 100644 --- a/pandas/tests/strings/test_api.py +++ b/pandas/tests/strings/test_api.py @@ -6,6 +6,7 @@ MultiIndex, Series, _testing as tm, + get_option, ) from pandas.core import strings as strings @@ -128,7 +129,9 @@ def test_api_per_method( def test_api_for_categorical(any_string_method, any_string_dtype, request): # https://github.com/pandas-dev/pandas/issues/10661 - if any_string_dtype == "arrow_string": + if any_string_dtype == "string[pyarrow]" or ( + any_string_dtype == "string" and get_option("string_storage") == "pyarrow" + ): # unsupported operand type(s) for +: 'ArrowStringArray' and 'str' mark = pytest.mark.xfail(raises=TypeError, reason="Not Implemented") request.node.add_marker(mark)
continuation of #36142 todo: - [x] during the merge I removed the import gymnastics from `pandas/core/arrays/string_arrow.py`. We added since `ArrowStringDtype` should always be available. I think this is no longer the case and we want to move the import checks to `StringDtype`. I expect envs without pyarrow to fail for now. - [x] `test_arrow_roundtrip` is failing. `StringDtype.__from_arrow__` needs updating. - [x] address @jorisvandenbossche comments https://github.com/pandas-dev/pandas/pull/36142#discussion_r484213504 and https://github.com/pandas-dev/pandas/pull/36142#discussion_r484213103 - [x] some other test failures `AssertionError: assert 'unknown-array' == 'string'`
https://api.github.com/repos/pandas-dev/pandas/pulls/39908
2021-02-19T14:03:54Z
2021-06-08T13:36:42Z
2021-06-08T13:36:42Z
2021-06-08T14:25:20Z
STYLE keep local imports relative
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d433fb08209bf..fbd2daf9204e8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -208,7 +208,8 @@ repos: hooks: - id: no-string-hints - repo: https://github.com/MarcoGorelli/abs-imports - rev: v0.1.2 + rev: c434798 hooks: - id: abs-imports files: ^pandas/ + args: [--keep-local-imports-relative] diff --git a/pandas/__init__.py b/pandas/__init__.py index cc4c99efc4345..b24dfe268c94b 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -19,14 +19,14 @@ del hard_dependencies, dependency, missing_dependencies # numpy compat -from pandas.compat import ( +from .compat import ( np_version_under1p17 as _np_version_under1p17, np_version_under1p18 as _np_version_under1p18, is_numpy_dev as _is_numpy_dev, ) try: - from pandas._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib + from ._libs import hashtable as _hashtable, lib as _lib, tslib as _tslib except ImportError as e: # pragma: no cover # hack but overkill to use re module = str(e).replace("cannot import name ", "") @@ -36,7 +36,7 @@ "'python setup.py build_ext --force' to build the C extensions first." ) from e -from pandas._config import ( +from ._config import ( get_option, set_option, reset_option, @@ -48,7 +48,7 @@ # let init-time option registration happen import pandas.core.config_init -from pandas.core.api import ( +from .core.api import ( # dtype Int8Dtype, Int16Dtype, @@ -115,14 +115,14 @@ DataFrame, ) -from pandas.core.arrays.sparse import SparseDtype +from .core.arrays.sparse import SparseDtype -from pandas.tseries.api import infer_freq -from pandas.tseries import offsets +from .tseries.api import infer_freq +from .tseries import offsets -from pandas.core.computation.api import eval +from .core.computation.api import eval -from pandas.core.reshape.api import ( +from .core.reshape.api import ( concat, lreshape, melt, @@ -139,9 +139,9 @@ ) import pandas.api -from pandas.util._print_versions import show_versions +from .util._print_versions import show_versions -from pandas.io.api import ( +from .io.api import ( # excel ExcelFile, ExcelWriter, @@ -173,14 +173,14 @@ read_spss, ) -from pandas.io.json import _json_normalize as json_normalize +from .io.json import _json_normalize as json_normalize -from pandas.util._tester import test +from .util._tester import test import pandas.testing import pandas.arrays # use the closest tagged version if possible -from pandas._version import get_versions +from ._version import get_versions v = get_versions() __version__ = v.get("closest-tag", v["version"]) @@ -237,7 +237,7 @@ def __getattr__(name): FutureWarning, stacklevel=2, ) - from pandas.core.arrays.sparse import SparseArray as _SparseArray + from .core.arrays.sparse import SparseArray as _SparseArray return _SparseArray diff --git a/pandas/_config/__init__.py b/pandas/_config/__init__.py index 65936a9fcdbf3..cbafa0edae1b6 100644 --- a/pandas/_config/__init__.py +++ b/pandas/_config/__init__.py @@ -15,9 +15,9 @@ "option_context", "options", ] -from pandas._config import config -from pandas._config import dates # noqa:F401 -from pandas._config.config import ( +from . import config +from . import dates # noqa:F401 +from .config import ( describe_option, get_option, option_context, @@ -25,4 +25,4 @@ reset_option, set_option, ) -from pandas._config.display import detect_console_encoding +from .display import detect_console_encoding diff --git a/pandas/_config/dates.py b/pandas/_config/dates.py index 5bf2b49ce5904..f59cbd6339932 100644 --- a/pandas/_config/dates.py +++ b/pandas/_config/dates.py @@ -1,7 +1,7 @@ """ config for datetime formatting """ -from pandas._config import config as cf +from . import config as cf pc_date_dayfirst_doc = """ : boolean diff --git a/pandas/_config/display.py b/pandas/_config/display.py index ec819481525da..7ae66e3fc1f11 100644 --- a/pandas/_config/display.py +++ b/pandas/_config/display.py @@ -6,7 +6,7 @@ import sys from typing import Optional -from pandas._config import config as cf +from . import config as cf # ----------------------------------------------------------------------------- # Global formatting options diff --git a/pandas/_config/localization.py b/pandas/_config/localization.py index bc76aca93da2a..76b442da651ac 100644 --- a/pandas/_config/localization.py +++ b/pandas/_config/localization.py @@ -8,7 +8,7 @@ import re import subprocess -from pandas._config.config import options +from .config import options @contextmanager diff --git a/pandas/_libs/__init__.py b/pandas/_libs/__init__.py index f119e280f5867..4ea32377d1446 100644 --- a/pandas/_libs/__init__.py +++ b/pandas/_libs/__init__.py @@ -10,8 +10,8 @@ ] -from pandas._libs.interval import Interval -from pandas._libs.tslibs import ( +from .interval import Interval +from .tslibs import ( NaT, NaTType, OutOfBoundsDatetime, diff --git a/pandas/_libs/tslibs/__init__.py b/pandas/_libs/tslibs/__init__.py index e38ed9a20e55b..ddd41f48a374e 100644 --- a/pandas/_libs/tslibs/__init__.py +++ b/pandas/_libs/tslibs/__init__.py @@ -27,38 +27,38 @@ "tz_compare", ] -from pandas._libs.tslibs import dtypes -from pandas._libs.tslibs.conversion import ( +from . import dtypes +from .conversion import ( OutOfBoundsTimedelta, localize_pydatetime, ) -from pandas._libs.tslibs.dtypes import Resolution -from pandas._libs.tslibs.nattype import ( +from .dtypes import Resolution +from .nattype import ( NaT, NaTType, iNaT, is_null_datetimelike, nat_strings, ) -from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime -from pandas._libs.tslibs.offsets import ( +from .np_datetime import OutOfBoundsDatetime +from .offsets import ( BaseOffset, Tick, to_offset, ) -from pandas._libs.tslibs.period import ( +from .period import ( IncompatibleFrequency, Period, ) -from pandas._libs.tslibs.timedeltas import ( +from .timedeltas import ( Timedelta, delta_to_nanoseconds, ints_to_pytimedelta, ) -from pandas._libs.tslibs.timestamps import Timestamp -from pandas._libs.tslibs.timezones import tz_compare -from pandas._libs.tslibs.tzconversion import tz_convert_from_utc_single -from pandas._libs.tslibs.vectorized import ( +from .timestamps import Timestamp +from .timezones import tz_compare +from .tzconversion import tz_convert_from_utc_single +from .vectorized import ( dt64arr_to_periodarr, get_resolution, ints_to_pydatetime, diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 6b88bd26627b0..80d11d59b330a 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -49,7 +49,14 @@ Series, bdate_range, ) -from pandas._testing._io import ( # noqa:F401 +from pandas.core.arrays import ( + DatetimeArray, + PeriodArray, + TimedeltaArray, + period_array, +) + +from ._io import ( # noqa:F401 close, network, round_trip_localpath, @@ -58,14 +65,14 @@ with_connectivity_check, write_to_compressed, ) -from pandas._testing._random import ( # noqa:F401 +from ._random import ( # noqa:F401 randbool, rands, rands_array, randu_array, ) -from pandas._testing._warnings import assert_produces_warning # noqa:F401 -from pandas._testing.asserters import ( # noqa:F401 +from ._warnings import assert_produces_warning # noqa:F401 +from .asserters import ( # noqa:F401 assert_almost_equal, assert_attr_equal, assert_categorical_equal, @@ -88,8 +95,8 @@ assert_timedelta_array_equal, raise_assert_detail, ) -from pandas._testing.compat import get_dtype # noqa:F401 -from pandas._testing.contexts import ( # noqa:F401 +from .compat import get_dtype # noqa:F401 +from .contexts import ( # noqa:F401 RNGContext, decompress_file, ensure_clean, @@ -99,12 +106,6 @@ use_numexpr, with_csv_dialect, ) -from pandas.core.arrays import ( - DatetimeArray, - PeriodArray, - TimedeltaArray, - period_array, -) if TYPE_CHECKING: from pandas import ( diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py index e327f48f9a888..4cc49043b1e25 100644 --- a/pandas/_testing/_io.py +++ b/pandas/_testing/_io.py @@ -19,11 +19,12 @@ ) import pandas as pd -from pandas._testing._random import rands -from pandas._testing.contexts import ensure_clean from pandas.io.common import urlopen +from ._random import rands +from .contexts import ensure_clean + _RAISE_NETWORK_ERROR_DEFAULT = False lzma = import_lzma() diff --git a/pandas/_typing.py b/pandas/_typing.py index 074b57054c0d1..fc3c209df0200 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -38,32 +38,29 @@ if TYPE_CHECKING: from typing import final - from pandas._libs import ( + from . import Interval + from ._libs import ( Period, Timedelta, Timestamp, ) - - from pandas.core.dtypes.dtypes import ExtensionDtype - - from pandas import Interval - from pandas.core.arrays.base import ExtensionArray # noqa: F401 - from pandas.core.frame import DataFrame - from pandas.core.generic import NDFrame # noqa: F401 - from pandas.core.groupby.generic import ( + from .core.arrays.base import ExtensionArray # noqa: F401 + from .core.dtypes.dtypes import ExtensionDtype + from .core.frame import DataFrame + from .core.generic import NDFrame # noqa: F401 + from .core.groupby.generic import ( DataFrameGroupBy, SeriesGroupBy, ) - from pandas.core.indexes.base import Index - from pandas.core.internals import ( + from .core.indexes.base import Index + from .core.internals import ( ArrayManager, BlockManager, ) - from pandas.core.resample import Resampler - from pandas.core.series import Series - from pandas.core.window.rolling import BaseWindow - - from pandas.io.formats.format import EngFormatter + from .core.resample import Resampler + from .core.series import Series + from .core.window.rolling import BaseWindow + from .io.formats.format import EngFormatter else: # typing.final does not exist until py38 final = lambda x: x diff --git a/pandas/api/__init__.py b/pandas/api/__init__.py index c22f37f2ef292..9c524cabae3dd 100644 --- a/pandas/api/__init__.py +++ b/pandas/api/__init__.py @@ -1,5 +1,5 @@ """ public toolkit API """ -from pandas.api import ( # noqa +from . import ( # noqa extensions, indexers, types, diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index eb6cf4f9d7d85..9cb8543f9fe0f 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -12,7 +12,8 @@ import warnings from pandas._typing import F -from pandas.compat.numpy import ( + +from .numpy import ( is_numpy_dev, np_array_datetime64_compat, np_datetime64_compat, diff --git a/pandas/conftest.py b/pandas/conftest.py index ce572e42abec6..bb1ef6738142f 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -45,13 +45,10 @@ import pandas.util._test_decorators as td -from pandas.core.dtypes.dtypes import ( - DatetimeTZDtype, - IntervalDtype, -) - import pandas as pd -from pandas import ( +import pandas._testing as tm + +from . import ( DataFrame, Interval, Period, @@ -59,9 +56,12 @@ Timedelta, Timestamp, ) -import pandas._testing as tm -from pandas.core import ops -from pandas.core.indexes.api import ( +from .core import ops +from .core.dtypes.dtypes import ( + DatetimeTZDtype, + IntervalDtype, +) +from .core.indexes.api import ( Index, MultiIndex, ) diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 744a1ffa5fea1..f3b02dfebf523 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -32,22 +32,22 @@ FrameOrSeriesUnion, ) -from pandas.core.dtypes.common import ( +import pandas.core.common as com + +from .algorithms import safe_sort +from .base import SpecificationError +from .dtypes.common import ( is_dict_like, is_list_like, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCDataFrame, ABCSeries, ) - -from pandas.core.algorithms import safe_sort -from pandas.core.base import SpecificationError -import pandas.core.common as com -from pandas.core.indexes.api import Index +from .indexes.api import Index if TYPE_CHECKING: - from pandas.core.series import Series + from .series import Series def reconstruct_func( @@ -482,7 +482,7 @@ def transform_dict_like( """ Compute transform in the case of a dict-like func """ - from pandas.core.reshape.concat import concat + from .reshape.concat import concat if len(func) == 0: raise ValueError("No transform functions were provided") diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 40533cdd554b3..f82fdf8b44c76 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -36,12 +36,17 @@ ) from pandas.util._decorators import doc -from pandas.core.dtypes.cast import ( +from .construction import ( + array, + ensure_wrapped_if_datetimelike, + extract_array, +) +from .dtypes.cast import ( construct_1d_object_array_from_listlike, infer_dtype_from_array, maybe_promote, ) -from pandas.core.dtypes.common import ( +from .dtypes.common import ( ensure_float64, ensure_int64, ensure_object, @@ -68,8 +73,8 @@ needs_i8_conversion, pandas_dtype, ) -from pandas.core.dtypes.dtypes import PandasDtype -from pandas.core.dtypes.generic import ( +from .dtypes.dtypes import PandasDtype +from .dtypes.generic import ( ABCDatetimeArray, ABCExtensionArray, ABCIndex, @@ -78,17 +83,11 @@ ABCSeries, ABCTimedeltaArray, ) -from pandas.core.dtypes.missing import ( +from .dtypes.missing import ( isna, na_value_for_dtype, ) - -from pandas.core.construction import ( - array, - ensure_wrapped_if_datetimelike, - extract_array, -) -from pandas.core.indexers import validate_indices +from .indexers import validate_indices if TYPE_CHECKING: from pandas import ( @@ -97,7 +96,8 @@ Index, Series, ) - from pandas.core.arrays import ( + + from .arrays import ( DatetimeArray, TimedeltaArray, ) @@ -819,12 +819,12 @@ def value_counts( ------- Series """ - from pandas.core.series import Series + from .series import Series name = getattr(values, "name", None) if bins is not None: - from pandas.core.reshape.tile import cut + from .reshape.tile import cut values = Series(values) try: @@ -2247,8 +2247,8 @@ def _sort_tuples(values: np.ndarray): nans (can't use `np.sort` as it may fail when str and nan are mixed in a column as types cannot be compared). """ - from pandas.core.internals.construction import to_arrays - from pandas.core.sorting import lexsort_indexer + from .internals.construction import to_arrays + from .sorting import lexsort_indexer arrays, _ = to_arrays(values, None) indexer = lexsort_indexer(arrays, orders=True) diff --git a/pandas/core/api.py b/pandas/core/api.py index 2677530455b07..9037edee5f253 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -8,31 +8,21 @@ ) from pandas._libs.missing import NA -from pandas.core.dtypes.dtypes import ( - CategoricalDtype, - DatetimeTZDtype, - IntervalDtype, - PeriodDtype, -) -from pandas.core.dtypes.missing import ( - isna, - isnull, - notna, - notnull, -) +from pandas.io.formats.format import set_eng_float_format +from pandas.tseries.offsets import DateOffset -from pandas.core.algorithms import ( +from .algorithms import ( factorize, unique, value_counts, ) -from pandas.core.arrays import Categorical -from pandas.core.arrays.boolean import BooleanDtype -from pandas.core.arrays.floating import ( +from .arrays import Categorical +from .arrays.boolean import BooleanDtype +from .arrays.floating import ( Float32Dtype, Float64Dtype, ) -from pandas.core.arrays.integer import ( +from .arrays.integer import ( Int8Dtype, Int16Dtype, Int32Dtype, @@ -42,14 +32,26 @@ UInt32Dtype, UInt64Dtype, ) -from pandas.core.arrays.string_ import StringDtype -from pandas.core.construction import array -from pandas.core.flags import Flags -from pandas.core.groupby import ( +from .arrays.string_ import StringDtype +from .construction import array +from .dtypes.dtypes import ( + CategoricalDtype, + DatetimeTZDtype, + IntervalDtype, + PeriodDtype, +) +from .dtypes.missing import ( + isna, + isnull, + notna, + notnull, +) +from .flags import Flags +from .groupby import ( Grouper, NamedAgg, ) -from pandas.core.indexes.api import ( +from .indexes.api import ( CategoricalIndex, DatetimeIndex, Float64Index, @@ -62,24 +64,21 @@ TimedeltaIndex, UInt64Index, ) -from pandas.core.indexes.datetimes import ( +from .indexes.datetimes import ( bdate_range, date_range, ) -from pandas.core.indexes.interval import ( +from .indexes.interval import ( Interval, interval_range, ) -from pandas.core.indexes.period import period_range -from pandas.core.indexes.timedeltas import timedelta_range -from pandas.core.indexing import IndexSlice -from pandas.core.series import Series -from pandas.core.tools.datetimes import to_datetime -from pandas.core.tools.numeric import to_numeric -from pandas.core.tools.timedeltas import to_timedelta - -from pandas.io.formats.format import set_eng_float_format -from pandas.tseries.offsets import DateOffset +from .indexes.period import period_range +from .indexes.timedeltas import timedelta_range +from .indexing import IndexSlice +from .series import Series +from .tools.datetimes import to_datetime +from .tools.numeric import to_numeric +from .tools.timedeltas import to_timedelta # DataFrame needs to be imported after NamedAgg to avoid a circular import -from pandas.core.frame import DataFrame # isort:skip +from .frame import DataFrame # isort:skip diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b41c432dff172..1b4583c9fcc44 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -30,42 +30,43 @@ ) from pandas.util._decorators import cache_readonly -from pandas.core.dtypes.cast import is_nested_object -from pandas.core.dtypes.common import ( +import pandas.core.common as com + +from .algorithms import safe_sort +from .base import ( + DataError, + SpecificationError, +) +from .construction import ( + array as pd_array, + create_series_with_explicit_dtype, +) +from .dtypes.cast import is_nested_object +from .dtypes.common import ( is_dict_like, is_extension_array_dtype, is_list_like, is_sequence, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCDataFrame, ABCNDFrame, ABCSeries, ) -from pandas.core.algorithms import safe_sort -from pandas.core.base import ( - DataError, - SpecificationError, -) -import pandas.core.common as com -from pandas.core.construction import ( - array as pd_array, - create_series_with_explicit_dtype, -) - if TYPE_CHECKING: from pandas import ( DataFrame, Index, Series, ) - from pandas.core.groupby import ( + + from .groupby import ( DataFrameGroupBy, SeriesGroupBy, ) - from pandas.core.resample import Resampler - from pandas.core.window.rolling import BaseWindow + from .resample import Resampler + from .window.rolling import BaseWindow ResType = Dict[int, Any] @@ -210,7 +211,7 @@ def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion: ------- Result of aggregation. """ - from pandas.core.reshape.concat import concat + from .reshape.concat import concat obj = self.obj arg = cast(List[AggFuncTypeBase], self.f) @@ -355,7 +356,7 @@ def agg_dict_like(self, _axis: int) -> FrameOrSeriesUnion: ) raise SpecificationError(f"Column(s) {cols} do not exist") - from pandas.core.reshape.concat import concat + from .reshape.concat import concat if selected_obj.ndim == 1: # key only used for output diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index 3f45f503d0f62..4cf7a2e3065ac 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -15,12 +15,12 @@ from pandas._libs import lib -from pandas.core.construction import extract_array -from pandas.core.ops import ( +from .construction import extract_array +from .ops import ( maybe_dispatch_ufunc_to_dunder_op, roperator, ) -from pandas.core.ops.common import unpack_zerodim_and_defer +from .ops.common import unpack_zerodim_and_defer class OpsMixin: @@ -183,7 +183,8 @@ def _maybe_fallback(ufunc: Callable, method: str, *inputs: Any, **kwargs: Any): See https://github.com/pandas-dev/pandas/pull/39239 """ from pandas import DataFrame - from pandas.core.generic import NDFrame + + from .generic import NDFrame n_alignable = sum(isinstance(x, NDFrame) for x in inputs) n_frames = sum(isinstance(x, DataFrame) for x in inputs) @@ -242,8 +243,8 @@ def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any) -------- numpy.org/doc/stable/reference/arrays.classes.html#numpy.class.__array_ufunc__ """ - from pandas.core.generic import NDFrame - from pandas.core.internals import BlockManager + from .generic import NDFrame + from .internals import BlockManager cls = type(self) diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index 22f15ca9650db..599e8ac98c6f6 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -1,23 +1,23 @@ -from pandas.core.arrays.base import ( +from .base import ( ExtensionArray, ExtensionOpsMixin, ExtensionScalarOpsMixin, ) -from pandas.core.arrays.boolean import BooleanArray -from pandas.core.arrays.categorical import Categorical -from pandas.core.arrays.datetimes import DatetimeArray -from pandas.core.arrays.floating import FloatingArray -from pandas.core.arrays.integer import IntegerArray -from pandas.core.arrays.interval import IntervalArray -from pandas.core.arrays.masked import BaseMaskedArray -from pandas.core.arrays.numpy_ import PandasArray -from pandas.core.arrays.period import ( +from .boolean import BooleanArray +from .categorical import Categorical +from .datetimes import DatetimeArray +from .floating import FloatingArray +from .integer import IntegerArray +from .interval import IntervalArray +from .masked import BaseMaskedArray +from .numpy_ import PandasArray +from .period import ( PeriodArray, period_array, ) -from pandas.core.arrays.sparse import SparseArray -from pandas.core.arrays.string_ import StringArray -from pandas.core.arrays.timedeltas import TimedeltaArray +from .sparse import SparseArray +from .string_ import StringArray +from .timedeltas import TimedeltaArray __all__ = [ "ExtensionArray", diff --git a/pandas/core/arrays/_arrow_utils.py b/pandas/core/arrays/_arrow_utils.py index 31f6896b12f98..9bf40706e1141 100644 --- a/pandas/core/arrays/_arrow_utils.py +++ b/pandas/core/arrays/_arrow_utils.py @@ -4,7 +4,7 @@ import numpy as np import pyarrow -from pandas.core.arrays.interval import VALID_CLOSED +from .interval import VALID_CLOSED _pyarrow_version_ge_015 = LooseVersion(pyarrow.__version__) >= LooseVersion("0.15") diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 825757ddffee4..2a2d62073d092 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -33,10 +33,11 @@ value_counts, ) from pandas.core.array_algos.transforms import shift -from pandas.core.arrays.base import ExtensionArray from pandas.core.construction import extract_array from pandas.core.indexers import check_array_indexer +from .base import ExtensionArray + NDArrayBackedExtensionArrayT = TypeVar( "NDArrayBackedExtensionArrayT", bound="NDArrayBackedExtensionArray" ) diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index edc8fa14ca142..209298819ca0b 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -515,8 +515,8 @@ def astype(self, dtype, copy=True): array : ndarray NumPy ndarray with 'dtype' for its dtype. """ - from pandas.core.arrays.string_ import StringDtype - from pandas.core.arrays.string_arrow import ArrowStringDtype + from .string_ import StringDtype + from .string_arrow import ArrowStringDtype dtype = pandas_dtype(dtype) if is_dtype_equal(dtype, self.dtype): diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 260cd08707473..52c19d1025dd2 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -39,7 +39,8 @@ from pandas.core.dtypes.missing import isna from pandas.core import ops -from pandas.core.arrays.masked import ( + +from .masked import ( BaseMaskedArray, BaseMaskedDtype, ) @@ -727,7 +728,7 @@ def _maybe_mask_result(self, result, mask, other, op_name: str): if (is_float_dtype(other) or is_float(other)) or ( op_name in ["rtruediv", "truediv"] ): - from pandas.core.arrays import FloatingArray + from . import FloatingArray return FloatingArray(result, mask, copy=False) @@ -735,7 +736,7 @@ def _maybe_mask_result(self, result, mask, other, op_name: str): return BooleanArray(result, mask, copy=False) elif is_integer_dtype(result): - from pandas.core.arrays import IntegerArray + from . import IntegerArray return IntegerArray(result, mask, copy=False) else: diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 916d4f9f2fd28..66ecd7940c68a 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -91,7 +91,6 @@ take_nd, unique1d, ) -from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.base import ( ExtensionArray, NoNewAttributesMixin, @@ -111,6 +110,8 @@ from pandas.io.formats import console +from ._mixins import NDArrayBackedExtensionArray + if TYPE_CHECKING: from pandas import Index @@ -2391,7 +2392,7 @@ def _str_map(self, f, na_value=np.nan, dtype=np.dtype(object)): # Optimization to apply the callable `f` to the categories once # and rebuild the result by `take`ing from the result with the codes. # Returns the same type as the object-dtype implementation though. - from pandas.core.arrays import PandasArray + from . import PandasArray categories = self.categories codes = self.codes @@ -2400,7 +2401,7 @@ def _str_map(self, f, na_value=np.nan, dtype=np.dtype(object)): def _str_get_dummies(self, sep="|"): # sep may not be in categories. Just bail on this. - from pandas.core.arrays import PandasArray + from . import PandasArray return PandasArray(self.astype(str))._str_get_dummies(sep) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 5dd55ff0f1fa2..ee4430bccfff7 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -94,10 +94,6 @@ unique1d, ) from pandas.core.arraylike import OpsMixin -from pandas.core.arrays._mixins import ( - NDArrayBackedExtensionArray, - ravel_compat, -) import pandas.core.common as com from pandas.core.construction import ( array, @@ -115,8 +111,13 @@ from pandas.tseries import frequencies +from ._mixins import ( + NDArrayBackedExtensionArray, + ravel_compat, +) + if TYPE_CHECKING: - from pandas.core.arrays import ( + from . import ( DatetimeArray, TimedeltaArray, ) @@ -1086,7 +1087,7 @@ def _add_timedelta_arraylike(self, other): if isinstance(other, np.ndarray): # ndarray[timedelta64]; wrap in TimedeltaIndex for op - from pandas.core.arrays import TimedeltaArray + from . import TimedeltaArray other = TimedeltaArray._from_sequence(other) @@ -1250,7 +1251,7 @@ def __add__(self, other): return NotImplemented if isinstance(result, np.ndarray) and is_timedelta64_dtype(result.dtype): - from pandas.core.arrays import TimedeltaArray + from . import TimedeltaArray return TimedeltaArray(result) return result @@ -1306,7 +1307,7 @@ def __sub__(self, other): return NotImplemented if isinstance(result, np.ndarray) and is_timedelta64_dtype(result.dtype): - from pandas.core.arrays import TimedeltaArray + from . import TimedeltaArray return TimedeltaArray(result) return result @@ -1322,7 +1323,7 @@ def __rsub__(self, other): return Timestamp(other) - self if not isinstance(other, DatetimeLikeArrayMixin): # Avoid down-casting DatetimeIndex - from pandas.core.arrays import DatetimeArray + from . import DatetimeArray other = DatetimeArray(other) return other - self diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 05184ea02e7a2..f0ad8189faf68 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -67,8 +67,6 @@ from pandas.core.dtypes.missing import isna from pandas.core.algorithms import checked_add_with_arr -from pandas.core.arrays import datetimelike as dtl -from pandas.core.arrays._ranges import generate_regular_range import pandas.core.common as com from pandas.tseries.frequencies import get_period_alias @@ -78,6 +76,9 @@ Tick, ) +from . import datetimelike as dtl +from ._ranges import generate_regular_range + _midnight = time(0, 0) @@ -1109,7 +1110,7 @@ def to_period(self, freq=None): PeriodIndex(['2017-01-01', '2017-01-02'], dtype='period[D]', freq='D') """ - from pandas.core.arrays import PeriodArray + from . import PeriodArray if self.tz is not None: warnings.warn( @@ -1158,7 +1159,7 @@ def to_perioddelta(self, freq): FutureWarning, stacklevel=3, ) - from pandas.core.arrays.timedeltas import TimedeltaArray + from .timedeltas import TimedeltaArray i8delta = self.asi8 - self.to_period(freq).to_timestamp().asi8 m8delta = i8delta.view("m8[ns]") @@ -1890,7 +1891,7 @@ def std( # Because std is translation-invariant, we can get self.std # by calculating (self - Timestamp(0)).std, and we can do it # without creating a copy by using a view on self._ndarray - from pandas.core.arrays import TimedeltaArray + from . import TimedeltaArray tda = TimedeltaArray(self._ndarray.view("i8")) return tda.std( diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index a43b30f5043e2..152643769d25d 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -37,12 +37,13 @@ ) from pandas.core.dtypes.missing import isna -from pandas.core.arrays.numeric import ( +from pandas.core.ops import invalid_comparison +from pandas.core.tools.numeric import to_numeric + +from .numeric import ( NumericArray, NumericDtype, ) -from pandas.core.ops import invalid_comparison -from pandas.core.tools.numeric import to_numeric class FloatingDtype(NumericDtype): diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index d62a05253b265..f0004147251f6 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -40,16 +40,17 @@ ) from pandas.core.dtypes.missing import isna -from pandas.core.arrays.masked import ( +from pandas.core.ops import invalid_comparison +from pandas.core.tools.numeric import to_numeric + +from .masked import ( BaseMaskedArray, BaseMaskedDtype, ) -from pandas.core.arrays.numeric import ( +from .numeric import ( NumericArray, NumericDtype, ) -from pandas.core.ops import invalid_comparison -from pandas.core.tools.numeric import to_numeric class _IntegerDtype(NumericDtype): @@ -106,7 +107,7 @@ def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: if np.issubdtype(np_dtype, np.integer): return INT_STR_TO_DTYPE[str(np_dtype)] elif np.issubdtype(np_dtype, np.floating): - from pandas.core.arrays.floating import FLOAT_STR_TO_DTYPE + from .floating import FLOAT_STR_TO_DTYPE return FLOAT_STR_TO_DTYPE[str(np_dtype)] return None @@ -401,7 +402,7 @@ def _values_for_argsort(self) -> np.ndarray: return data def _cmp_method(self, other, op): - from pandas.core.arrays import BooleanArray + from . import BooleanArray mask = None @@ -476,12 +477,12 @@ def _maybe_mask_result(self, result, mask, other, op_name: str): if (is_float_dtype(other) or is_float(other)) or ( op_name in ["rtruediv", "truediv"] ): - from pandas.core.arrays import FloatingArray + from . import FloatingArray return FloatingArray(result, mask, copy=False) if result.dtype == "timedelta64[ns]": - from pandas.core.arrays import TimedeltaArray + from . import TimedeltaArray result[mask] = iNaT return TimedeltaArray._simple_new(result) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 6cfc0e1853b74..870f8acdab002 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -69,11 +69,6 @@ take, value_counts, ) -from pandas.core.arrays.base import ( - ExtensionArray, - _extension_array_shared_docs, -) -from pandas.core.arrays.categorical import Categorical import pandas.core.common as com from pandas.core.construction import ( array, @@ -87,6 +82,12 @@ unpack_zerodim_and_defer, ) +from .base import ( + ExtensionArray, + _extension_array_shared_docs, +) +from .categorical import Categorical + IntervalArrayT = TypeVar("IntervalArrayT", bound="IntervalArray") _interval_shared_docs = {} @@ -808,7 +809,8 @@ def astype(self, dtype, copy=True): ExtensionArray or NumPy ndarray with 'dtype' for its dtype. """ from pandas import Index - from pandas.core.arrays.string_ import StringDtype + + from .string_ import StringDtype if dtype is not None: dtype = pandas_dtype(dtype) @@ -1370,7 +1372,7 @@ def __arrow_array__(self, type=None): """ import pyarrow - from pandas.core.arrays._arrow_utils import ArrowIntervalType + from ._arrow_utils import ArrowIntervalType try: subtype = pyarrow.from_numpy_dtype(self.dtype.subtype) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index bae14f4e560c2..2580005a11642 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -51,12 +51,14 @@ ) from pandas.core.array_algos import masked_reductions from pandas.core.arraylike import OpsMixin -from pandas.core.arrays import ExtensionArray from pandas.core.indexers import check_array_indexer +from . import ExtensionArray + if TYPE_CHECKING: from pandas import Series - from pandas.core.arrays import BooleanArray + + from . import BooleanArray BaseMaskedArrayT = TypeVar("BaseMaskedArrayT", bound="BaseMaskedArray") @@ -358,7 +360,7 @@ def take( def isin(self, values) -> BooleanArray: - from pandas.core.arrays import BooleanArray + from . import BooleanArray result = isin(self._data, values) if self._hasna: diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index 57017e44a66e9..73a3e4841af70 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -26,7 +26,8 @@ ) from pandas.core import ops -from pandas.core.arrays.masked import ( + +from .masked import ( BaseMaskedArray, BaseMaskedDtype, ) @@ -44,7 +45,7 @@ def __from_arrow__( """ import pyarrow - from pandas.core.arrays._arrow_utils import pyarrow_array_to_numpy_and_mask + from ._arrow_utils import pyarrow_array_to_numpy_and_mask array_class = self.construct_array_type() @@ -181,12 +182,12 @@ def reconstruct(x): # raise for reduce up above. if is_integer_dtype(x.dtype): - from pandas.core.arrays import IntegerArray + from . import IntegerArray m = mask.copy() return IntegerArray(x, m) elif is_float_dtype(x.dtype): - from pandas.core.arrays import FloatingArray + from . import FloatingArray m = mask.copy() return FloatingArray(x, m) diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index fd95ab987b18a..e03fdc50d4f56 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -27,9 +27,10 @@ ops, ) from pandas.core.arraylike import OpsMixin -from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.strings.object_array import ObjectStringArrayMixin +from ._mixins import NDArrayBackedExtensionArray + class PandasArray( OpsMixin, @@ -390,7 +391,7 @@ def _wrap_ndarray_result(self, result: np.ndarray): # If we have timedelta64[ns] result, return a TimedeltaArray instead # of a PandasArray if result.dtype == "timedelta64[ns]": - from pandas.core.arrays import TimedeltaArray + from . import TimedeltaArray return TimedeltaArray._simple_new(result) return type(self)(result) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 109be2c67bb1a..c5008b10e37c5 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -73,9 +73,10 @@ ) import pandas.core.algorithms as algos -from pandas.core.arrays import datetimelike as dtl import pandas.core.common as com +from . import datetimelike as dtl + _shared_doc_kwargs = { "klass": "PeriodArray", } @@ -343,7 +344,7 @@ def __arrow_array__(self, type=None): """ import pyarrow - from pandas.core.arrays._arrow_utils import ArrowPeriodType + from ._arrow_utils import ArrowPeriodType if type is not None: if pyarrow.types.is_integer(type): @@ -462,7 +463,7 @@ def to_timestamp(self, freq=None, how="start"): ------- DatetimeArray/Index """ - from pandas.core.arrays import DatetimeArray + from . import DatetimeArray how = libperiod.validate_end_alias(how) diff --git a/pandas/core/arrays/sparse/__init__.py b/pandas/core/arrays/sparse/__init__.py index 18294ead0329d..b11af8f6fbb6b 100644 --- a/pandas/core/arrays/sparse/__init__.py +++ b/pandas/core/arrays/sparse/__init__.py @@ -1,13 +1,13 @@ # flake8: noqa: F401 -from pandas.core.arrays.sparse.accessor import ( +from .accessor import ( SparseAccessor, SparseFrameAccessor, ) -from pandas.core.arrays.sparse.array import ( +from .array import ( BlockIndex, IntIndex, SparseArray, make_sparse_index, ) -from pandas.core.arrays.sparse.dtype import SparseDtype +from .dtype import SparseDtype diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index c3d11793dbd8c..73f190dda45e6 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -10,8 +10,9 @@ PandasDelegate, delegate_names, ) -from pandas.core.arrays.sparse.array import SparseArray -from pandas.core.arrays.sparse.dtype import SparseDtype + +from .array import SparseArray +from .dtype import SparseDtype class BaseAccessor: @@ -91,7 +92,8 @@ def from_coo(cls, A, dense_index=False): dtype: Sparse[float64, nan] """ from pandas import Series - from pandas.core.arrays.sparse.scipy_sparse import coo_to_sparse_series + + from .scipy_sparse import coo_to_sparse_series result = coo_to_sparse_series(A, dense_index=dense_index) result = Series(result.array, index=result.index, copy=False) @@ -171,7 +173,7 @@ def to_coo(self, row_levels=(0,), column_levels=(1,), sort_labels=False): >>> columns [('a', 0), ('a', 1), ('b', 0), ('b', 1)] """ - from pandas.core.arrays.sparse.scipy_sparse import sparse_series_to_coo + from .scipy_sparse import sparse_series_to_coo A, rows, columns = sparse_series_to_coo( self._parent, row_levels, column_levels, sort_labels=sort_labels diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index a209037f9a9a6..619ec29ace892 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -66,7 +66,6 @@ import pandas.core.algorithms as algos from pandas.core.arraylike import OpsMixin from pandas.core.arrays import ExtensionArray -from pandas.core.arrays.sparse.dtype import SparseDtype from pandas.core.base import PandasObject import pandas.core.common as com from pandas.core.construction import ( @@ -80,6 +79,8 @@ import pandas.io.formats.printing as printing +from .dtype import SparseDtype + # ---------------------------------------------------------------------------- # Array diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 948edcbd99e64..06e669a1ef338 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -39,7 +39,7 @@ ) if TYPE_CHECKING: - from pandas.core.arrays.sparse.array import SparseArray + from .array import SparseArray @register_extension_dtype @@ -197,7 +197,7 @@ def construct_array_type(cls) -> Type[SparseArray]: ------- type """ - from pandas.core.arrays.sparse.array import SparseArray + from .array import SparseArray return SparseArray diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 6fd68050bc8dc..b78f70318705f 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -35,16 +35,17 @@ from pandas.core import ops from pandas.core.array_algos import masked_reductions -from pandas.core.arrays import ( +from pandas.core.construction import extract_array +from pandas.core.indexers import check_array_indexer +from pandas.core.missing import isna + +from . import ( FloatingArray, IntegerArray, PandasArray, ) -from pandas.core.arrays.floating import FloatingDtype -from pandas.core.arrays.integer import _IntegerDtype -from pandas.core.construction import extract_array -from pandas.core.indexers import check_array_indexer -from pandas.core.missing import isna +from .floating import FloatingDtype +from .integer import _IntegerDtype if TYPE_CHECKING: import pyarrow @@ -229,7 +230,7 @@ def _from_sequence(cls, scalars, *, dtype: Optional[Dtype] = None, copy=False): if dtype: assert dtype == "string" - from pandas.core.arrays.masked import BaseMaskedArray + from .masked import BaseMaskedArray if isinstance(scalars, BaseMaskedArray): # avoid costly conversion to object dtype @@ -408,7 +409,8 @@ def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None): IntegerArray, StringArray, ) - from pandas.core.arrays.string_ import StringDtype + + from .string_ import StringDtype if dtype is None: dtype = StringDtype() diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index e2b0ad372bf88..0a2be48f4dc8a 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -34,13 +34,14 @@ is_scalar, ) from pandas.core.arraylike import OpsMixin -from pandas.core.arrays.base import ExtensionArray from pandas.core.indexers import ( check_array_indexer, validate_indices, ) from pandas.core.missing import get_fill_func +from .base import ExtensionArray + try: import pyarrow as pa except ImportError: diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 893644be23a0e..b4b5de3945854 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -57,15 +57,16 @@ from pandas.core import nanops from pandas.core.algorithms import checked_add_with_arr -from pandas.core.arrays import ( - IntegerArray, - datetimelike as dtl, -) -from pandas.core.arrays._ranges import generate_regular_range import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.ops.common import unpack_zerodim_and_defer +from . import ( + IntegerArray, + datetimelike as dtl, +) +from ._ranges import generate_regular_range + def _field_accessor(name: str, alias: str, docstring: str): def f(self) -> np.ndarray: @@ -432,7 +433,7 @@ def _add_period(self, other: Period): Add a Period object. """ # We will wrap in a PeriodArray and defer to the reversed operation - from pandas.core.arrays.period import PeriodArray + from .period import PeriodArray i8vals = np.broadcast_to(other.ordinal, self.shape) oth = PeriodArray(i8vals, freq=other.freq) @@ -444,7 +445,7 @@ def _add_datetime_arraylike(self, other): """ if isinstance(other, np.ndarray): # At this point we have already checked that dtype is datetime64 - from pandas.core.arrays import DatetimeArray + from . import DatetimeArray other = DatetimeArray(other) @@ -453,7 +454,7 @@ def _add_datetime_arraylike(self, other): def _add_datetimelike_scalar(self, other): # adding a timedeltaindex to a datetimelike - from pandas.core.arrays import DatetimeArray + from . import DatetimeArray assert other is not NaT other = Timestamp(other) diff --git a/pandas/core/base.py b/pandas/core/base.py index fd40e0467720d..1f22816fde22e 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -32,35 +32,35 @@ doc, ) -from pandas.core.dtypes.common import ( +import pandas.core.nanops as nanops + +from . import algorithms +from .accessor import DirNamesMixin +from .algorithms import ( + duplicated, + unique1d, + value_counts, +) +from .arraylike import OpsMixin +from .arrays import ExtensionArray +from .construction import create_series_with_explicit_dtype +from .dtypes.common import ( is_categorical_dtype, is_dict_like, is_extension_array_dtype, is_object_dtype, is_scalar, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCDataFrame, ABCIndex, ABCSeries, ) -from pandas.core.dtypes.missing import ( +from .dtypes.missing import ( isna, remove_na_arraylike, ) -from pandas.core import algorithms -from pandas.core.accessor import DirNamesMixin -from pandas.core.algorithms import ( - duplicated, - unique1d, - value_counts, -) -from pandas.core.arraylike import OpsMixin -from pandas.core.arrays import ExtensionArray -from pandas.core.construction import create_series_with_explicit_dtype -import pandas.core.nanops as nanops - if TYPE_CHECKING: from pandas import Categorical diff --git a/pandas/core/common.py b/pandas/core/common.py index 50aed70bf275d..3b7f441e25240 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -36,20 +36,20 @@ ) from pandas.compat import np_version_under1p18 -from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike -from pandas.core.dtypes.common import ( +from .dtypes.cast import construct_1d_object_array_from_listlike +from .dtypes.common import ( is_array_like, is_bool_dtype, is_extension_array_dtype, is_integer, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCExtensionArray, ABCIndex, ABCSeries, ) -from pandas.core.dtypes.inference import iterable_not_string -from pandas.core.dtypes.missing import ( # noqa +from .dtypes.inference import iterable_not_string +from .dtypes.missing import ( # noqa isna, isnull, notnull, diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 94724d559e501..39e40714559e0 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -30,7 +30,8 @@ from pandas.core.base import PandasObject import pandas.core.common as com -from pandas.core.computation.common import result_type_many + +from .common import result_type_many if TYPE_CHECKING: from pandas.core.indexes.api import Index diff --git a/pandas/core/computation/api.py b/pandas/core/computation/api.py index 31e8a4873b0ad..8234dc7bd782b 100644 --- a/pandas/core/computation/api.py +++ b/pandas/core/computation/api.py @@ -1,3 +1,3 @@ # flake8: noqa -from pandas.core.computation.eval import eval +from .eval import eval diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py index 5b2dbed7af6ea..c1b6ae6e801b0 100644 --- a/pandas/core/computation/engines.py +++ b/pandas/core/computation/engines.py @@ -8,17 +8,17 @@ Type, ) -from pandas.core.computation.align import ( +import pandas.io.formats.printing as printing + +from .align import ( align_terms, reconstruct_object, ) -from pandas.core.computation.ops import ( +from .ops import ( MATHOPS, REDUCTIONS, ) -import pandas.io.formats.printing as printing - _ne_builtins = frozenset(MATHOPS + REDUCTIONS) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 51fcbb02fd926..f1fa1c020f794 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -9,15 +9,15 @@ from pandas._libs.lib import no_default from pandas.util._validators import validate_bool_kwarg -from pandas.core.computation.engines import ENGINES -from pandas.core.computation.expr import ( +from pandas.io.formats.printing import pprint_thing + +from .engines import ENGINES +from .expr import ( PARSERS, Expr, ) -from pandas.core.computation.parsing import tokenize_string -from pandas.core.computation.scope import ensure_scope - -from pandas.io.formats.printing import pprint_thing +from .parsing import tokenize_string +from .scope import ensure_scope def _check_engine(engine: Optional[str]) -> str: @@ -41,7 +41,7 @@ def _check_engine(engine: Optional[str]) -> str: str Engine name. """ - from pandas.core.computation.check import NUMEXPR_INSTALLED + from .check import NUMEXPR_INSTALLED if engine is None: engine = "numexpr" if NUMEXPR_INSTALLED else "python" diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 02660539f4981..097556b2d4475 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -23,7 +23,10 @@ from pandas.compat import PY39 import pandas.core.common as com -from pandas.core.computation.ops import ( + +import pandas.io.formats.printing as printing + +from .ops import ( ARITH_OPS_SYMS, BOOL_OPS_SYMS, CMP_OPS_SYMS, @@ -41,13 +44,11 @@ UndefinedVariableError, is_term, ) -from pandas.core.computation.parsing import ( +from .parsing import ( clean_backtick_quoted_toks, tokenize_string, ) -from pandas.core.computation.scope import Scope - -import pandas.io.formats.printing as printing +from .scope import Scope def _rewrite_assign(tok: Tuple[int, str]) -> Tuple[int, str]: diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 05736578b6337..2d2a920e829b3 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -21,9 +21,10 @@ from pandas.core.dtypes.generic import ABCDataFrame -from pandas.core.computation.check import NUMEXPR_INSTALLED from pandas.core.ops import roperator +from .check import NUMEXPR_INSTALLED + if NUMEXPR_INSTALLED: import numexpr as ne diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 2f7623060e7dc..d0d73eb780f64 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -25,17 +25,18 @@ ) import pandas.core.common as com -from pandas.core.computation.common import ( - ensure_decoded, - result_type_many, -) -from pandas.core.computation.scope import DEFAULT_GLOBALS from pandas.io.formats.printing import ( pprint_thing, pprint_thing_encoded, ) +from .common import ( + ensure_decoded, + result_type_many, +) +from .scope import DEFAULT_GLOBALS + REDUCTIONS = ("sum", "prod") _unary_math_ops = ( @@ -457,7 +458,7 @@ def evaluate(self, env, engine: str, parser, term_type, eval_in_python): if self.op in eval_in_python: res = self.func(left.value, right.value) else: - from pandas.core.computation.eval import eval + from .eval import eval res = eval(self, local_dict=env, engine=engine, parser=parser) @@ -618,7 +619,7 @@ def __repr__(self) -> str: class FuncNode: def __init__(self, name: str): - from pandas.core.computation.check import ( + from .check import ( NUMEXPR_INSTALLED, NUMEXPR_VERSION, ) diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 5e7fdb8dc9c7d..d7823cc136199 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -21,17 +21,6 @@ from pandas.core.dtypes.common import is_list_like import pandas.core.common as com -from pandas.core.computation import ( - expr, - ops, - scope as _scope, -) -from pandas.core.computation.common import ensure_decoded -from pandas.core.computation.expr import BaseExprVisitor -from pandas.core.computation.ops import ( - UndefinedVariableError, - is_term, -) from pandas.core.construction import extract_array from pandas.core.indexes.base import Index @@ -40,6 +29,18 @@ pprint_thing_encoded, ) +from . import ( + expr, + ops, + scope as _scope, +) +from .common import ensure_decoded +from .expr import BaseExprVisitor +from .ops import ( + UndefinedVariableError, + is_term, +) + class PyTablesScope(_scope.Scope): __slots__ = ("queryables",) diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 71d725051977f..4e0be018e5a83 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -209,7 +209,7 @@ def resolve(self, key: str, is_local: bool): return self.temps[key] except KeyError as err: # runtime import because ops imports from scope - from pandas.core.computation.ops import UndefinedVariableError + from .ops import UndefinedVariableError raise UndefinedVariableError(key, is_local) from err diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 56ef1ea28ed1b..9e862e2cf1c3d 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -33,7 +33,7 @@ def use_bottleneck_cb(key): - from pandas.core import nanops + from . import nanops nanops.set_use_bottleneck(cf.get_option(key)) @@ -47,7 +47,7 @@ def use_bottleneck_cb(key): def use_numexpr_cb(key): - from pandas.core.computation import expressions + from .computation import expressions expressions.set_use_numexpr(cf.get_option(key)) @@ -61,7 +61,7 @@ def use_numexpr_cb(key): def use_numba_cb(key): - from pandas.core.util import numba_ + from .util import numba_ numba_.set_use_numba(cf.get_option(key)) @@ -473,7 +473,7 @@ def _deprecate_negative_int_max_colwidth(key): def use_inf_as_na_cb(key): - from pandas.core.dtypes.missing import _use_inf_as_na + from .dtypes.missing import _use_inf_as_na _use_inf_as_na(key) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index dd75473da6d78..f6c9a5c84a779 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -31,11 +31,13 @@ DtypeObj, ) -from pandas.core.dtypes.base import ( +import pandas.core.common as com + +from .dtypes.base import ( ExtensionDtype, registry, ) -from pandas.core.dtypes.cast import ( +from .dtypes.cast import ( construct_1d_arraylike_from_scalar, construct_1d_ndarray_preserving_na, construct_1d_object_array_from_listlike, @@ -45,7 +47,7 @@ maybe_convert_platform, maybe_upcast, ) -from pandas.core.dtypes.common import ( +from .dtypes.common import ( is_datetime64_ns_dtype, is_extension_array_dtype, is_float_dtype, @@ -56,15 +58,13 @@ is_string_dtype, is_timedelta64_ns_dtype, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCExtensionArray, ABCIndex, ABCPandasArray, ABCSeries, ) -from pandas.core.dtypes.missing import isna - -import pandas.core.common as com +from .dtypes.missing import isna if TYPE_CHECKING: from pandas import ( @@ -286,7 +286,7 @@ def array( ... ValueError: Cannot pass scalar '1' to 'pandas.array'. """ - from pandas.core.arrays import ( + from .arrays import ( BooleanArray, DatetimeArray, FloatingArray, @@ -425,12 +425,12 @@ def ensure_wrapped_if_datetimelike(arr): """ if isinstance(arr, np.ndarray): if arr.dtype.kind == "M": - from pandas.core.arrays import DatetimeArray + from .arrays import DatetimeArray return DatetimeArray._from_sequence(arr) elif arr.dtype.kind == "m": - from pandas.core.arrays import TimedeltaArray + from .arrays import TimedeltaArray return TimedeltaArray._from_sequence(arr) @@ -706,7 +706,7 @@ def create_series_with_explicit_dtype( ------- Series """ - from pandas.core.series import Series + from .series import Series if is_empty_data(data) and dtype is None: dtype = dtype_if_empty diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 3a872c6202e04..03c5c424696e8 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -30,16 +30,15 @@ ) from pandas.util._validators import validate_percentile -from pandas.core.dtypes.common import ( +from pandas.io.formats.format import format_percentiles + +from .dtypes.common import ( is_bool_dtype, is_datetime64_any_dtype, is_numeric_dtype, is_timedelta64_dtype, ) - -from pandas.core.reshape.concat import concat - -from pandas.io.formats.format import format_percentiles +from .reshape.concat import concat if TYPE_CHECKING: from pandas import ( diff --git a/pandas/core/dtypes/api.py b/pandas/core/dtypes/api.py index 051affd0af1f9..cb0912cbcf880 100644 --- a/pandas/core/dtypes/api.py +++ b/pandas/core/dtypes/api.py @@ -1,6 +1,6 @@ # flake8: noqa -from pandas.core.dtypes.common import ( +from .common import ( is_array_like, is_bool, is_bool_dtype, diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index d83405803753a..d86f2a6405032 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -19,7 +19,7 @@ from pandas._typing import DtypeObj from pandas.errors import AbstractMethodError -from pandas.core.dtypes.generic import ( +from .generic import ( ABCDataFrame, ABCIndex, ABCSeries, diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 669bfe08d42b0..e53d02c9322a1 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -53,7 +53,7 @@ from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg -from pandas.core.dtypes.common import ( +from .common import ( DT64NS_DTYPE, POSSIBLY_CAST_DTYPES, TD64NS_DTYPE, @@ -87,20 +87,20 @@ is_timedelta64_ns_dtype, is_unsigned_integer_dtype, ) -from pandas.core.dtypes.dtypes import ( +from .dtypes import ( DatetimeTZDtype, ExtensionDtype, IntervalDtype, PeriodDtype, ) -from pandas.core.dtypes.generic import ( +from .generic import ( ABCDataFrame, ABCExtensionArray, ABCIndex, ABCSeries, ) -from pandas.core.dtypes.inference import is_list_like -from pandas.core.dtypes.missing import ( +from .inference import is_list_like +from .missing import ( is_valid_na_for_dtype, isna, na_value_for_dtype, diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 0966d0b93cc25..cb3885a3b6952 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -23,19 +23,19 @@ Optional, ) -from pandas.core.dtypes.base import registry -from pandas.core.dtypes.dtypes import ( +from .base import registry +from .dtypes import ( CategoricalDtype, DatetimeTZDtype, ExtensionDtype, IntervalDtype, PeriodDtype, ) -from pandas.core.dtypes.generic import ( +from .generic import ( ABCCategorical, ABCIndex, ) -from pandas.core.dtypes.inference import ( # noqa:F401 +from .inference import ( # noqa:F401 is_array_like, is_bool, is_complex, diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 42ac786ff315e..372c563781b04 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -10,25 +10,25 @@ DtypeObj, ) -from pandas.core.dtypes.cast import find_common_type -from pandas.core.dtypes.common import ( +from pandas.core.arrays import ExtensionArray +from pandas.core.arrays.sparse import SparseArray +from pandas.core.construction import ( + array, + ensure_wrapped_if_datetimelike, +) + +from .cast import find_common_type +from .common import ( is_categorical_dtype, is_dtype_equal, is_extension_array_dtype, is_sparse, ) -from pandas.core.dtypes.generic import ( +from .generic import ( ABCCategoricalIndex, ABCSeries, ) -from pandas.core.arrays import ExtensionArray -from pandas.core.arrays.sparse import SparseArray -from pandas.core.construction import ( - array, - ensure_wrapped_if_datetimelike, -) - def _cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike: """ diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index da3a9269cf2c4..ed2fa2f3d3147 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -38,15 +38,15 @@ Ordered, ) -from pandas.core.dtypes.base import ( +from .base import ( ExtensionDtype, register_extension_dtype, ) -from pandas.core.dtypes.generic import ( +from .generic import ( ABCCategoricalIndex, ABCIndex, ) -from pandas.core.dtypes.inference import ( +from .inference import ( is_bool, is_list_like, ) @@ -591,7 +591,7 @@ def ordered(self) -> Ordered: @property def _is_boolean(self) -> bool: - from pandas.core.dtypes.common import is_bool_dtype + from .common import is_bool_dtype return is_bool_dtype(self.categories) @@ -621,7 +621,7 @@ def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: x.categories.dtype if isinstance(x, CategoricalDtype) else x for x in dtypes ] # TODO should categorical always give an answer? - from pandas.core.dtypes.cast import find_common_type + from .cast import find_common_type return find_common_type(non_cat_dtypes) @@ -1046,7 +1046,7 @@ class IntervalDtype(PandasExtensionDtype): _cache: Dict[str_type, PandasExtensionDtype] = {} def __new__(cls, subtype=None, closed: Optional[str_type] = None): - from pandas.core.dtypes.common import ( + from .common import ( is_string_dtype, pandas_dtype, ) @@ -1181,7 +1181,7 @@ def __eq__(self, other: Any) -> bool: elif self.closed != other.closed: return False else: - from pandas.core.dtypes.common import is_dtype_equal + from .common import is_dtype_equal return is_dtype_equal(self.subtype, other.subtype) @@ -1246,7 +1246,7 @@ def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: if not all(cast("IntervalDtype", x).closed == closed for x in dtypes): return np.dtype(object) - from pandas.core.dtypes.cast import find_common_type + from .cast import find_common_type common = find_common_type([cast("IntervalDtype", x).subtype for x in dtypes]) if common == object: diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 3279007fcebe1..dca5b45ef9811 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -19,7 +19,7 @@ DtypeObj, ) -from pandas.core.dtypes.common import ( +from .common import ( DT64NS_DTYPE, TD64NS_DTYPE, ensure_object, @@ -37,14 +37,14 @@ is_string_like_dtype, needs_i8_conversion, ) -from pandas.core.dtypes.generic import ( +from .generic import ( ABCDataFrame, ABCExtensionArray, ABCIndex, ABCMultiIndex, ABCSeries, ) -from pandas.core.dtypes.inference import is_list_like +from .inference import is_list_like isposinf_scalar = libmissing.isposinf_scalar isneginf_scalar = libmissing.isneginf_scalar diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3fe330f659513..d7ccc1d17aaea 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -89,7 +89,38 @@ validate_percentile, ) -from pandas.core.dtypes.cast import ( +from pandas.io.common import get_handle +from pandas.io.formats import ( + console, + format as fmt, +) +from pandas.io.formats.info import ( + BaseInfo, + DataFrameInfo, +) +import pandas.plotting + +from . import ( + algorithms, + common as com, + generic, + nanops, + ops, +) +from .accessor import CachedAccessor +from .aggregation import ( + reconstruct_func, + relabel_result, + transform, +) +from .arraylike import OpsMixin +from .arrays import ExtensionArray +from .arrays.sparse import SparseFrameAccessor +from .construction import ( + extract_array, + sanitize_masked_array, +) +from .dtypes.cast import ( construct_1d_arraylike_from_scalar, construct_2d_arraylike_from_scalar, find_common_type, @@ -101,7 +132,7 @@ maybe_infer_to_datetimelike, validate_numeric_casting, ) -from pandas.core.dtypes.common import ( +from .dtypes.common import ( ensure_int64, ensure_platform_int, infer_dtype_from_object, @@ -123,57 +154,36 @@ is_sequence, pandas_dtype, ) -from pandas.core.dtypes.missing import ( +from .dtypes.missing import ( isna, notna, ) - -from pandas.core import ( - algorithms, - common as com, - generic, - nanops, - ops, -) -from pandas.core.accessor import CachedAccessor -from pandas.core.aggregation import ( - reconstruct_func, - relabel_result, - transform, -) -from pandas.core.arraylike import OpsMixin -from pandas.core.arrays import ExtensionArray -from pandas.core.arrays.sparse import SparseFrameAccessor -from pandas.core.construction import ( - extract_array, - sanitize_masked_array, -) -from pandas.core.generic import ( +from .generic import ( NDFrame, _shared_docs, ) -from pandas.core.indexers import check_key_length -from pandas.core.indexes import base as ibase -from pandas.core.indexes.api import ( +from .indexers import check_key_length +from .indexes import base as ibase +from .indexes.api import ( DatetimeIndex, Index, PeriodIndex, ensure_index, ensure_index_from_sequences, ) -from pandas.core.indexes.multi import ( +from .indexes.multi import ( MultiIndex, maybe_droplevels, ) -from pandas.core.indexing import ( +from .indexing import ( check_bool_indexer, convert_to_index_sliceable, ) -from pandas.core.internals import ( +from .internals import ( ArrayManager, BlockManager, ) -from pandas.core.internals.construction import ( +from .internals.construction import ( arrays_to_mgr, dataclasses_to_dicts, init_dict, @@ -186,25 +196,14 @@ to_arrays, treat_as_nested, ) -from pandas.core.reshape.melt import melt -from pandas.core.series import Series -from pandas.core.sorting import ( +from .reshape.melt import melt +from .series import Series +from .sorting import ( get_group_index, lexsort_indexer, nargsort, ) -from pandas.io.common import get_handle -from pandas.io.formats import ( - console, - format as fmt, -) -from pandas.io.formats.info import ( - BaseInfo, - DataFrameInfo, -) -import pandas.plotting - if TYPE_CHECKING: from typing import Literal @@ -213,11 +212,11 @@ TimestampConvertibleTypes, ) - from pandas.core.groupby.generic import DataFrameGroupBy - from pandas.core.resample import Resampler - from pandas.io.formats.style import Styler + from .groupby.generic import DataFrameGroupBy + from .resample import Resampler + # --------------------------------------------------------------------- # Docstring templates @@ -3708,7 +3707,7 @@ def eval(self, expr: str, inplace: bool = False, **kwargs): 3 4 4 8 0 4 5 2 7 3 """ - from pandas.core.computation.eval import eval as _eval + from .computation.eval import eval as _eval inplace = validate_bool_kwarg(inplace, "inplace") resolvers = kwargs.pop("resolvers", None) @@ -6851,7 +6850,7 @@ def groupby( observed: bool = False, dropna: bool = True, ) -> DataFrameGroupBy: - from pandas.core.groupby.generic import DataFrameGroupBy + from .groupby.generic import DataFrameGroupBy if squeeze is not no_default: warnings.warn( @@ -7029,7 +7028,7 @@ def groupby( @Substitution("") @Appender(_shared_docs["pivot"]) def pivot(self, index=None, columns=None, values=None) -> DataFrame: - from pandas.core.reshape.pivot import pivot + from .reshape.pivot import pivot return pivot(self, index=index, columns=columns, values=values) @@ -7181,7 +7180,7 @@ def pivot_table( margins_name="All", observed=False, ) -> DataFrame: - from pandas.core.reshape.pivot import pivot_table + from .reshape.pivot import pivot_table return pivot_table( self, @@ -7357,7 +7356,7 @@ def stack(self, level: Level = -1, dropna: bool = True): dog kg NaN 2.0 m 3.0 NaN """ - from pandas.core.reshape.reshape import ( + from .reshape.reshape import ( stack, stack_multiple, ) @@ -7505,7 +7504,7 @@ def unstack(self, level=-1, fill_value=None): b 4.0 dtype: float64 """ - from pandas.core.reshape.reshape import unstack + from .reshape.reshape import unstack result = unstack(self, level, fill_value) @@ -7758,7 +7757,7 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): return result def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): - from pandas.core.apply import frame_apply + from .apply import frame_apply op = frame_apply( self if axis == 0 else self.T, @@ -7936,7 +7935,7 @@ def apply( 1 1 2 2 1 2 """ - from pandas.core.apply import frame_apply + from .apply import frame_apply op = frame_apply( self, @@ -8160,7 +8159,7 @@ def append( if (self.columns.get_indexer(other.columns) >= 0).all(): other = other.reindex(columns=self.columns) - from pandas.core.reshape.concat import concat + from .reshape.concat import concat if isinstance(other, (list, tuple)): to_concat = [self, *other] @@ -8314,8 +8313,8 @@ def _join_compat( rsuffix: str = "", sort: bool = False, ): - from pandas.core.reshape.concat import concat - from pandas.core.reshape.merge import merge + from .reshape.concat import concat + from .reshape.merge import merge if isinstance(other, Series): if other.name is None: @@ -8390,7 +8389,7 @@ def merge( indicator: bool = False, validate: Optional[str] = None, ) -> DataFrame: - from pandas.core.reshape.merge import merge + from .reshape.merge import merge return merge( self, @@ -8485,7 +8484,7 @@ def round(self, decimals=0, *args, **kwargs) -> DataFrame: 2 0.7 0.0 3 0.2 0.0 """ - from pandas.core.reshape.concat import concat + from .reshape.concat import concat def _dict_round(df, decimals): for col, vals in df.items(): @@ -9673,7 +9672,7 @@ def isin(self, values) -> DataFrame: dog False False """ if isinstance(values, dict): - from pandas.core.reshape.concat import concat + from .reshape.concat import concat values = collections.defaultdict(list, values) return concat( diff --git a/pandas/core/generic.py b/pandas/core/generic.py index a32ae7090ef8b..929c01b5b1804 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -75,7 +75,33 @@ validate_fillna_kwargs, ) -from pandas.core.dtypes.common import ( +import pandas.core.algorithms as algos +import pandas.core.common as com + +from pandas.io.formats import format as fmt +from pandas.io.formats.format import ( + DataFrameFormatter, + DataFrameRenderer, +) +from pandas.io.formats.printing import pprint_thing + +from . import ( + arraylike, + indexing, + missing, + nanops, +) +from .arrays import ExtensionArray +from .base import ( + PandasObject, + SelectionMixin, +) +from .construction import ( + create_series_with_explicit_dtype, + extract_array, +) +from .describe import describe_ndframe +from .dtypes.common import ( ensure_int64, ensure_object, ensure_str, @@ -96,37 +122,18 @@ is_timedelta64_dtype, pandas_dtype, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCDataFrame, ABCSeries, ) -from pandas.core.dtypes.inference import is_hashable -from pandas.core.dtypes.missing import ( +from .dtypes.inference import is_hashable +from .dtypes.missing import ( isna, notna, ) - -from pandas.core import ( - arraylike, - indexing, - missing, - nanops, -) -import pandas.core.algorithms as algos -from pandas.core.arrays import ExtensionArray -from pandas.core.base import ( - PandasObject, - SelectionMixin, -) -import pandas.core.common as com -from pandas.core.construction import ( - create_series_with_explicit_dtype, - extract_array, -) -from pandas.core.describe import describe_ndframe -from pandas.core.flags import Flags -from pandas.core.indexes import base as ibase -from pandas.core.indexes.api import ( +from .flags import Flags +from .indexes import base as ibase +from .indexes.api import ( DatetimeIndex, Index, MultiIndex, @@ -134,36 +141,29 @@ RangeIndex, ensure_index, ) -from pandas.core.internals import ( +from .internals import ( ArrayManager, BlockManager, ) -from pandas.core.missing import find_valid_index -from pandas.core.ops import align_method_FRAME -from pandas.core.reshape.concat import concat -from pandas.core.shared_docs import _shared_docs -from pandas.core.sorting import get_indexer_indexer -from pandas.core.window import ( +from .missing import find_valid_index +from .ops import align_method_FRAME +from .reshape.concat import concat +from .shared_docs import _shared_docs +from .sorting import get_indexer_indexer +from .window import ( Expanding, ExponentialMovingWindow, Rolling, Window, ) -from pandas.io.formats import format as fmt -from pandas.io.formats.format import ( - DataFrameFormatter, - DataFrameRenderer, -) -from pandas.io.formats.printing import pprint_thing - if TYPE_CHECKING: from pandas._libs.tslibs import BaseOffset - from pandas.core.frame import DataFrame - from pandas.core.resample import Resampler - from pandas.core.series import Series - from pandas.core.window.indexers import BaseIndexer + from .frame import DataFrame + from .resample import Resampler + from .series import Series + from .window.indexers import BaseIndexer # goal is to be able to define the docs close to function, while still being # able to share @@ -552,7 +552,7 @@ def _get_axis_resolvers(self, axis: str) -> Dict[str, Union[Series, MultiIndex]] @final def _get_index_resolvers(self) -> Dict[Hashable, Union[Series, MultiIndex]]: - from pandas.core.computation.parsing import clean_column_name + from .computation.parsing import clean_column_name d: Dict[str, Union[Series, MultiIndex]] = {} for axis_name in self._AXIS_ORDERS: @@ -569,7 +569,7 @@ def _get_cleaned_column_resolvers(self) -> Dict[Hashable, Series]: be referred to by backtick quoting. Used in :meth:`DataFrame.eval`. """ - from pandas.core.computation.parsing import clean_column_name + from .computation.parsing import clean_column_name if isinstance(self, ABCSeries): return {clean_column_name(self.name): self} @@ -7615,7 +7615,7 @@ def asfreq( 2000-01-01 00:02:30 3.0 2000-01-01 00:03:00 3.0 """ - from pandas.core.resample import asfreq + from .resample import asfreq return asfreq( self, @@ -8182,7 +8182,7 @@ def resample( 2000-10-02 00:41:00 24 Freq: 17T, dtype: int64 """ - from pandas.core.resample import get_resampler + from .resample import get_resampler axis = self._get_axis_number(axis) return get_resampler( @@ -8470,7 +8470,7 @@ def compare( keep_shape: bool_t = False, keep_equal: bool_t = False, ): - from pandas.core.reshape.concat import concat + from .reshape.concat import concat if type(self) is not type(other): cls_self, cls_other = type(self).__name__, type(other).__name__ @@ -9533,7 +9533,7 @@ def truncate( # if we have a date index, convert to dates, otherwise # treat like a slice if ax._is_all_dates: - from pandas.core.tools.datetimes import to_datetime + from .tools.datetimes import to_datetime before = to_datetime(before) after = to_datetime(after) diff --git a/pandas/core/groupby/__init__.py b/pandas/core/groupby/__init__.py index 8248f378e2c1a..9ea010e6e3831 100644 --- a/pandas/core/groupby/__init__.py +++ b/pandas/core/groupby/__init__.py @@ -1,10 +1,10 @@ -from pandas.core.groupby.generic import ( +from .generic import ( DataFrameGroupBy, NamedAgg, SeriesGroupBy, ) -from pandas.core.groupby.groupby import GroupBy -from pandas.core.groupby.grouper import Grouper +from .groupby import GroupBy +from .grouper import Grouper __all__ = [ "DataFrameGroupBy", diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index c1a277925de2a..e3f3b97105330 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -94,15 +94,6 @@ from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame -from pandas.core.groupby import base -from pandas.core.groupby.groupby import ( - GroupBy, - _agg_template, - _apply_docs, - _transform_template, - get_groupby, - group_selection_context, -) from pandas.core.indexes.api import ( Index, MultiIndex, @@ -115,6 +106,16 @@ from pandas.plotting import boxplot_frame_groupby +from . import base +from .groupby import ( + GroupBy, + _agg_template, + _apply_docs, + _transform_template, + get_groupby, + group_selection_context, +) + if TYPE_CHECKING: from pandas.core.internals import Block diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index bc277bf67614d..1634b5d540c97 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -94,11 +94,6 @@ class providing the base-class of operations. import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame -from pandas.core.groupby import ( - base, - numba_, - ops, -) from pandas.core.indexes.api import ( CategoricalIndex, Index, @@ -108,6 +103,12 @@ class providing the base-class of operations. from pandas.core.sorting import get_group_index_sorter from pandas.core.util.numba_ import NUMBA_FUNC_CACHE +from . import ( + base, + numba_, + ops, +) + _common_see_also = """ See Also -------- @@ -589,7 +590,7 @@ def __init__( self.dropna = dropna if grouper is None: - from pandas.core.groupby.grouper import get_grouper + from .grouper import get_grouper grouper, exclusions, obj = get_grouper( obj, @@ -2179,7 +2180,7 @@ def nth(self, n: Union[int, List[int]], dropna: Optional[str] = None) -> DataFra # create a grouper with the original parameters, but on dropped # object - from pandas.core.groupby.grouper import get_grouper + from .grouper import get_grouper grouper, _, _ = get_grouper( dropped, @@ -3111,11 +3112,11 @@ def get_groupby( klass: Type[GroupBy] if isinstance(obj, Series): - from pandas.core.groupby.generic import SeriesGroupBy + from .generic import SeriesGroupBy klass = SeriesGroupBy elif isinstance(obj, DataFrame): - from pandas.core.groupby.generic import DataFrameGroupBy + from .generic import DataFrameGroupBy klass = DataFrameGroupBy else: diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 89becb880c519..979678b6d2ed6 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -38,11 +38,6 @@ ) import pandas.core.common as com from pandas.core.frame import DataFrame -from pandas.core.groupby import ops -from pandas.core.groupby.categorical import ( - recode_for_groupby, - recode_from_groupby, -) from pandas.core.indexes.api import ( CategoricalIndex, Index, @@ -52,6 +47,12 @@ from pandas.io.formats.printing import pprint_thing +from . import ops +from .categorical import ( + recode_for_groupby, + recode_from_groupby, +) + class Grouper: """ diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 00cb65fff3803..cf5520e4f782d 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -75,10 +75,6 @@ import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame -from pandas.core.groupby import ( - base, - grouper, -) from pandas.core.indexes.api import ( Index, MultiIndex, @@ -94,6 +90,11 @@ get_indexer_dict, ) +from . import ( + base, + grouper, +) + class BaseGrouper: """ diff --git a/pandas/core/index.py b/pandas/core/index.py index 44f434e038a4b..3a5923e5a6cb8 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1,6 +1,6 @@ import warnings -from pandas.core.indexes.api import ( # noqa:F401 +from .indexes.api import ( # noqa:F401 CategoricalIndex, DatetimeIndex, Float64Index, @@ -19,7 +19,7 @@ ensure_index_from_sequences, get_objs_combined_axis, ) -from pandas.core.indexes.multi import sparsify_labels # noqa:F401 +from .indexes.multi import sparsify_labels # noqa:F401 # GH#30193 warnings.warn( diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py index 0649cc3efc153..02f4f778ad2cf 100644 --- a/pandas/core/indexers.py +++ b/pandas/core/indexers.py @@ -14,7 +14,7 @@ ArrayLike, ) -from pandas.core.dtypes.common import ( +from .dtypes.common import ( is_array_like, is_bool_dtype, is_extension_array_dtype, @@ -22,14 +22,14 @@ is_integer_dtype, is_list_like, ) -from pandas.core.dtypes.generic import ( +from .dtypes.generic import ( ABCIndex, ABCSeries, ) if TYPE_CHECKING: - from pandas.core.frame import DataFrame - from pandas.core.indexes.base import Index + from .frame import DataFrame + from .indexes.base import Index # ----------------------------------------------------------- # Indexer Identification @@ -514,7 +514,7 @@ def check_array_indexer(array: AnyArrayLike, indexer: Any) -> Any: ... IndexError: arrays used as indices must be of integer or boolean type """ - from pandas.core.construction import array as pd_array + from .construction import array as pd_array # whatever is not an array-like is returned as-is (possible valid array # indexers that are not array-like: integer, slice, Ellipsis, None) diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index 017f58bff03e9..f784434fe77c0 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -32,8 +32,9 @@ NoNewAttributesMixin, PandasObject, ) -from pandas.core.indexes.datetimes import DatetimeIndex -from pandas.core.indexes.timedeltas import TimedeltaIndex + +from .datetimes import DatetimeIndex +from .timedeltas import TimedeltaIndex if TYPE_CHECKING: from pandas import Series diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 5656323b82fb7..39223e3e8cd4d 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -10,26 +10,26 @@ ) from pandas.errors import InvalidIndexError -from pandas.core.indexes.base import ( +from .base import ( Index, _new_Index, ensure_index, ensure_index_from_sequences, get_unanimous_names, ) -from pandas.core.indexes.category import CategoricalIndex -from pandas.core.indexes.datetimes import DatetimeIndex -from pandas.core.indexes.interval import IntervalIndex -from pandas.core.indexes.multi import MultiIndex -from pandas.core.indexes.numeric import ( +from .category import CategoricalIndex +from .datetimes import DatetimeIndex +from .interval import IntervalIndex +from .multi import MultiIndex +from .numeric import ( Float64Index, Int64Index, NumericIndex, UInt64Index, ) -from pandas.core.indexes.period import PeriodIndex -from pandas.core.indexes.range import RangeIndex -from pandas.core.indexes.timedeltas import TimedeltaIndex +from .period import PeriodIndex +from .range import RangeIndex +from .timedeltas import TimedeltaIndex _sort_msg = textwrap.dedent( """\ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 71095b8f4113a..74d115bccb55c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -141,7 +141,6 @@ import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import deprecate_ndim_indexing -from pandas.core.indexes.frozen import FrozenList from pandas.core.ops import get_op_result_name from pandas.core.ops.invalid import make_invalid_op from pandas.core.sorting import ( @@ -158,6 +157,8 @@ pprint_thing, ) +from .frozen import FrozenList + if TYPE_CHECKING: from pandas import ( CategoricalIndex, @@ -166,7 +167,8 @@ RangeIndex, Series, ) - from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin + + from .datetimelike import DatetimeIndexOpsMixin __all__ = ["Index"] @@ -204,7 +206,7 @@ def _new_Index(cls, d): # required for backward compat, because PI can't be instantiated with # ordinals through __new__ GH #13277 if issubclass(cls, ABCPeriodIndex): - from pandas.core.indexes.period import _new_PeriodIndex + from .period import _new_PeriodIndex return _new_PeriodIndex(cls, **d) @@ -333,7 +335,8 @@ def __new__( ) from pandas.core.arrays import PandasArray - from pandas.core.indexes.range import RangeIndex + + from .range import RangeIndex name = maybe_extract_name(name, data, cls) @@ -432,7 +435,7 @@ def __new__( if data and all(isinstance(e, tuple) for e in data): # we must be all tuples, otherwise don't construct # 10697 - from pandas.core.indexes.multi import MultiIndex + from .multi import MultiIndex return MultiIndex.from_tuples( data, names=name or kwargs.get("names") @@ -831,7 +834,7 @@ def astype(self, dtype, copy=True): return self.copy() if copy else self elif is_categorical_dtype(dtype): - from pandas.core.indexes.category import CategoricalIndex + from .category import CategoricalIndex return CategoricalIndex( self._values, name=self.name, dtype=dtype, copy=copy @@ -1821,7 +1824,7 @@ def _drop_level_numbers(self, levnums: List[int]): result._name = new_names[0] return result else: - from pandas.core.indexes.multi import MultiIndex + from .multi import MultiIndex return MultiIndex( levels=new_levels, @@ -3940,9 +3943,10 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False) @final def _join_multi(self, other, how, return_indexers=True): - from pandas.core.indexes.multi import MultiIndex from pandas.core.reshape.merge import restore_dropped_levels_multijoin + from .multi import MultiIndex + # figure out join names self_names_list = list(com.not_none(*self.names)) other_names_list = list(com.not_none(*other.names)) @@ -4058,7 +4062,7 @@ def _join_level( MultiIndex will not be changed; otherwise, it will tie out with `other`. """ - from pandas.core.indexes.multi import MultiIndex + from .multi import MultiIndex def _get_leaf_sorter(labels): """ @@ -5329,7 +5333,7 @@ def map(self, mapper, na_action=None): If the function returns a tuple with more than one element a MultiIndex will be returned. """ - from pandas.core.indexes.multi import MultiIndex + from .multi import MultiIndex new_values = super()._map_values(mapper, na_action=na_action) @@ -6067,7 +6071,7 @@ def ensure_index_from_sequences(sequences, names=None): -------- ensure_index """ - from pandas.core.indexes.multi import MultiIndex + from .multi import MultiIndex if len(sequences) == 1: if names is not None: @@ -6140,7 +6144,7 @@ def ensure_index( converted, all_arrays = lib.clean_index_list(index_like) if len(converted) > 0 and all_arrays: - from pandas.core.indexes.multi import MultiIndex + from .multi import MultiIndex return MultiIndex.from_arrays(converted) else: @@ -6198,7 +6202,7 @@ def _validate_join_method(method: str): def default_index(n: int) -> RangeIndex: - from pandas.core.indexes.range import RangeIndex + from .range import RangeIndex return RangeIndex(0, n, name=None) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 13c53dfafed4d..e48d5520247a3 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -39,12 +39,13 @@ ) from pandas.core.construction import extract_array import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import ( + +from .base import ( Index, _index_shared_docs, maybe_extract_name, ) -from pandas.core.indexes.extension import ( +from .extension import ( NDArrayBackedExtensionIndex, inherit_names, ) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index b2c67ae2f0a00..6bdeb102555a4 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -57,17 +57,18 @@ from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin import pandas.core.common as com import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import ( +from pandas.core.tools.timedeltas import to_timedelta + +from .base import ( Index, _index_shared_docs, ) -from pandas.core.indexes.extension import ( +from .extension import ( NDArrayBackedExtensionIndex, inherit_names, make_wrapped_arith_op, ) -from pandas.core.indexes.numeric import Int64Index -from pandas.core.tools.timedeltas import to_timedelta +from .numeric import Int64Index if TYPE_CHECKING: from pandas import CategoricalIndex diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 9ea43d083f5b3..ed2ef4815cd59 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -55,14 +55,15 @@ tz_to_dtype, ) import pandas.core.common as com -from pandas.core.indexes.base import ( +from pandas.core.tools.times import to_time + +from .base import ( Index, get_unanimous_names, maybe_extract_name, ) -from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin -from pandas.core.indexes.extension import inherit_names -from pandas.core.tools.times import to_time +from .datetimelike import DatetimeTimedeltaMixin +from .extension import inherit_names if TYPE_CHECKING: from pandas import ( @@ -286,21 +287,21 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise") -> DatetimeInd @doc(DatetimeArray.to_period) def to_period(self, freq=None) -> PeriodIndex: - from pandas.core.indexes.api import PeriodIndex + from .api import PeriodIndex arr = self._data.to_period(freq) return PeriodIndex._simple_new(arr, name=self.name) @doc(DatetimeArray.to_perioddelta) def to_perioddelta(self, freq) -> TimedeltaIndex: - from pandas.core.indexes.api import TimedeltaIndex + from .api import TimedeltaIndex arr = self._data.to_perioddelta(freq) return TimedeltaIndex._simple_new(arr, name=self.name) @doc(DatetimeArray.to_julian_date) def to_julian_date(self) -> Float64Index: - from pandas.core.indexes.api import Float64Index + from .api import Float64Index arr = self._data.to_julian_date() return Float64Index._simple_new(arr, name=self.name) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 4150ec745bd2e..a7d925eae9bf1 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -28,9 +28,10 @@ from pandas.core.arrays import ExtensionArray from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.indexers import deprecate_ndim_indexing -from pandas.core.indexes.base import Index from pandas.core.ops import get_op_result_name +from .base import Index + _T = TypeVar("_T", bound="NDArrayBackedExtensionIndex") diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c2fabfc332b23..67ce62a5cbad8 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -81,27 +81,28 @@ import pandas.core.common as com from pandas.core.indexers import is_valid_positional_slice import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import ( +from pandas.core.ops import get_op_result_name + +from .base import ( Index, _index_shared_docs, default_pprint, ensure_index, maybe_extract_name, ) -from pandas.core.indexes.datetimes import ( +from .datetimes import ( DatetimeIndex, date_range, ) -from pandas.core.indexes.extension import ( +from .extension import ( ExtensionIndex, inherit_names, ) -from pandas.core.indexes.multi import MultiIndex -from pandas.core.indexes.timedeltas import ( +from .multi import MultiIndex +from .timedeltas import ( TimedeltaIndex, timedelta_range, ) -from pandas.core.ops import get_op_result_name if TYPE_CHECKING: from pandas import CategoricalIndex diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7ef81b0947a22..1a7f76495fe51 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -74,14 +74,6 @@ from pandas.core.arrays.categorical import factorize_from_iterables import pandas.core.common as com import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import ( - Index, - _index_shared_docs, - ensure_index, - get_unanimous_names, -) -from pandas.core.indexes.frozen import FrozenList -from pandas.core.indexes.numeric import Int64Index from pandas.core.ops.invalid import make_invalid_op from pandas.core.sorting import ( get_group_index, @@ -95,6 +87,15 @@ pprint_thing, ) +from .base import ( + Index, + _index_shared_docs, + ensure_index, + get_unanimous_names, +) +from .frozen import FrozenList +from .numeric import Int64Index + if TYPE_CHECKING: from pandas import ( CategoricalIndex, diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 96c8c1ab9b69c..fc642959734b2 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -33,7 +33,8 @@ from pandas.core.dtypes.generic import ABCSeries import pandas.core.common as com -from pandas.core.indexes.base import ( + +from .base import ( Index, maybe_extract_name, ) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 0c5dbec2094e5..57a8f1436d579 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -51,14 +51,15 @@ ) import pandas.core.common as com import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import maybe_extract_name -from pandas.core.indexes.datetimelike import DatetimeIndexOpsMixin -from pandas.core.indexes.datetimes import ( + +from .base import maybe_extract_name +from .datetimelike import DatetimeIndexOpsMixin +from .datetimes import ( DatetimeIndex, Index, ) -from pandas.core.indexes.extension import inherit_names -from pandas.core.indexes.numeric import Int64Index +from .extension import inherit_names +from .numeric import Int64Index _index_doc_kwargs = dict(ibase._index_doc_kwargs) _index_doc_kwargs.update({"target_klass": "PeriodIndex or list of Periods"}) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index bd9a92a657991..cd3198949668d 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -40,12 +40,13 @@ import pandas.core.common as com from pandas.core.construction import extract_array import pandas.core.indexes.base as ibase -from pandas.core.indexes.base import maybe_extract_name -from pandas.core.indexes.numeric import ( +from pandas.core.ops.common import unpack_zerodim_and_defer + +from .base import maybe_extract_name +from .numeric import ( Float64Index, Int64Index, ) -from pandas.core.ops.common import unpack_zerodim_and_defer if TYPE_CHECKING: from pandas import Index diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index a23dd10bc3c0e..609b3e4eee80a 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -23,12 +23,13 @@ from pandas.core.arrays import datetimelike as dtl from pandas.core.arrays.timedeltas import TimedeltaArray import pandas.core.common as com -from pandas.core.indexes.base import ( + +from .base import ( Index, maybe_extract_name, ) -from pandas.core.indexes.datetimelike import DatetimeTimedeltaMixin -from pandas.core.indexes.extension import inherit_names +from .datetimelike import DatetimeTimedeltaMixin +from .extension import inherit_names @inherit_names( diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 7b4921080e2e1..d2845ee0d486b 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -24,7 +24,10 @@ ) from pandas.util._decorators import doc -from pandas.core.dtypes.common import ( +import pandas.core.common as com + +from .construction import array as pd_array +from .dtypes.common import ( is_array_like, is_bool_dtype, is_hashable, @@ -36,26 +39,23 @@ is_scalar, is_sequence, ) -from pandas.core.dtypes.concat import concat_compat -from pandas.core.dtypes.generic import ( +from .dtypes.concat import concat_compat +from .dtypes.generic import ( ABCDataFrame, ABCMultiIndex, ABCSeries, ) -from pandas.core.dtypes.missing import ( +from .dtypes.missing import ( infer_fill_value, isna, ) - -import pandas.core.common as com -from pandas.core.construction import array as pd_array -from pandas.core.indexers import ( +from .indexers import ( check_array_indexer, is_exact_shape_match, is_list_like_indexer, length_of_indexer, ) -from pandas.core.indexes.api import Index +from .indexes.api import Index if TYPE_CHECKING: from pandas import ( diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index 132598e03d6c0..1b91c13bb99b7 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -1,6 +1,6 @@ -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 +from .array_manager import ArrayManager +from .base import DataManager +from .blocks import ( # io.pytables, io.packers Block, CategoricalBlock, DatetimeBlock, @@ -12,8 +12,8 @@ TimeDeltaBlock, make_block, ) -from pandas.core.internals.concat import concatenate_block_managers -from pandas.core.internals.managers import ( +from .concat import concatenate_block_managers +from .managers import ( BlockManager, SingleBlockManager, create_block_manager_from_arrays, diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 0e52ebf69137c..1396985b211d8 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -56,11 +56,12 @@ Index, ensure_index, ) -from pandas.core.internals.base import DataManager -from pandas.core.internals.blocks import make_block + +from .base import DataManager +from .blocks import make_block if TYPE_CHECKING: - from pandas.core.internals.managers import SingleBlockManager + from .managers import SingleBlockManager T = TypeVar("T", bound="ArrayManager") @@ -643,7 +644,7 @@ def iget(self, i: int) -> SingleBlockManager: """ Return the data as a SingleBlockManager. """ - from pandas.core.internals.managers import SingleBlockManager + from .managers import SingleBlockManager values = self.arrays[i] block = make_block(values, placement=slice(0, len(values)), ndim=1) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index aa3545b83dfe3..db5eca8a3db0d 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -41,9 +41,10 @@ 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 + +from .array_manager import ArrayManager +from .blocks import make_block +from .managers import BlockManager if TYPE_CHECKING: from pandas import Index diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 2cfe613b7072b..2f685082ff04f 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -70,7 +70,8 @@ get_objs_combined_axis, union_indexes, ) -from pandas.core.internals.managers import ( + +from .managers import ( create_block_manager_from_arrays, create_block_manager_from_blocks, ) @@ -165,7 +166,7 @@ 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 ( + from . import ( ArrayManager, BlockManager, ) @@ -259,7 +260,7 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool): if isinstance(dvals_list[n], np.ndarray): dvals_list[n] = dvals_list[n].reshape(1, -1) - from pandas.core.internals.blocks import make_block + from .blocks import make_block # TODO: What about re-joining object columns? block_values = [ diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 4ad094f315c78..5eff1ad67a045 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -62,8 +62,9 @@ Index, ensure_index, ) -from pandas.core.internals.base import DataManager -from pandas.core.internals.blocks import ( + +from .base import DataManager +from .blocks import ( Block, CategoricalBlock, DatetimeTZBlock, @@ -74,7 +75,7 @@ get_block_type, make_block, ) -from pandas.core.internals.ops import ( +from .ops import ( blockwise_all, operate_blockwise, ) diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py index 70d4f3b91c245..b98106d55ea0f 100644 --- a/pandas/core/internals/ops.py +++ b/pandas/core/internals/ops.py @@ -13,8 +13,8 @@ from pandas._typing import ArrayLike if TYPE_CHECKING: - from pandas.core.internals.blocks import Block - from pandas.core.internals.managers import BlockManager + from .blocks import Block + from .managers import BlockManager BlockPairInfo = namedtuple( diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 9ae5f7d1b7497..743f92cf52d07 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -26,14 +26,14 @@ ) from pandas.compat._optional import import_optional_dependency -from pandas.core.dtypes.cast import infer_dtype_from -from pandas.core.dtypes.common import ( +from .dtypes.cast import infer_dtype_from +from .dtypes.common import ( ensure_float64, is_integer_dtype, is_numeric_v_string_like, needs_i8_conversion, ) -from pandas.core.dtypes.missing import isna +from .dtypes.missing import isna if TYPE_CHECKING: from pandas import Index diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 24e75a2bbeff2..efc7ac8f27984 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -29,7 +29,8 @@ ) from pandas.compat._optional import import_optional_dependency -from pandas.core.dtypes.common import ( +from .construction import extract_array +from .dtypes.common import ( get_dtype, is_any_int_dtype, is_bool_dtype, @@ -46,15 +47,13 @@ needs_i8_conversion, pandas_dtype, ) -from pandas.core.dtypes.dtypes import PeriodDtype -from pandas.core.dtypes.missing import ( +from .dtypes.dtypes import PeriodDtype +from .dtypes.missing import ( isna, na_value_for_dtype, notna, ) -from pandas.core.construction import extract_array - bn = import_optional_dependency("bottleneck", errors="warn") _BOTTLENECK_INSTALLED = bn is not None _USE_BOTTLENECK = False diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 8ace64fedacb9..6f794d1d69d64 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -30,30 +30,31 @@ from pandas.core.dtypes.missing import isna from pandas.core import algorithms -from pandas.core.ops.array_ops import ( # noqa:F401 + +from .array_ops import ( # noqa:F401 arithmetic_op, comp_method_OBJECT_ARRAY, comparison_op, get_array_op, logical_op, ) -from pandas.core.ops.common import ( # noqa:F401 +from .common import ( # noqa:F401 get_op_result_name, unpack_zerodim_and_defer, ) -from pandas.core.ops.docstrings import ( +from .docstrings import ( _flex_comp_doc_FRAME, _op_descriptions, make_flex_doc, ) -from pandas.core.ops.invalid import invalid_comparison # noqa:F401 -from pandas.core.ops.mask_ops import ( # noqa: F401 +from .invalid import invalid_comparison # noqa:F401 +from .mask_ops import ( # noqa: F401 kleene_and, kleene_or, kleene_xor, ) -from pandas.core.ops.methods import add_flex_arithmetic_methods # noqa:F401 -from pandas.core.ops.roperator import ( # noqa:F401 +from .methods import add_flex_arithmetic_methods # noqa:F401 +from .roperator import ( # noqa:F401 radd, rand_, rdiv, diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 10807dffb026b..5289ef726a27a 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -46,10 +46,11 @@ ) from pandas.core.construction import ensure_wrapped_if_datetimelike -from pandas.core.ops import missing -from pandas.core.ops.dispatch import should_extension_dispatch -from pandas.core.ops.invalid import invalid_comparison -from pandas.core.ops.roperator import rpow + +from . import missing +from .dispatch import should_extension_dispatch +from .invalid import invalid_comparison +from .roperator import rpow def comp_method_OBJECT_ARRAY(op, x, y): diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py index 700c4a946e2b2..c7fda4306ba8c 100644 --- a/pandas/core/ops/methods.py +++ b/pandas/core/ops/methods.py @@ -8,7 +8,7 @@ ABCSeries, ) -from pandas.core.ops.roperator import ( +from .roperator import ( radd, rdivmod, rfloordiv, @@ -36,7 +36,7 @@ def _get_method_wrappers(cls): """ # TODO: make these non-runtime imports once the relevant functions # are no longer in __init__ - from pandas.core.ops import ( + from . import ( flex_arith_method_FRAME, flex_comp_method_FRAME, flex_method_SERIES, diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py index 20b7510c33160..25b0066df022d 100644 --- a/pandas/core/ops/missing.py +++ b/pandas/core/ops/missing.py @@ -31,7 +31,7 @@ is_scalar, ) -from pandas.core.ops.roperator import ( +from .roperator import ( rdivmod, rfloordiv, rmod, diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 2308f9edb4328..cd3df5bf1f8e6 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -36,56 +36,56 @@ doc, ) -from pandas.core.dtypes.generic import ( +import pandas.core.algorithms as algos + +from pandas.tseries.frequencies import ( + is_subperiod, + is_superperiod, +) +from pandas.tseries.offsets import ( + DateOffset, + Day, + Nano, + Tick, +) + +from .apply import ResamplerWindowApply +from .base import DataError +from .dtypes.generic import ( ABCDataFrame, ABCSeries, ) - -import pandas.core.algorithms as algos -from pandas.core.apply import ResamplerWindowApply -from pandas.core.base import DataError -from pandas.core.generic import ( +from .generic import ( NDFrame, _shared_docs, ) -from pandas.core.groupby.base import ( +from .groupby.base import ( GotItemMixin, ShallowMixin, ) -from pandas.core.groupby.generic import SeriesGroupBy -from pandas.core.groupby.groupby import ( +from .groupby.generic import SeriesGroupBy +from .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 -from pandas.core.indexes.datetimes import ( +from .groupby.grouper import Grouper +from .groupby.ops import BinGrouper +from .indexes.api import Index +from .indexes.datetimes import ( DatetimeIndex, date_range, ) -from pandas.core.indexes.period import ( +from .indexes.period import ( PeriodIndex, period_range, ) -from pandas.core.indexes.timedeltas import ( +from .indexes.timedeltas import ( TimedeltaIndex, timedelta_range, ) -from pandas.tseries.frequencies import ( - is_subperiod, - is_superperiod, -) -from pandas.tseries.offsets import ( - DateOffset, - Day, - Nano, - Tick, -) - _shared_docs_kwargs: Dict[str, str] = {} diff --git a/pandas/core/reshape/api.py b/pandas/core/reshape/api.py index 58d741c2c6988..647bc3dbfc66c 100644 --- a/pandas/core/reshape/api.py +++ b/pandas/core/reshape/api.py @@ -1,23 +1,23 @@ # flake8: noqa -from pandas.core.reshape.concat import concat -from pandas.core.reshape.melt import ( +from .concat import concat +from .melt import ( lreshape, melt, wide_to_long, ) -from pandas.core.reshape.merge import ( +from .merge import ( merge, merge_asof, merge_ordered, ) -from pandas.core.reshape.pivot import ( +from .pivot import ( crosstab, pivot, pivot_table, ) -from pandas.core.reshape.reshape import get_dummies -from pandas.core.reshape.tile import ( +from .reshape import get_dummies +from .tile import ( cut, qcut, ) diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 80a44e8fda39b..70bafc18fcfd4 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -28,11 +28,12 @@ Index, MultiIndex, ) -from pandas.core.reshape.concat import concat -from pandas.core.reshape.util import tile_compat from pandas.core.shared_docs import _shared_docs from pandas.core.tools.numeric import to_numeric +from .concat import concat +from .util import tile_compat + if TYPE_CHECKING: from pandas import ( DataFrame, diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 79d018427aa33..0ab5a1965bd3d 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -173,7 +173,7 @@ def _groupby_and_merge(by, on, left: DataFrame, right: DataFrame, merge_pieces): # preserve the original order # if we have a missing piece this can be reset - from pandas.core.reshape.concat import concat + from .concat import concat result = concat(pieces, ignore_index=True) result = result.reindex(columns=pieces[0].columns, copy=False) diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 778e37bc07eb5..9ccfbf146180e 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -44,10 +44,11 @@ MultiIndex, get_objs_combined_axis, ) -from pandas.core.reshape.concat import concat -from pandas.core.reshape.util import cartesian_product from pandas.core.series import Series +from .concat import concat +from .util import cartesian_product + if TYPE_CHECKING: from pandas import DataFrame diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 4ccdbc089a058..bf795c6f8790d 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -841,7 +841,7 @@ def get_dummies( 1 0.0 1.0 0.0 2 0.0 0.0 1.0 """ - from pandas.core.reshape.concat import concat + from .concat import concat dtypes_to_encode = ["object", "category"] @@ -931,7 +931,7 @@ def _get_dummies_1d( drop_first=False, dtype: Optional[Dtype] = None, ): - from pandas.core.reshape.concat import concat + from .concat import concat # Series avoids inconsistent NaN handling codes, levels = factorize_from_iterable(Series(data)) diff --git a/pandas/core/series.py b/pandas/core/series.py index cbb66918a661b..b62e61cc76deb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -56,13 +56,39 @@ validate_percentile, ) -from pandas.core.dtypes.cast import ( +import pandas.core.common as com +import pandas.core.indexes.base as ibase + +import pandas.io.formats.format as fmt +import pandas.plotting + +from . import ( + algorithms, + base, + generic, + missing, + nanops, + ops, +) +from .accessor import CachedAccessor +from .aggregation import transform +from .apply import series_apply +from .arrays import ExtensionArray +from .arrays.categorical import CategoricalAccessor +from .arrays.sparse import SparseAccessor +from .construction import ( + create_series_with_explicit_dtype, + extract_array, + is_empty_data, + sanitize_array, +) +from .dtypes.cast import ( convert_dtypes, maybe_box_native, maybe_cast_to_extension_array, validate_numeric_casting, ) -from pandas.core.dtypes.common import ( +from .dtypes.common import ( ensure_platform_int, is_bool, is_categorical_dtype, @@ -76,66 +102,40 @@ pandas_dtype, validate_all_hashable, ) -from pandas.core.dtypes.generic import ABCDataFrame -from pandas.core.dtypes.inference import is_hashable -from pandas.core.dtypes.missing import ( +from .dtypes.generic import ABCDataFrame +from .dtypes.inference import is_hashable +from .dtypes.missing import ( isna, na_value_for_dtype, notna, remove_na_arraylike, ) - -from pandas.core import ( - algorithms, - base, - generic, - missing, - nanops, - ops, -) -from pandas.core.accessor import CachedAccessor -from pandas.core.aggregation import transform -from pandas.core.apply import series_apply -from pandas.core.arrays import ExtensionArray -from pandas.core.arrays.categorical import CategoricalAccessor -from pandas.core.arrays.sparse import SparseAccessor -import pandas.core.common as com -from pandas.core.construction import ( - create_series_with_explicit_dtype, - extract_array, - is_empty_data, - sanitize_array, -) -from pandas.core.generic import NDFrame -from pandas.core.indexers import ( +from .generic import NDFrame +from .indexers import ( deprecate_ndim_indexing, unpack_1tuple, ) -from pandas.core.indexes.accessors import CombinedDatetimelikeProperties -from pandas.core.indexes.api import ( +from .indexes.accessors import CombinedDatetimelikeProperties +from .indexes.api import ( CategoricalIndex, Float64Index, Index, MultiIndex, ensure_index, ) -import pandas.core.indexes.base as ibase -from pandas.core.indexes.datetimes import DatetimeIndex -from pandas.core.indexes.period import PeriodIndex -from pandas.core.indexes.timedeltas import TimedeltaIndex -from pandas.core.indexing import check_bool_indexer -from pandas.core.internals import SingleBlockManager -from pandas.core.internals.construction import sanitize_index -from pandas.core.shared_docs import _shared_docs -from pandas.core.sorting import ( +from .indexes.datetimes import DatetimeIndex +from .indexes.period import PeriodIndex +from .indexes.timedeltas import TimedeltaIndex +from .indexing import check_bool_indexer +from .internals import SingleBlockManager +from .internals.construction import sanitize_index +from .shared_docs import _shared_docs +from .sorting import ( ensure_key_mapped, nargsort, ) -from pandas.core.strings import StringMethods -from pandas.core.tools.datetimes import to_datetime - -import pandas.io.formats.format as fmt -import pandas.plotting +from .strings import StringMethods +from .tools.datetimes import to_datetime if TYPE_CHECKING: from pandas._typing import ( @@ -143,9 +143,9 @@ TimestampConvertibleTypes, ) - from pandas.core.frame import DataFrame - from pandas.core.groupby.generic import SeriesGroupBy - from pandas.core.resample import Resampler + from .frame import DataFrame + from .groupby.generic import SeriesGroupBy + from .resample import Resampler __all__ = ["Series"] @@ -464,7 +464,7 @@ def _constructor_expanddim(self) -> Type[DataFrame]: Used when a manipulation result has one higher dimension as the original, such as Series.to_frame() """ - from pandas.core.frame import DataFrame + from .frame import DataFrame return DataFrame @@ -1736,7 +1736,7 @@ def groupby( observed: bool = False, dropna: bool = True, ) -> SeriesGroupBy: - from pandas.core.groupby.generic import SeriesGroupBy + from .groupby.generic import SeriesGroupBy if squeeze is not no_default: warnings.warn( @@ -2715,7 +2715,7 @@ def append(self, to_append, ignore_index=False, verify_integrity=False): ... ValueError: Indexes have overlapping values: [0, 1, 2] """ - from pandas.core.reshape.concat import concat + from .reshape.concat import concat if isinstance(to_append, (list, tuple)): to_concat = [self] @@ -3854,7 +3854,7 @@ def unstack(self, level=-1, fill_value=None): a 1 3 b 2 4 """ - from pandas.core.reshape.reshape import unstack + from .reshape.reshape import unstack return unstack(self, level, fill_value) diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 67863036929b3..0dbb44581e042 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -24,20 +24,21 @@ from pandas._libs.hashtable import unique_label_indices from pandas._typing import IndexKeyFunc -from pandas.core.dtypes.common import ( +import pandas.core.algorithms as algorithms + +from .construction import extract_array +from .dtypes.common import ( ensure_int64, ensure_platform_int, is_extension_array_dtype, ) -from pandas.core.dtypes.generic import ABCMultiIndex -from pandas.core.dtypes.missing import isna - -import pandas.core.algorithms as algorithms -from pandas.core.construction import extract_array +from .dtypes.generic import ABCMultiIndex +from .dtypes.missing import isna if TYPE_CHECKING: from pandas import MultiIndex - from pandas.core.indexes.base import Index + + from .indexes.base import Index _INT64_MAX = np.iinfo(np.int64).max @@ -289,7 +290,7 @@ def lexsort_indexer( .. versionadded:: 1.0.0 """ - from pandas.core.arrays import Categorical + from .arrays import Categorical labels = [] shape = [] @@ -485,7 +486,7 @@ def ensure_key_mapped(values, key: Optional[Callable], levels=None): levels : Optional[List], if values is a MultiIndex, list of levels to apply the key to. """ - from pandas.core.indexes.api import Index + from .indexes.api import Index if not key: return values diff --git a/pandas/core/strings/__init__.py b/pandas/core/strings/__init__.py index 943686fc85a05..243250f0360a0 100644 --- a/pandas/core/strings/__init__.py +++ b/pandas/core/strings/__init__.py @@ -26,7 +26,7 @@ # - PandasArray # - Categorical -from pandas.core.strings.accessor import StringMethods -from pandas.core.strings.base import BaseStringArrayMethods +from .accessor import StringMethods +from .base import BaseStringArrayMethods __all__ = ["StringMethods", "BaseStringArrayMethods"] diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 0a4543057c386..e1346de69b1a8 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -26,7 +26,7 @@ ) from pandas.core.dtypes.missing import isna -from pandas.core.strings.base import BaseStringArrayMethods +from .base import BaseStringArrayMethods class ObjectStringArrayMixin(BaseStringArrayMethods): diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 18f9ece3e3812..56656cd5a3220 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -1025,6 +1025,6 @@ def to_time(arg, format=None, infer_time_format=False, errors="raise"): FutureWarning, stacklevel=2, ) - from pandas.core.tools.times import to_time + from .times import to_time return to_time(arg, format, infer_time_format, errors) diff --git a/pandas/core/window/__init__.py b/pandas/core/window/__init__.py index 8f42cd782c67f..f41cb652323f1 100644 --- a/pandas/core/window/__init__.py +++ b/pandas/core/window/__init__.py @@ -1,12 +1,12 @@ -from pandas.core.window.ewm import ( # noqa:F401 +from .ewm import ( # noqa:F401 ExponentialMovingWindow, ExponentialMovingWindowGroupby, ) -from pandas.core.window.expanding import ( # noqa:F401 +from .expanding import ( # noqa:F401 Expanding, ExpandingGroupby, ) -from pandas.core.window.rolling import ( # noqa:F401 +from .rolling import ( # noqa:F401 Rolling, RollingGroupby, Window, diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 518119b63209e..4d5e26a1cd064 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -26,8 +26,9 @@ import pandas.core.common as common from pandas.core.util.numba_ import maybe_use_numba -from pandas.core.window.common import zsqrt -from pandas.core.window.doc import ( + +from .common import zsqrt +from .doc import ( _shared_docs, args_compat, create_section_header, @@ -36,13 +37,13 @@ template_returns, template_see_also, ) -from pandas.core.window.indexers import ( +from .indexers import ( BaseIndexer, ExponentialMovingWindowIndexer, GroupbyIndexer, ) -from pandas.core.window.numba_ import generate_numba_groupby_ewma_func -from pandas.core.window.rolling import ( +from .numba_ import generate_numba_groupby_ewma_func +from .rolling import ( BaseWindow, BaseWindowGroupby, ) diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 64e092d853456..f4fef4c32afc0 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -14,7 +14,7 @@ from pandas.compat.numpy import function as nv from pandas.util._decorators import doc -from pandas.core.window.doc import ( +from .doc import ( _shared_docs, args_compat, create_section_header, @@ -26,12 +26,12 @@ window_agg_numba_parameters, window_apply_parameters, ) -from pandas.core.window.indexers import ( +from .indexers import ( BaseIndexer, ExpandingIndexer, GroupbyIndexer, ) -from pandas.core.window.rolling import ( +from .rolling import ( BaseWindowGroupby, RollingAndExpandingMixin, ) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 20bf0142b0855..d39fbde782f37 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -77,11 +77,12 @@ NUMBA_FUNC_CACHE, maybe_use_numba, ) -from pandas.core.window.common import ( + +from .common import ( flex_binary_moment, zsqrt, ) -from pandas.core.window.doc import ( +from .doc import ( _shared_docs, args_compat, create_section_header, @@ -94,13 +95,13 @@ window_agg_numba_parameters, window_apply_parameters, ) -from pandas.core.window.indexers import ( +from .indexers import ( BaseIndexer, FixedWindowIndexer, GroupbyIndexer, VariableWindowIndexer, ) -from pandas.core.window.numba_ import ( +from .numba_ import ( generate_manual_numpy_nan_agg_with_axis, generate_numba_apply_func, generate_numba_table_func, diff --git a/pandas/io/api.py b/pandas/io/api.py index 2241f491b5d48..699eb10e1996e 100644 --- a/pandas/io/api.py +++ b/pandas/io/api.py @@ -4,36 +4,36 @@ # flake8: noqa -from pandas.io.clipboards import read_clipboard -from pandas.io.excel import ( +from .clipboards import read_clipboard +from .excel import ( ExcelFile, ExcelWriter, read_excel, ) -from pandas.io.feather_format import read_feather -from pandas.io.gbq import read_gbq -from pandas.io.html import read_html -from pandas.io.json import read_json -from pandas.io.orc import read_orc -from pandas.io.parquet import read_parquet -from pandas.io.parsers import ( +from .feather_format import read_feather +from .gbq import read_gbq +from .html import read_html +from .json import read_json +from .orc import read_orc +from .parquet import read_parquet +from .parsers import ( read_csv, read_fwf, read_table, ) -from pandas.io.pickle import ( +from .pickle import ( read_pickle, to_pickle, ) -from pandas.io.pytables import ( +from .pytables import ( HDFStore, read_hdf, ) -from pandas.io.sas import read_sas -from pandas.io.spss import read_spss -from pandas.io.sql import ( +from .sas import read_sas +from .spss import read_spss +from .sql import ( read_sql, read_sql_query, read_sql_table, ) -from pandas.io.stata import read_stata +from .stata import read_stata diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index 54cb6b9f91137..00c9e73dffae9 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -35,8 +35,8 @@ def read_clipboard(sep=r"\s+", **kwargs): # pragma: no cover if encoding is not None and encoding.lower().replace("-", "") != "utf8": raise NotImplementedError("reading from clipboard only supports utf-8 encoding") - from pandas.io.clipboard import clipboard_get - from pandas.io.parsers import read_csv + from .clipboard import clipboard_get + from .parsers import read_csv text = clipboard_get() @@ -107,7 +107,7 @@ def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover if encoding is not None and encoding.lower().replace("-", "") != "utf8": raise ValueError("clipboard only supports utf-8 encoding") - from pandas.io.clipboard import clipboard_set + from .clipboard import clipboard_set if excel is None: excel = True diff --git a/pandas/io/excel/__init__.py b/pandas/io/excel/__init__.py index 854e2a1ec3a73..e9bef63447e7e 100644 --- a/pandas/io/excel/__init__.py +++ b/pandas/io/excel/__init__.py @@ -1,13 +1,13 @@ -from pandas.io.excel._base import ( +from ._base import ( ExcelFile, ExcelWriter, read_excel, ) -from pandas.io.excel._odswriter import ODSWriter as _ODSWriter -from pandas.io.excel._openpyxl import OpenpyxlWriter as _OpenpyxlWriter -from pandas.io.excel._util import register_writer -from pandas.io.excel._xlsxwriter import XlsxWriter as _XlsxWriter -from pandas.io.excel._xlwt import XlwtWriter as _XlwtWriter +from ._odswriter import ODSWriter as _ODSWriter +from ._openpyxl import OpenpyxlWriter as _OpenpyxlWriter +from ._util import register_writer +from ._xlsxwriter import XlsxWriter as _XlsxWriter +from ._xlwt import XlwtWriter as _XlwtWriter __all__ = ["read_excel", "ExcelWriter", "ExcelFile"] diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 9ad589d4583c6..b73c38b8675dd 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -54,14 +54,15 @@ stringify_path, validate_header_arg, ) -from pandas.io.excel._util import ( +from pandas.io.parsers import TextParser + +from ._util import ( fill_mi_header, get_default_engine, get_writer, maybe_convert_usecols, pop_header_name, ) -from pandas.io.parsers import TextParser _read_excel_doc = ( """ @@ -1064,10 +1065,10 @@ class ExcelFile: This is not supported, switch to using ``openpyxl`` instead. """ - from pandas.io.excel._odfreader import ODFReader - from pandas.io.excel._openpyxl import OpenpyxlReader - from pandas.io.excel._pyxlsb import PyxlsbReader - from pandas.io.excel._xlrd import XlrdReader + from ._odfreader import ODFReader + from ._openpyxl import OpenpyxlReader + from ._pyxlsb import PyxlsbReader + from ._xlrd import XlrdReader _engines: Mapping[str, Any] = { "xlrd": XlrdReader, diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py index c5aa4a061a05b..0bbbfe05fc508 100644 --- a/pandas/io/excel/_odfreader.py +++ b/pandas/io/excel/_odfreader.py @@ -14,7 +14,7 @@ import pandas as pd -from pandas.io.excel._base import BaseExcelReader +from ._base import BaseExcelReader class ODFReader(BaseExcelReader): diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py index d00e600b4e5d4..1e03354e94436 100644 --- a/pandas/io/excel/_odswriter.py +++ b/pandas/io/excel/_odswriter.py @@ -13,10 +13,11 @@ import pandas._libs.json as json from pandas._typing import StorageOptions -from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import validate_freeze_panes from pandas.io.formats.excel import ExcelCell +from ._base import ExcelWriter +from ._util import validate_freeze_panes + class ODSWriter(ExcelWriter): engine = "odf" diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index be2c9b919a5c3..9d1a8cde9761b 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -17,11 +17,11 @@ ) from pandas.compat._optional import import_optional_dependency -from pandas.io.excel._base import ( +from ._base import ( BaseExcelReader, ExcelWriter, ) -from pandas.io.excel._util import validate_freeze_panes +from ._util import validate_freeze_panes if TYPE_CHECKING: from openpyxl.descriptors.serialisable import Serialisable diff --git a/pandas/io/excel/_pyxlsb.py b/pandas/io/excel/_pyxlsb.py index 71ec189854f6d..0acbd1533ed86 100644 --- a/pandas/io/excel/_pyxlsb.py +++ b/pandas/io/excel/_pyxlsb.py @@ -7,7 +7,7 @@ ) from pandas.compat._optional import import_optional_dependency -from pandas.io.excel._base import BaseExcelReader +from ._base import BaseExcelReader class PyxlsbReader(BaseExcelReader): diff --git a/pandas/io/excel/_xlrd.py b/pandas/io/excel/_xlrd.py index 5eb88a694218a..6f29128c9ba63 100644 --- a/pandas/io/excel/_xlrd.py +++ b/pandas/io/excel/_xlrd.py @@ -5,7 +5,7 @@ from pandas._typing import StorageOptions from pandas.compat._optional import import_optional_dependency -from pandas.io.excel._base import BaseExcelReader +from ._base import BaseExcelReader class XlrdReader(BaseExcelReader): diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py index 849572cff813a..04703bd5a6296 100644 --- a/pandas/io/excel/_xlsxwriter.py +++ b/pandas/io/excel/_xlsxwriter.py @@ -7,8 +7,8 @@ import pandas._libs.json as json from pandas._typing import StorageOptions -from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import validate_freeze_panes +from ._base import ExcelWriter +from ._util import validate_freeze_panes class _XlsxStyler: diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py index a8386242faf72..310cb28c629e9 100644 --- a/pandas/io/excel/_xlwt.py +++ b/pandas/io/excel/_xlwt.py @@ -6,8 +6,8 @@ import pandas._libs.json as json from pandas._typing import StorageOptions -from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import validate_freeze_panes +from ._base import ExcelWriter +from ._util import validate_freeze_panes if TYPE_CHECKING: from xlwt import XFStyle diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index 3999f91a7b141..d35d50ebe941b 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -16,7 +16,7 @@ ) from pandas.core import generic -from pandas.io.common import get_handle +from .common import get_handle @doc(storage_options=generic._shared_docs["storage_options"]) diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index ca8340cfd0a24..bf4fe02077a5d 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -42,7 +42,7 @@ from pandas.io.common import get_handle if TYPE_CHECKING: - from pandas.io.formats.format import DataFrameFormatter + from .format import DataFrameFormatter class CSVFormatter: diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 1ec2f7bfdd4be..3b8d8da671e01 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -42,13 +42,13 @@ from pandas.core import generic import pandas.core.common as com -from pandas.io.formats._color_data import CSS4_COLORS -from pandas.io.formats.css import ( +from ._color_data import CSS4_COLORS +from .css import ( CSSResolver, CSSWarning, ) -from pandas.io.formats.format import get_level_lengths -from pandas.io.formats.printing import pprint_thing +from .format import get_level_lengths +from .printing import pprint_thing class ExcelCell: diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index a1b6986079723..c80c0972b264a 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -98,7 +98,8 @@ from pandas.core.reshape.concat import concat from pandas.io.common import stringify_path -from pandas.io.formats.printing import ( + +from .printing import ( adjoin, justify, pprint_thing, @@ -968,7 +969,7 @@ def to_latex( """ Render a DataFrame to a LaTeX tabular/longtable environment output. """ - from pandas.io.formats.latex import LatexFormatter + from .latex import LatexFormatter latex_formatter = LatexFormatter( self.fmt, @@ -1016,7 +1017,7 @@ def to_html( render_links : bool, default False Convert URLs to HTML links. """ - from pandas.io.formats.html import ( + from .html import ( HTMLFormatter, NotebookFormatter, ) @@ -1051,7 +1052,7 @@ def to_string( line_width : int, optional Width to wrap a line in characters. """ - from pandas.io.formats.string import StringFormatter + from .string import StringFormatter string_formatter = StringFormatter(self.fmt, line_width=line_width) string = string_formatter.to_string() @@ -1079,7 +1080,7 @@ def to_csv( """ Render dataframe as comma-separated file. """ - from pandas.io.formats.csvs import CSVFormatter + from .csvs import CSVFormatter if path_or_buf is None: created_buffer = True diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py index 6f4a6d87c7959..e7d3503049ab5 100644 --- a/pandas/io/formats/html.py +++ b/pandas/io/formats/html.py @@ -25,11 +25,12 @@ ) from pandas.io.common import is_url -from pandas.io.formats.format import ( + +from .format import ( DataFrameFormatter, get_level_lengths, ) -from pandas.io.formats.printing import pprint_thing +from .printing import pprint_thing class HTMLFormatter: diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index 2c1739998da08..7723b9d7a893f 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -26,8 +26,8 @@ from pandas.core.indexes.api import Index -from pandas.io.formats import format as fmt -from pandas.io.formats.printing import pprint_thing +from . import format as fmt +from .printing import pprint_thing if TYPE_CHECKING: from pandas.core.frame import DataFrame diff --git a/pandas/io/formats/latex.py b/pandas/io/formats/latex.py index fce0814e979a4..d8436727e6b33 100644 --- a/pandas/io/formats/latex.py +++ b/pandas/io/formats/latex.py @@ -19,7 +19,7 @@ from pandas.core.dtypes.generic import ABCMultiIndex -from pandas.io.formats.format import DataFrameFormatter +from .format import DataFrameFormatter def _split_into_full_short_caption( diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index acb17aee50b76..35f6d3e81bade 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -321,8 +321,8 @@ def format_object_summary( ------- summary string """ - from pandas.io.formats.console import get_console_size - from pandas.io.formats.format import get_adjustment + from .console import get_console_size + from .format import get_adjustment display_width, _ = get_console_size() if display_width is None: diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py index 622001f280885..57b3f7ceb42e2 100644 --- a/pandas/io/formats/string.py +++ b/pandas/io/formats/string.py @@ -10,8 +10,8 @@ import numpy as np -from pandas.io.formats.format import DataFrameFormatter -from pandas.io.formats.printing import pprint_thing +from .format import DataFrameFormatter +from .printing import pprint_thing class StringFormatter: diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 877e146fd8681..e832e2e413bd5 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -355,7 +355,7 @@ def to_excel( freeze_panes: Optional[Tuple[int, int]] = None, ) -> None: - from pandas.io.formats.excel import ExcelFormatter + from .excel import ExcelFormatter formatter = ExcelFormatter( self, diff --git a/pandas/io/html.py b/pandas/io/html.py index 7541e5d62fd1e..829b9c6ae063d 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -31,14 +31,14 @@ from pandas.core.construction import create_series_with_explicit_dtype from pandas.core.frame import DataFrame -from pandas.io.common import ( +from .common import ( is_url, stringify_path, urlopen, validate_header_arg, ) -from pandas.io.formats.printing import pprint_thing -from pandas.io.parsers import TextParser +from .formats.printing import pprint_thing +from .parsers import TextParser _IMPORTS = False _HAS_BS4 = False diff --git a/pandas/io/json/__init__.py b/pandas/io/json/__init__.py index 1de1abcdb9920..20c92de3ae2c8 100644 --- a/pandas/io/json/__init__.py +++ b/pandas/io/json/__init__.py @@ -1,14 +1,14 @@ -from pandas.io.json._json import ( +from ._json import ( dumps, loads, read_json, to_json, ) -from pandas.io.json._normalize import ( +from ._normalize import ( _json_normalize, json_normalize, ) -from pandas.io.json._table_schema import build_table_schema +from ._table_schema import build_table_schema __all__ = [ "dumps", diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 635a493d03d61..3f6e038031590 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -61,12 +61,13 @@ is_url, stringify_path, ) -from pandas.io.json._normalize import convert_to_line_delimits -from pandas.io.json._table_schema import ( +from pandas.io.parsers.readers import validate_integer + +from ._normalize import convert_to_line_delimits +from ._table_schema import ( build_table_schema, parse_table_schema, ) -from pandas.io.parsers.readers import validate_integer loads = json.loads dumps = json.dumps diff --git a/pandas/io/orc.py b/pandas/io/orc.py index df76156aac9eb..8b0c9c00373ee 100644 --- a/pandas/io/orc.py +++ b/pandas/io/orc.py @@ -10,7 +10,7 @@ from pandas._typing import FilePathOrBuffer -from pandas.io.common import get_handle +from .common import get_handle if TYPE_CHECKING: from pandas import DataFrame diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 183d753ddd60b..f026a0a8b2ae1 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -29,7 +29,7 @@ ) from pandas.core import generic -from pandas.io.common import ( +from .common import ( IOHandles, get_handle, is_fsspec_url, diff --git a/pandas/io/parsers/__init__.py b/pandas/io/parsers/__init__.py index ff11968db15f0..c7f9b328fc304 100644 --- a/pandas/io/parsers/__init__.py +++ b/pandas/io/parsers/__init__.py @@ -1,4 +1,4 @@ -from pandas.io.parsers.readers import ( +from .readers import ( TextFileReader, TextParser, read_csv, diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 135e093cdc1e0..253b86c3a220c 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -3,7 +3,7 @@ from pandas.core.indexes.api import ensure_index_from_sequences -from pandas.io.parsers.base_parser import ( +from .base_parser import ( ParserBase, is_index_col, ) diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 37f553c724c9e..8957016a997ae 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -30,7 +30,7 @@ from pandas.core.dtypes.common import is_integer -from pandas.io.parsers.base_parser import ( +from .base_parser import ( ParserBase, parser_defaults, ) diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index edfc7ee0b6258..633dde249f644 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -43,13 +43,14 @@ from pandas.core.indexes.api import RangeIndex from pandas.io.common import validate_header_arg -from pandas.io.parsers.base_parser import ( + +from .base_parser import ( ParserBase, is_index_col, parser_defaults, ) -from pandas.io.parsers.c_parser_wrapper import CParserWrapper -from pandas.io.parsers.python_parser import ( +from .c_parser_wrapper import CParserWrapper +from .python_parser import ( FixedWidthFieldParser, PythonParser, ) diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py index 785afce9e0214..66612245679af 100644 --- a/pandas/io/pickle.py +++ b/pandas/io/pickle.py @@ -13,7 +13,7 @@ from pandas.core import generic -from pandas.io.common import get_handle +from .common import get_handle @doc(storage_options=generic._shared_docs["storage_options"]) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 88b444acfea62..d3bea85ff73fb 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -94,8 +94,8 @@ 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 ( +from .common import stringify_path +from .formats.printing import ( adjoin, pprint_thing, ) diff --git a/pandas/io/sas/__init__.py b/pandas/io/sas/__init__.py index 8f81352e6aecb..fa6b29a1a3fcc 100644 --- a/pandas/io/sas/__init__.py +++ b/pandas/io/sas/__init__.py @@ -1 +1 @@ -from pandas.io.sas.sasreader import read_sas # noqa +from .sasreader import read_sas # noqa diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py index 392dfa22ee67b..5faa9a221e608 100644 --- a/pandas/io/sas/sas7bdat.py +++ b/pandas/io/sas/sas7bdat.py @@ -37,9 +37,10 @@ from pandas import isna from pandas.io.common import get_handle -from pandas.io.sas._sas import Parser import pandas.io.sas.sas_constants as const -from pandas.io.sas.sasreader import ReaderBase + +from ._sas import Parser +from .sasreader import ReaderBase def _parse_datetime(sas_datetime: float, unit: str): diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index c71de542bbf77..ff854efc6bdd6 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -23,7 +23,8 @@ import pandas as pd from pandas.io.common import get_handle -from pandas.io.sas.sasreader import ReaderBase + +from .sasreader import ReaderBase _correct_line1 = ( "HEADER RECORD*******LIBRARY HEADER RECORD!!!!!!!" diff --git a/pandas/io/sas/sasreader.py b/pandas/io/sas/sasreader.py index 69da038929482..a92684a34e543 100644 --- a/pandas/io/sas/sasreader.py +++ b/pandas/io/sas/sasreader.py @@ -136,7 +136,7 @@ def read_sas( reader: ReaderBase if format.lower() == "xport": - from pandas.io.sas.sas_xport import XportReader + from .sas_xport import XportReader reader = XportReader( filepath_or_buffer, @@ -145,7 +145,7 @@ def read_sas( chunksize=chunksize, ) elif format.lower() == "sas7bdat": - from pandas.io.sas.sas7bdat import SAS7BDATReader + from .sas7bdat import SAS7BDATReader reader = SAS7BDATReader( filepath_or_buffer, diff --git a/pandas/io/spss.py b/pandas/io/spss.py index fb0ecee995463..ee5008e02dedf 100644 --- a/pandas/io/spss.py +++ b/pandas/io/spss.py @@ -11,7 +11,7 @@ from pandas.core.api import DataFrame -from pandas.io.common import stringify_path +from .common import stringify_path def read_spss( diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 462c7b41f4271..b6985994e657b 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -68,7 +68,7 @@ from pandas.core.indexes.base import Index from pandas.core.series import Series -from pandas.io.common import get_handle +from .common import get_handle _version_error = ( "Version of given Stata file is {version}. pandas supports importing " diff --git a/pandas/plotting/__init__.py b/pandas/plotting/__init__.py index 55c861e384d67..ae85bb8e7334c 100644 --- a/pandas/plotting/__init__.py +++ b/pandas/plotting/__init__.py @@ -55,7 +55,7 @@ For the discussion about the API see https://github.com/pandas-dev/pandas/issues/26747. """ -from pandas.plotting._core import ( +from ._core import ( PlotAccessor, boxplot, boxplot_frame, @@ -63,7 +63,7 @@ hist_frame, hist_series, ) -from pandas.plotting._misc import ( +from ._misc import ( andrews_curves, autocorrelation_plot, bootstrap_plot, diff --git a/pandas/plotting/_matplotlib/__init__.py b/pandas/plotting/_matplotlib/__init__.py index b12ca6187c945..849aba95ae50b 100644 --- a/pandas/plotting/_matplotlib/__init__.py +++ b/pandas/plotting/_matplotlib/__init__.py @@ -6,17 +6,17 @@ Type, ) -from pandas.plotting._matplotlib.boxplot import ( +from .boxplot import ( BoxPlot, boxplot, boxplot_frame, boxplot_frame_groupby, ) -from pandas.plotting._matplotlib.converter import ( +from .converter import ( deregister, register, ) -from pandas.plotting._matplotlib.core import ( +from .core import ( AreaPlot, BarhPlot, BarPlot, @@ -25,13 +25,13 @@ PiePlot, ScatterPlot, ) -from pandas.plotting._matplotlib.hist import ( +from .hist import ( HistPlot, KdePlot, hist_frame, hist_series, ) -from pandas.plotting._matplotlib.misc import ( +from .misc import ( andrews_curves, autocorrelation_plot, bootstrap_plot, @@ -40,10 +40,10 @@ radviz, scatter_matrix, ) -from pandas.plotting._matplotlib.tools import table +from .tools import table if TYPE_CHECKING: - from pandas.plotting._matplotlib.core import MPLPlot + from .core import MPLPlot PLOT_CLASSES: Dict[str, Type[MPLPlot]] = { "line": LinePlot, diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 1ec4efe7b4795..afb560ac18418 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -14,12 +14,13 @@ import pandas.core.common as com from pandas.io.formats.printing import pprint_thing -from pandas.plotting._matplotlib.core import ( + +from .core import ( LinePlot, MPLPlot, ) -from pandas.plotting._matplotlib.style import get_standard_colors -from pandas.plotting._matplotlib.tools import ( +from .style import get_standard_colors +from .tools import ( create_subplots, flatten_axes, maybe_adjust_figure, diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 3b0d59501ba05..6fe0cacde8bc7 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -43,17 +43,18 @@ import pandas.core.common as com 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.timeseries import ( + +from .compat import mpl_ge_3_0_0 +from .converter import register_pandas_matplotlib_converters +from .style import get_standard_colors +from .timeseries import ( decorate_axes, format_dateaxis, maybe_convert_index, maybe_resample, use_dynamic_x, ) -from pandas.plotting._matplotlib.tools import ( +from .tools import ( create_subplots, flatten_axes, format_date_labels, diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index 3de467c77d289..13563406666e4 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -18,11 +18,12 @@ ) from pandas.io.formats.printing import pprint_thing -from pandas.plotting._matplotlib.core import ( + +from .core import ( LinePlot, MPLPlot, ) -from pandas.plotting._matplotlib.tools import ( +from .tools import ( create_subplots, flatten_axes, maybe_adjust_figure, diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 3d5f4af72db6c..054f695c77ab0 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -17,8 +17,9 @@ 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 ( + +from .style import get_standard_colors +from .tools import ( create_subplots, do_adjust_figure, maybe_adjust_figure, diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 8374988708701..04e4a74ca61af 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -26,17 +26,18 @@ ) from pandas.io.formats.printing import pprint_thing -from pandas.plotting._matplotlib.converter import ( - TimeSeries_DateFormatter, - TimeSeries_DateLocator, - TimeSeries_TimedeltaFormatter, -) from pandas.tseries.frequencies import ( get_period_alias, is_subperiod, is_superperiod, ) +from .converter import ( + TimeSeries_DateFormatter, + TimeSeries_DateLocator, + TimeSeries_TimedeltaFormatter, +) + if TYPE_CHECKING: from matplotlib.axes import Axes @@ -136,7 +137,7 @@ def _replot_ax(ax: Axes, freq, kwargs): # for tsplot if isinstance(plotf, str): - from pandas.plotting._matplotlib import PLOT_CLASSES + from . import PLOT_CLASSES plotf = PLOT_CLASSES[plotf]._plot diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 500d570835493..88e1257d813f5 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -25,7 +25,7 @@ ABCSeries, ) -from pandas.plotting._matplotlib import compat +from . import compat if TYPE_CHECKING: from matplotlib.axes import Axes diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index e0a860b9d8709..dae49ddc120de 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -1,6 +1,6 @@ from contextlib import contextmanager -from pandas.plotting._core import _get_plot_backend +from ._core import _get_plot_backend def table(ax, data, rowLabels=None, colLabels=None, **kwargs): diff --git a/pandas/testing.py b/pandas/testing.py index 841b55df48556..237ca56eca9e5 100644 --- a/pandas/testing.py +++ b/pandas/testing.py @@ -3,7 +3,7 @@ """ -from pandas._testing import ( +from ._testing import ( assert_extension_array_equal, assert_frame_equal, assert_index_equal, diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 71804bded3e44..31423c03dee34 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -1,6 +1,7 @@ import pandas._testing as tm from pandas.api import types -from pandas.tests.api.test_api import Base + +from .test_api import Base class TestTypes(Base): diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index f28407df24508..fa6e17674d3cb 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -40,7 +40,8 @@ TimedeltaArray, ) from pandas.core.ops import roperator -from pandas.tests.arithmetic.common import ( + +from .common import ( assert_invalid_addsub_type, assert_invalid_comparison, get_upcast_box, diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index f0c03fee50b39..71fcbb2d83ccc 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -25,7 +25,8 @@ import pandas._testing as tm from pandas.core import ops from pandas.core.arrays import TimedeltaArray -from pandas.tests.arithmetic.common import assert_invalid_comparison + +from .common import assert_invalid_comparison # ------------------------------------------------------------------ # Comparisons diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 3df54f769a6e4..fc06c567aee52 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -26,7 +26,8 @@ timedelta_range, ) import pandas._testing as tm -from pandas.tests.arithmetic.common import ( + +from .common import ( assert_invalid_addsub_type, assert_invalid_comparison, get_upcast_box, diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index a6dea639488a2..a2140599c6225 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -12,7 +12,8 @@ ) import pandas._testing as tm from pandas.core.arrays.categorical import recode_for_categories -from pandas.tests.arrays.categorical.common import TestCategorical + +from .common import TestCategorical class TestCategoricalAPI: diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 5b31776301f7b..793e5ed9ce61d 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -14,7 +14,8 @@ ) import pandas._testing as tm import pandas.core.common as com -from pandas.tests.arrays.categorical.common import TestCategorical + +from .common import TestCategorical class TestCategoricalIndexingWithFactor(TestCategorical): diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 4a00df2d783cf..463897fb38618 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -12,7 +12,8 @@ date_range, ) import pandas._testing as tm -from pandas.tests.arrays.categorical.common import TestCategorical + +from .common import TestCategorical class TestCategoricalOpsWithFactor(TestCategorical): diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py index e23fbb16190ea..1e5e79433fe83 100644 --- a/pandas/tests/arrays/categorical/test_repr.py +++ b/pandas/tests/arrays/categorical/test_repr.py @@ -9,7 +9,8 @@ period_range, timedelta_range, ) -from pandas.tests.arrays.categorical.common import TestCategorical + +from .common import TestCategorical class TestCategoricalReprWithFactor(TestCategorical): diff --git a/pandas/tests/base/test_fillna.py b/pandas/tests/base/test_fillna.py index c6f58af4c5c3a..1e7c83da6f670 100644 --- a/pandas/tests/base/test_fillna.py +++ b/pandas/tests/base/test_fillna.py @@ -13,7 +13,8 @@ from pandas import Index import pandas._testing as tm -from pandas.tests.base.common import allow_na_ops + +from .common import allow_na_ops def test_fillna(index_or_series_obj): diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py index 4aefa4be176fb..c9f52c409fa57 100644 --- a/pandas/tests/base/test_unique.py +++ b/pandas/tests/base/test_unique.py @@ -10,7 +10,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.base.common import allow_na_ops + +from .common import allow_na_ops def test_unique(index_or_series_obj): diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py index 4151781f0dbf5..db24694e4dc51 100644 --- a/pandas/tests/base/test_value_counts.py +++ b/pandas/tests/base/test_value_counts.py @@ -21,7 +21,8 @@ TimedeltaIndex, ) import pandas._testing as tm -from pandas.tests.base.common import allow_na_ops + +from .common import allow_na_ops def test_value_counts(index_or_series_obj): diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py index 829be279b45d3..d513c175e728b 100644 --- a/pandas/tests/extension/arrow/test_bool.py +++ b/pandas/tests/extension/arrow/test_bool.py @@ -8,7 +8,7 @@ pytest.importorskip("pyarrow", minversion="0.13.0") -from pandas.tests.extension.arrow.arrays import ( # isort:skip +from .arrays import ( # isort:skip ArrowBoolArray, ArrowBoolDtype, ) diff --git a/pandas/tests/extension/arrow/test_string.py b/pandas/tests/extension/arrow/test_string.py index 23a07b2031bf5..abd5c1f386dc5 100644 --- a/pandas/tests/extension/arrow/test_string.py +++ b/pandas/tests/extension/arrow/test_string.py @@ -4,7 +4,7 @@ pytest.importorskip("pyarrow", minversion="0.13.0") -from pandas.tests.extension.arrow.arrays import ArrowStringDtype # isort:skip +from .arrays import ArrowStringDtype # isort:skip def test_constructor_from_list(): diff --git a/pandas/tests/extension/arrow/test_timestamp.py b/pandas/tests/extension/arrow/test_timestamp.py index 819e5549d05ae..cd6f49f9a8e05 100644 --- a/pandas/tests/extension/arrow/test_timestamp.py +++ b/pandas/tests/extension/arrow/test_timestamp.py @@ -15,7 +15,7 @@ import pyarrow as pa # isort:skip -from pandas.tests.extension.arrow.arrays import ArrowExtensionArray # isort:skip +from .arrays import ArrowExtensionArray # isort:skip @register_extension_dtype diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py index 9cf3bdab40d0b..323cb843b2d74 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -41,26 +41,26 @@ class TestMyDtype(BaseDtypeTests): ``assert_series_equal`` on your base test class. """ -from pandas.tests.extension.base.casting import BaseCastingTests # noqa -from pandas.tests.extension.base.constructors import BaseConstructorsTests # noqa -from pandas.tests.extension.base.dtype import BaseDtypeTests # noqa -from pandas.tests.extension.base.getitem import BaseGetitemTests # noqa -from pandas.tests.extension.base.groupby import BaseGroupbyTests # noqa -from pandas.tests.extension.base.interface import BaseInterfaceTests # noqa -from pandas.tests.extension.base.io import BaseParsingTests # noqa -from pandas.tests.extension.base.methods import BaseMethodsTests # noqa -from pandas.tests.extension.base.missing import BaseMissingTests # noqa -from pandas.tests.extension.base.ops import ( # noqa +from .casting import BaseCastingTests # noqa +from .constructors import BaseConstructorsTests # noqa +from .dtype import BaseDtypeTests # noqa +from .getitem import BaseGetitemTests # noqa +from .groupby import BaseGroupbyTests # noqa +from .interface import BaseInterfaceTests # noqa +from .io import BaseParsingTests # noqa +from .methods import BaseMethodsTests # noqa +from .missing import BaseMissingTests # noqa +from .ops import ( # noqa BaseArithmeticOpsTests, BaseComparisonOpsTests, BaseOpsUtil, BaseUnaryOpsTests, ) -from pandas.tests.extension.base.printing import BasePrintingTests # noqa -from pandas.tests.extension.base.reduce import ( # noqa +from .printing import BasePrintingTests # noqa +from .reduce import ( # noqa BaseBooleanReduceTests, BaseNoReduceTests, BaseNumericReduceTests, ) -from pandas.tests.extension.base.reshaping import BaseReshapingTests # noqa -from pandas.tests.extension.base.setitem import BaseSetitemTests # noqa +from .reshaping import BaseReshapingTests # noqa +from .setitem import BaseSetitemTests # noqa diff --git a/pandas/tests/extension/base/casting.py b/pandas/tests/extension/base/casting.py index 0b79a5368a542..039b42210224e 100644 --- a/pandas/tests/extension/base/casting.py +++ b/pandas/tests/extension/base/casting.py @@ -3,7 +3,8 @@ import pandas as pd from pandas.core.internals import ObjectBlock -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseCastingTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/constructors.py b/pandas/tests/extension/base/constructors.py index 6f0d8d16a0224..9dbfd2a5589c0 100644 --- a/pandas/tests/extension/base/constructors.py +++ b/pandas/tests/extension/base/constructors.py @@ -3,7 +3,8 @@ import pandas as pd from pandas.core.internals import ExtensionBlock -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseConstructorsTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py index ea4443010c6a6..96145e4fb78a7 100644 --- a/pandas/tests/extension/base/dtype.py +++ b/pandas/tests/extension/base/dtype.py @@ -9,7 +9,8 @@ is_object_dtype, is_string_dtype, ) -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseDtypeTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 286ed9c736f31..bfd6da0fc864d 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -2,7 +2,8 @@ import pytest import pandas as pd -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseGetitemTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/groupby.py b/pandas/tests/extension/base/groupby.py index 30b115b9dba6f..c81304695f353 100644 --- a/pandas/tests/extension/base/groupby.py +++ b/pandas/tests/extension/base/groupby.py @@ -2,7 +2,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseGroupbyTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py index 05a28f20b956a..6a4ff68b4580f 100644 --- a/pandas/tests/extension/base/interface.py +++ b/pandas/tests/extension/base/interface.py @@ -5,7 +5,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseInterfaceTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/io.py b/pandas/tests/extension/base/io.py index a8c25db3181d0..3de752a8c682a 100644 --- a/pandas/tests/extension/base/io.py +++ b/pandas/tests/extension/base/io.py @@ -4,7 +4,8 @@ import pytest import pandas as pd -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseParsingTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index bf5e9fe009cd1..67348cfe57c2d 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -9,7 +9,8 @@ import pandas as pd import pandas._testing as tm from pandas.core.sorting import nargsort -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseMethodsTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index 0cf03533915f2..a5969ef961bab 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -2,7 +2,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseMissingTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index 2a27f670fa046..9b1681094cef5 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -8,7 +8,8 @@ import pandas as pd import pandas._testing as tm from pandas.core import ops -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseOpsUtil(BaseExtensionTests): diff --git a/pandas/tests/extension/base/printing.py b/pandas/tests/extension/base/printing.py index eab75be66080f..ad34a83c7cf71 100644 --- a/pandas/tests/extension/base/printing.py +++ b/pandas/tests/extension/base/printing.py @@ -3,7 +3,8 @@ import pytest import pandas as pd -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BasePrintingTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/reduce.py b/pandas/tests/extension/base/reduce.py index 0f7bd59411eb5..55f8aca1b8ae0 100644 --- a/pandas/tests/extension/base/reduce.py +++ b/pandas/tests/extension/base/reduce.py @@ -4,7 +4,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseReduceTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/reshaping.py b/pandas/tests/extension/base/reshaping.py index 18f6084f989dc..44e3fc1eb56d8 100644 --- a/pandas/tests/extension/base/reshaping.py +++ b/pandas/tests/extension/base/reshaping.py @@ -5,7 +5,8 @@ import pandas as pd from pandas.core.internals import ExtensionBlock -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseReshapingTests(BaseExtensionTests): diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index 16b9b8e8efdea..9ec842d801919 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -3,7 +3,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.extension.base.base import BaseExtensionTests + +from .base import BaseExtensionTests class BaseSetitemTests(BaseExtensionTests): diff --git a/pandas/tests/extension/decimal/__init__.py b/pandas/tests/extension/decimal/__init__.py index 34727b43a7b0f..ab8f8f3e91c19 100644 --- a/pandas/tests/extension/decimal/__init__.py +++ b/pandas/tests/extension/decimal/__init__.py @@ -1,4 +1,4 @@ -from pandas.tests.extension.decimal.array import ( +from .array import ( DecimalArray, DecimalDtype, make_data, diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 23b1ce250a5e5..9d4b2d230a802 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -9,7 +9,8 @@ import pandas._testing as tm from pandas.api.types import infer_dtype from pandas.tests.extension import base -from pandas.tests.extension.decimal.array import ( + +from .array import ( DecimalArray, DecimalDtype, make_data, diff --git a/pandas/tests/extension/json/__init__.py b/pandas/tests/extension/json/__init__.py index 7ebfd54a5b0d6..8de9f99d8fb06 100644 --- a/pandas/tests/extension/json/__init__.py +++ b/pandas/tests/extension/json/__init__.py @@ -1,4 +1,4 @@ -from pandas.tests.extension.json.array import ( +from .array import ( JSONArray, JSONDtype, make_data, diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index b8fa158083327..5605f343916f0 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -6,7 +6,8 @@ import pandas as pd import pandas._testing as tm from pandas.tests.extension import base -from pandas.tests.extension.json.array import ( + +from .array import ( JSONArray, JSONDtype, make_data, diff --git a/pandas/tests/extension/list/__init__.py b/pandas/tests/extension/list/__init__.py index 0f3f2f3537788..acae7322a80a8 100644 --- a/pandas/tests/extension/list/__init__.py +++ b/pandas/tests/extension/list/__init__.py @@ -1,4 +1,4 @@ -from pandas.tests.extension.list.array import ( +from .array import ( ListArray, ListDtype, make_data, diff --git a/pandas/tests/extension/list/test_list.py b/pandas/tests/extension/list/test_list.py index 295f08679c3eb..32e5207a17dc6 100644 --- a/pandas/tests/extension/list/test_list.py +++ b/pandas/tests/extension/list/test_list.py @@ -1,7 +1,8 @@ import pytest import pandas as pd -from pandas.tests.extension.list.array import ( + +from .array import ( ListArray, ListDtype, make_data, diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index 3ef3beaa9c1b1..0f235143be5d9 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -19,7 +19,8 @@ import pandas as pd import pandas._testing as tm from pandas.core.arrays.boolean import BooleanDtype -from pandas.tests.extension import base + +from . import base def make_data(): diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index 3f1f2c02c79f7..6c184256d7435 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -26,7 +26,8 @@ ) import pandas._testing as tm from pandas.api.types import CategoricalDtype -from pandas.tests.extension import base + +from . import base def make_data(): diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index 6c5963402b3d7..0ac416a2b6b6a 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -20,7 +20,8 @@ import pandas as pd from pandas.core.arrays import DatetimeArray -from pandas.tests.extension import base + +from . import base @pytest.fixture(params=["US/Central"]) diff --git a/pandas/tests/extension/test_floating.py b/pandas/tests/extension/test_floating.py index 617dfc694741e..b96717995b359 100644 --- a/pandas/tests/extension/test_floating.py +++ b/pandas/tests/extension/test_floating.py @@ -25,7 +25,8 @@ Float32Dtype, Float64Dtype, ) -from pandas.tests.extension import base + +from . import base def make_data(): diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index 2305edc1e1327..4f755ff01a5c0 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -32,7 +32,8 @@ UInt32Dtype, UInt64Dtype, ) -from pandas.tests.extension import base + +from . import base def make_data(): diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 1bc06ee4b6397..1f53916ae0007 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -20,7 +20,8 @@ from pandas import Interval from pandas.core.arrays import IntervalArray -from pandas.tests.extension import base + +from . import base def make_data(): diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 17f29e02a2883..e4812c5b3afd5 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -24,7 +24,8 @@ import pandas as pd import pandas._testing as tm from pandas.core.arrays.numpy_ import PandasArray -from pandas.tests.extension import base + +from . import base @pytest.fixture(params=["float", "object"]) diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index bbb991259ac29..ae4a287eb3a6f 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -22,7 +22,8 @@ import pandas as pd from pandas.core.arrays import PeriodArray -from pandas.tests.extension import base + +from . import base @pytest.fixture diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 067fada5edcae..bb3c25282ac80 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -28,7 +28,8 @@ from pandas import SparseDtype import pandas._testing as tm from pandas.arrays import SparseArray -from pandas.tests.extension import base + +from . import base def make_data(fill_value): diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index d0a3ef17afdbc..1e8ad22c0f7d7 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -23,7 +23,8 @@ import pandas as pd from pandas.core.arrays.string_ import StringDtype from pandas.core.arrays.string_arrow import ArrowStringDtype -from pandas.tests.extension import base + +from . import base @pytest.fixture( diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 44b6d44ee6275..f72fd2248847d 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -19,7 +19,8 @@ _MIN_ELEMENTS, NUMEXPR_INSTALLED, ) -from pandas.tests.frame.common import ( + +from .common import ( _check_mixed_float, _check_mixed_int, ) diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index 49a1dc8bbb21c..d80930050f124 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -12,7 +12,8 @@ date_range, ) import pandas._testing as tm -from pandas.tests.generic.test_generic import Generic + +from .test_generic import Generic class TestDataFrame(Generic): diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index 823ce7435f229..530515c3fc162 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -10,7 +10,8 @@ date_range, ) import pandas._testing as tm -from pandas.tests.generic.test_generic import Generic + +from .test_generic import Generic class TestSeries(Generic): diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index 4c8ab27d2c824..33fba672e9dc6 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -5,7 +5,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.indexes.common import Base + +from .common import Base class DatetimeLike(Base): diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 9399945bf1913..91933e9266703 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -714,7 +714,7 @@ def test_date_range_timezone_str_argument(self, tzstr): tm.assert_index_equal(result, expected) def test_date_range_with_fixedoffset_noname(self): - from pandas.tests.indexes.datetimes.test_timezones import fixed_off_no_name + from .test_timezones import fixed_off_no_name off = fixed_off_no_name start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 127f0432efa01..369ce352f5559 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -43,7 +43,8 @@ ensure_index, ensure_index_from_sequences, ) -from pandas.tests.indexes.common import Base + +from .common import Base class TestIndex(Base): diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 74c961418176b..e3e63814edb93 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -15,7 +15,8 @@ UInt64Index, ) import pandas._testing as tm -from pandas.tests.indexes.common import Base + +from .common import Base class TestArithmetic: diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 881e47f4f5fe2..8309bd7dc068b 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -25,7 +25,8 @@ import pandas._testing as tm from pandas.api.types import is_scalar from pandas.core.indexing import IndexingError -from pandas.tests.indexing.common import Base + +from .common import Base # We pass through the error message from numpy _slice_iloc_msg = re.escape( diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 842394ac75f3e..272788748ca09 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -23,8 +23,9 @@ timedelta_range, ) import pandas._testing as tm -from pandas.tests.indexing.common import _mklbl -from pandas.tests.indexing.test_floats import gen_obj + +from .common import _mklbl +from .test_floats import gen_obj # ------------------------------------------------------------------------ # Indexing test cases diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 55a979859a12a..b0722d1b83383 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -33,7 +33,8 @@ ) import pandas._testing as tm from pandas.api.types import is_scalar -from pandas.tests.indexing.common import Base + +from .common import Base class TestLoc(Base): diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 39611bce2b4fa..2d96912631b56 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -15,7 +15,8 @@ date_range, ) import pandas._testing as tm -from pandas.tests.indexing.common import Base + +from .common import Base class TestScalar(Base): diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 1c71666e88651..5e7d4a3e2cb75 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -20,7 +20,8 @@ Series, ) import pandas._testing as tm -from pandas.tests.io.excel import xlrd_version + +from . import xlrd_version read_ext_params = [".xls", ".xlsx", ".xlsm", ".xlsb", ".ods"] engine_params = [ diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index c0d8acf8ab562..4ceb64e1117c5 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -4,10 +4,11 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.io.excel import xlrd_version from pandas.io.excel import ExcelFile +from . import xlrd_version + xlrd = pytest.importorskip("xlrd") xlwt = pytest.importorskip("xlwt") diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index 3eebeee9788c6..b9310427887a9 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -18,7 +18,8 @@ date_range, read_hdf, ) -from pandas.tests.io.pytables.common import ( + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py index 858e38e40f017..3e28c5cd98fee 100644 --- a/pandas/tests/io/pytables/test_categorical.py +++ b/pandas/tests/io/pytables/test_categorical.py @@ -9,7 +9,8 @@ concat, read_hdf, ) -from pandas.tests.io.pytables.common import ( + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, diff --git a/pandas/tests/io/pytables/test_compat.py b/pandas/tests/io/pytables/test_compat.py index c7200385aa998..36abc665f6735 100644 --- a/pandas/tests/io/pytables/test_compat.py +++ b/pandas/tests/io/pytables/test_compat.py @@ -2,7 +2,8 @@ import pandas as pd import pandas._testing as tm -from pandas.tests.io.pytables.common import ensure_clean_path + +from .common import ensure_clean_path tables = pytest.importorskip("tables") diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py index 8e1dee5873512..20e6d212c31da 100644 --- a/pandas/tests/io/pytables/test_complex.py +++ b/pandas/tests/io/pytables/test_complex.py @@ -11,13 +11,14 @@ Series, ) import pandas._testing as tm -from pandas.tests.io.pytables.common import ( + +from pandas.io.pytables import read_hdf + +from .common import ( ensure_clean_path, ensure_clean_store, ) -from pandas.io.pytables import read_hdf - # TODO(ArrayManager) HDFStore relies on accessing the blocks pytestmark = td.skip_array_manager_not_yet_implemented diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py index 11ee5e3564634..dc623855f162b 100644 --- a/pandas/tests/io/pytables/test_errors.py +++ b/pandas/tests/io/pytables/test_errors.py @@ -16,16 +16,17 @@ date_range, read_hdf, ) -from pandas.tests.io.pytables.common import ( - ensure_clean_path, - ensure_clean_store, -) from pandas.io.pytables import ( Term, _maybe_adjust_name, ) +from .common import ( + ensure_clean_path, + ensure_clean_store, +) + pytestmark = pytest.mark.single diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py index 6340311b234f1..59eac8e063d1c 100644 --- a/pandas/tests/io/pytables/test_file_handling.py +++ b/pandas/tests/io/pytables/test_file_handling.py @@ -13,12 +13,6 @@ _testing as tm, read_hdf, ) -from pandas.tests.io.pytables.common import ( - _maybe_remove, - ensure_clean_path, - ensure_clean_store, - tables, -) from pandas.io import pytables as pytables from pandas.io.pytables import ( @@ -27,6 +21,13 @@ Term, ) +from .common import ( + _maybe_remove, + ensure_clean_path, + ensure_clean_store, + tables, +) + pytestmark = pytest.mark.single diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py index 02b79bd0fdbc1..947ece11eba83 100644 --- a/pandas/tests/io/pytables/test_keys.py +++ b/pandas/tests/io/pytables/test_keys.py @@ -5,7 +5,8 @@ HDFStore, _testing as tm, ) -from pandas.tests.io.pytables.common import ( + +from .common import ( ensure_clean_path, ensure_clean_store, tables, diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 4f8c7c84a9fcc..d8cf35cd68399 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -22,12 +22,13 @@ _testing as tm, concat, ) -from pandas.tests.io.pytables.common import ( +from pandas.util import _test_decorators as td + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, ) -from pandas.util import _test_decorators as td pytestmark = pytest.mark.single diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index f8d302a0190f8..c1e18be46b44d 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -16,14 +16,15 @@ _testing as tm, read_hdf, ) -from pandas.tests.io.pytables.common import ( +from pandas.util import _test_decorators as td + +from pandas.io.pytables import TableIterator + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, ) -from pandas.util import _test_decorators as td - -from pandas.io.pytables import TableIterator pytestmark = pytest.mark.single diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py index 16772d03c6d26..10185c799a3e8 100644 --- a/pandas/tests/io/pytables/test_retain_attributes.py +++ b/pandas/tests/io/pytables/test_retain_attributes.py @@ -11,7 +11,8 @@ date_range, read_hdf, ) -from pandas.tests.io.pytables.common import ( + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index 03d3d838a936c..6fda138ea75d5 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -20,12 +20,13 @@ bdate_range, read_hdf, ) -from pandas.tests.io.pytables.common import ( +from pandas.util import _test_decorators as td + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, ) -from pandas.util import _test_decorators as td _default_compressor = "blosc" diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py index a8f63bdc5fb2f..6ee9c7eae76a6 100644 --- a/pandas/tests/io/pytables/test_select.py +++ b/pandas/tests/io/pytables/test_select.py @@ -20,15 +20,16 @@ isna, read_hdf, ) -from pandas.tests.io.pytables.common import ( + +from pandas.io.pytables import Term + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, tables, ) -from pandas.io.pytables import Term - pytestmark = pytest.mark.single diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index ef75c86190a25..9e0a215c52911 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -25,7 +25,8 @@ timedelta_range, ) import pandas._testing as tm -from pandas.tests.io.pytables.common import ( + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, diff --git a/pandas/tests/io/pytables/test_subclass.py b/pandas/tests/io/pytables/test_subclass.py index 75b04f332e054..eb6d85cd1c0da 100644 --- a/pandas/tests/io/pytables/test_subclass.py +++ b/pandas/tests/io/pytables/test_subclass.py @@ -5,13 +5,14 @@ Series, ) import pandas._testing as tm -from pandas.tests.io.pytables.common import ensure_clean_path from pandas.io.pytables import ( HDFStore, read_hdf, ) +from .common import ensure_clean_path + class TestHDFStoreSubclass: # GH 33748 diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py index 5e42dbde4b9f1..a7b5176e7f977 100644 --- a/pandas/tests/io/pytables/test_time_series.py +++ b/pandas/tests/io/pytables/test_time_series.py @@ -8,7 +8,8 @@ Series, _testing as tm, ) -from pandas.tests.io.pytables.common import ensure_clean_store + +from .common import ensure_clean_store pytestmark = pytest.mark.single diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index f67efb4cc60be..3075c9187ff83 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -18,7 +18,8 @@ date_range, ) import pandas._testing as tm -from pandas.tests.io.pytables.common import ( + +from .common import ( _maybe_remove, ensure_clean_path, ensure_clean_store, diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 63dfbd59acd94..a83c32512580b 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -57,7 +57,7 @@ @pytest.fixture(scope="module") def current_pickle_data(): # our current version pickle data - from pandas.tests.io.generate_legacy_storage_files import create_pickle_data + from .generate_legacy_storage_files import create_pickle_data return create_pickle_data() diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 448679d562a4a..86956debeb8b9 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -16,13 +16,14 @@ timedelta_range, ) import pandas._testing as tm -from pandas.tests.plotting.common import ( + +import pandas.plotting as plotting + +from .common import ( TestPlotBase, _check_plot_works, ) -import pandas.plotting as plotting - pytestmark = pytest.mark.slow diff --git a/pandas/tests/plotting/test_common.py b/pandas/tests/plotting/test_common.py index 4674fc1bb2c18..67a132a656286 100644 --- a/pandas/tests/plotting/test_common.py +++ b/pandas/tests/plotting/test_common.py @@ -3,7 +3,8 @@ import pandas.util._test_decorators as td from pandas import DataFrame -from pandas.tests.plotting.common import ( + +from .common import ( TestPlotBase, _check_plot_works, _gen_two_subplots, diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 6e71b56e8182b..866c21c50312a 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -37,10 +37,11 @@ period_range, ) from pandas.core.indexes.timedeltas import timedelta_range -from pandas.tests.plotting.common import TestPlotBase from pandas.tseries.offsets import WeekOfMonth +from .common import TestPlotBase + pytestmark = pytest.mark.slow diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index 76320767a6b01..d10d3ee938215 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -13,7 +13,8 @@ Series, ) import pandas._testing as tm -from pandas.tests.plotting.common import TestPlotBase + +from .common import TestPlotBase pytestmark = pytest.mark.slow diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index a6e3ba71e94ab..78c059bf2cb50 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -13,7 +13,8 @@ to_datetime, ) import pandas._testing as tm -from pandas.tests.plotting.common import ( + +from .common import ( TestPlotBase, _check_plot_works, ) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 7f0d1802580b9..ba5d6fe474410 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -10,13 +10,14 @@ Series, ) import pandas._testing as tm -from pandas.tests.plotting.common import ( + +import pandas.plotting as plotting + +from .common import ( TestPlotBase, _check_plot_works, ) -import pandas.plotting as plotting - pytestmark = pytest.mark.slow diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 59b0cc99d94fb..9511d470ceac7 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -16,13 +16,14 @@ date_range, ) import pandas._testing as tm -from pandas.tests.plotting.common import ( + +import pandas.plotting as plotting + +from .common import ( TestPlotBase, _check_plot_works, ) -import pandas.plotting as plotting - pytestmark = pytest.mark.slow diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index e5499c44be7d7..0a415fe2d7868 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -13,7 +13,8 @@ merge, ) import pandas._testing as tm -from pandas.tests.reshape.merge.test_merge import ( + +from .test_merge import ( NGROUPS, N, get_test_data, diff --git a/pandas/tests/strings/test_cat.py b/pandas/tests/strings/test_cat.py index cdaccf0dad8e6..b2e6aaa927c96 100644 --- a/pandas/tests/strings/test_cat.py +++ b/pandas/tests/strings/test_cat.py @@ -10,7 +10,8 @@ _testing as tm, concat, ) -from pandas.tests.strings.test_strings import assert_series_or_index_equal + +from .test_strings import assert_series_or_index_equal @pytest.mark.parametrize("other", [None, Series, Index]) diff --git a/pandas/tests/tseries/offsets/test_business_day.py b/pandas/tests/tseries/offsets/test_business_day.py index 26df051ef928f..0348212e1d42e 100644 --- a/pandas/tests/tseries/offsets/test_business_day.py +++ b/pandas/tests/tseries/offsets/test_business_day.py @@ -23,15 +23,16 @@ _testing as tm, read_pickle, ) -from pandas.tests.tseries.offsets.common import ( + +from pandas.tseries import offsets as offsets +from pandas.tseries.holiday import USFederalHolidayCalendar + +from .common import ( Base, assert_is_on_offset, assert_offset_equal, ) -from pandas.tests.tseries.offsets.test_offsets import _ApplyCases - -from pandas.tseries import offsets as offsets -from pandas.tseries.holiday import USFederalHolidayCalendar +from .test_offsets import _ApplyCases class TestBusinessDay(Base): diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py index 72b939b79c321..33b9723922e4a 100644 --- a/pandas/tests/tseries/offsets/test_business_hour.py +++ b/pandas/tests/tseries/offsets/test_business_hour.py @@ -23,7 +23,8 @@ _testing as tm, date_range, ) -from pandas.tests.tseries.offsets.common import ( + +from .common import ( Base, assert_offset_equal, ) diff --git a/pandas/tests/tseries/offsets/test_custom_business_hour.py b/pandas/tests/tseries/offsets/test_custom_business_hour.py index 07270008adbd2..e931e359fe5a8 100644 --- a/pandas/tests/tseries/offsets/test_custom_business_hour.py +++ b/pandas/tests/tseries/offsets/test_custom_business_hour.py @@ -14,7 +14,8 @@ ) import pandas._testing as tm -from pandas.tests.tseries.offsets.common import ( + +from .common import ( Base, assert_offset_equal, ) diff --git a/pandas/tests/tseries/offsets/test_dst.py b/pandas/tests/tseries/offsets/test_dst.py index 0ae94b6b57640..2ad146fdcf50a 100644 --- a/pandas/tests/tseries/offsets/test_dst.py +++ b/pandas/tests/tseries/offsets/test_dst.py @@ -28,7 +28,7 @@ YearEnd, ) -from pandas.tests.tseries.offsets.test_offsets import get_utc_offset_hours +from .test_offsets import get_utc_offset_hours class TestDST: diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py index 1eee9e611e0f1..a5881961b6bb3 100644 --- a/pandas/tests/tseries/offsets/test_fiscal.py +++ b/pandas/tests/tseries/offsets/test_fiscal.py @@ -10,12 +10,6 @@ from pandas import Timestamp import pandas._testing as tm -from pandas.tests.tseries.offsets.common import ( - Base, - WeekDay, - assert_is_on_offset, - assert_offset_equal, -) from pandas.tseries.frequencies import get_offset from pandas.tseries.offsets import ( @@ -23,6 +17,13 @@ FY5253Quarter, ) +from .common import ( + Base, + WeekDay, + assert_is_on_offset, + assert_offset_equal, +) + def makeFY5253LastOfMonthQuarter(*args, **kwds): return FY5253Quarter(*args, variation="last", **kwds) diff --git a/pandas/tests/tseries/offsets/test_month.py b/pandas/tests/tseries/offsets/test_month.py index b9c0cfe75fe7e..b35815e145f77 100644 --- a/pandas/tests/tseries/offsets/test_month.py +++ b/pandas/tests/tseries/offsets/test_month.py @@ -24,15 +24,16 @@ _testing as tm, date_range, ) -from pandas.tests.tseries.offsets.common import ( + +from pandas.tseries import offsets as offsets +from pandas.tseries.holiday import USFederalHolidayCalendar + +from .common import ( Base, assert_is_on_offset, assert_offset_equal, ) -from pandas.tests.tseries.offsets.test_offsets import _ApplyCases - -from pandas.tseries import offsets as offsets -from pandas.tseries.holiday import USFederalHolidayCalendar +from .test_offsets import _ApplyCases class CustomBusinessMonthBase: diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 50bfc21637407..f4d502f63deb2 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -31,11 +31,6 @@ from pandas import DatetimeIndex import pandas._testing as tm -from pandas.tests.tseries.offsets.common import ( - Base, - WeekDay, - assert_offset_equal, -) import pandas.tseries.offsets as offsets from pandas.tseries.offsets import ( @@ -60,6 +55,12 @@ WeekOfMonth, ) +from .common import ( + Base, + WeekDay, + assert_offset_equal, +) + _ApplyCases = List[Tuple[BaseOffset, Dict[datetime, datetime]]] diff --git a/pandas/tests/tseries/offsets/test_ticks.py b/pandas/tests/tseries/offsets/test_ticks.py index 52a2f3aeee850..19e89081f5953 100644 --- a/pandas/tests/tseries/offsets/test_ticks.py +++ b/pandas/tests/tseries/offsets/test_ticks.py @@ -23,7 +23,6 @@ Timestamp, ) import pandas._testing as tm -from pandas.tests.tseries.offsets.common import assert_offset_equal from pandas.tseries import offsets from pandas.tseries.offsets import ( @@ -35,6 +34,8 @@ Second, ) +from .common import assert_offset_equal + # --------------------------------------------------------------------- # Test Helpers diff --git a/pandas/tests/tseries/offsets/test_week.py b/pandas/tests/tseries/offsets/test_week.py index b46a36e00f2da..e78ac29dc8b60 100644 --- a/pandas/tests/tseries/offsets/test_week.py +++ b/pandas/tests/tseries/offsets/test_week.py @@ -15,7 +15,7 @@ WeekOfMonth, ) -from pandas.tests.tseries.offsets.common import ( +from .common import ( Base, WeekDay, assert_is_on_offset, diff --git a/pandas/tests/tseries/offsets/test_yqm_offsets.py b/pandas/tests/tseries/offsets/test_yqm_offsets.py index 260f7368123a4..12f9dd3ac732c 100644 --- a/pandas/tests/tseries/offsets/test_yqm_offsets.py +++ b/pandas/tests/tseries/offsets/test_yqm_offsets.py @@ -7,11 +7,6 @@ import pandas as pd from pandas import Timestamp -from pandas.tests.tseries.offsets.common import ( - Base, - assert_is_on_offset, - assert_offset_equal, -) from pandas.tseries.offsets import ( BMonthBegin, @@ -28,6 +23,12 @@ YearEnd, ) +from .common import ( + Base, + assert_is_on_offset, + assert_offset_equal, +) + # -------------------------------------------------------------------- # Misc diff --git a/pandas/tseries/api.py b/pandas/tseries/api.py index 2094791ecdc60..1d5ebf3e9729f 100644 --- a/pandas/tseries/api.py +++ b/pandas/tseries/api.py @@ -4,5 +4,6 @@ # flake8: noqa -from pandas.tseries.frequencies import infer_freq import pandas.tseries.offsets as offsets + +from .frequencies import infer_freq diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index ce303928dc8ee..3b42027d039c5 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -27,7 +27,7 @@ date_range, ) -from pandas.tseries.offsets import ( +from .offsets import ( Day, Easter, ) diff --git a/pandas/util/__init__.py b/pandas/util/__init__.py index 35a88a802003e..35c8bc546f70a 100644 --- a/pandas/util/__init__.py +++ b/pandas/util/__init__.py @@ -1,14 +1,14 @@ -from pandas.util._decorators import ( # noqa - Appender, - Substitution, - cache_readonly, -) - from pandas.core.util.hashing import ( # noqa hash_array, hash_pandas_object, ) +from ._decorators import ( # noqa + Appender, + Substitution, + cache_readonly, +) + def __getattr__(name): if name == "testing":
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them xref [this comment](https://github.com/pandas-dev/pandas/pull/39561#discussion_r575644482): > > more generally, i like relative imports for same-directory as it clarified dependency structure > > +1, I also find this helpful. I think it should certainly be doable to have a check that relative imports are never outside the local directory @jorisvandenbossche @jbrockmendel is this what you had in mind? Like this, imports in the same folder are relative, and those outside are absolute. So, for example, in `pandas/_testing/_io.py`: - `from pandas.io.common import urlopen` stays absolute - `from pandas._testing.contexts import ensure_clean` becomes `from .contexts import ensure_clean`
https://api.github.com/repos/pandas-dev/pandas/pulls/39902
2021-02-19T08:54:25Z
2021-02-19T12:33:16Z
null
2021-02-19T12:33:16Z
TST: unnecessary check_stacklevel=False
diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 71804bded3e44..7b6cc9412e03d 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -59,5 +59,5 @@ def test_types(self): def test_deprecated_from_api_types(self): for t in self.deprecated: - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): getattr(types, t)(1) diff --git a/pandas/tests/apply/test_frame_transform.py b/pandas/tests/apply/test_frame_transform.py index 6cee8b8a4b440..7718ec5215499 100644 --- a/pandas/tests/apply/test_frame_transform.py +++ b/pandas/tests/apply/test_frame_transform.py @@ -206,7 +206,7 @@ def test_transform_bad_dtype(op, frame_or_series): # tshift is deprecated warn = None if op != "tshift" else FutureWarning - with tm.assert_produces_warning(warn, check_stacklevel=False): + with tm.assert_produces_warning(warn): with pytest.raises(ValueError, match=msg): obj.transform(op) with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index a5522e503c7f4..2b689364c5002 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -724,7 +724,7 @@ def test_astype_nansafe(val, typ): msg = "Cannot convert NaT values to integer" with pytest.raises(ValueError, match=msg): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): # datetimelike astype(int64) deprecated astype_nansafe(arr, dtype=typ) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 4da9ed76844af..cb60de9695568 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -295,7 +295,7 @@ def test_getitem_boolean( # we are producing a warning that since the passed boolean # key is not the same as the given index, we will reindex # not sure this is really necessary - with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + with tm.assert_produces_warning(UserWarning): indexer_obj = indexer_obj.reindex(datetime_frame.index[::-1]) subframe_obj = datetime_frame[indexer_obj] tm.assert_frame_equal(subframe_obj, subframe) diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py index 11e83a3d94151..26c6010c753cc 100644 --- a/pandas/tests/frame/methods/test_join.py +++ b/pandas/tests/frame/methods/test_join.py @@ -227,7 +227,7 @@ def test_suppress_future_warning_with_sort_kw(sort_kw): if sort_kw is False: expected = expected.reindex(index=["c", "a", "b"]) - with tm.assert_produces_warning(None, check_stacklevel=False): + with tm.assert_produces_warning(None): result = a.join([b, c], how="outer", sort=sort_kw) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 24ff20872baef..eaea22df3adfe 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -845,7 +845,7 @@ def test_sort_column_level_and_index_label( if len(levels) > 1: # Accessing multi-level columns that are not lexsorted raises a # performance warning - with tm.assert_produces_warning(PerformanceWarning, check_stacklevel=False): + with tm.assert_produces_warning(PerformanceWarning): tm.assert_frame_equal(result, expected) else: tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index e85b399e69874..3595da61bda11 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -669,7 +669,7 @@ def test_mode_sortwarning(self): df = DataFrame({"A": [np.nan, np.nan, "a", "a"]}) expected = DataFrame({"A": ["a", np.nan]}) - with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + with tm.assert_produces_warning(UserWarning): result = df.mode(dropna=False) result = result.sort_values(by="A").reset_index(drop=True) diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index c9c86f9eebde9..60fa8f1a0c083 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -33,7 +33,7 @@ def test_hash_error(index): def test_copy_dtype_deprecated(index): # GH#35853 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): index.copy(dtype=object) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index efd99df9a5e4f..32f30c1646a2b 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -96,7 +96,7 @@ def test_getitem_ndarray_3d(self, index, frame_or_series, indexer_sli): potential_errors = (IndexError, ValueError, NotImplementedError) with pytest.raises(potential_errors, match=msg): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): idxr[nd3] def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli): diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index 76bc188afdd1f..66c238bbd0962 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -112,7 +112,7 @@ def test_compression_warning(compression_only): ) with tm.ensure_clean() as path: with icom.get_handle(path, "w", compression=compression_only) as handles: - with tm.assert_produces_warning(RuntimeWarning, check_stacklevel=False): + with tm.assert_produces_warning(RuntimeWarning): df.to_csv(handles.handle, compression=compression_only) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 9de0422917e7b..decff32baa970 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -1420,7 +1420,7 @@ def test_mode_sortwarning(self): expected = Series(["foo", np.nan]) s = Series([1, "foo", "foo", np.nan, np.nan]) - with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + with tm.assert_produces_warning(UserWarning): result = s.mode(dropna=False) result = result.sort_values().reset_index(drop=True) diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 6bd794b1933a2..54f3f21dc9f6f 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -507,7 +507,7 @@ def test_to_pydatetime_nonzero_nano(self): ts = Timestamp("2011-01-01 9:00:00.123456789") # Warn the user of data loss (nanoseconds). - with tm.assert_produces_warning(UserWarning, check_stacklevel=False): + with tm.assert_produces_warning(UserWarning): expected = datetime(2011, 1, 1, 9, 0, 0, 123456) result = ts.to_pydatetime() assert result == expected @@ -541,13 +541,13 @@ def test_to_datetime_bijective(self): # Ensure that converting to datetime and back only loses precision # by going from nanoseconds to microseconds. exp_warning = None if Timestamp.max.nanosecond == 0 else UserWarning - with tm.assert_produces_warning(exp_warning, check_stacklevel=False): + with tm.assert_produces_warning(exp_warning): pydt_max = Timestamp.max.to_pydatetime() assert Timestamp(pydt_max).value / 1000 == Timestamp.max.value / 1000 exp_warning = None if Timestamp.min.nanosecond == 0 else UserWarning - with tm.assert_produces_warning(exp_warning, check_stacklevel=False): + with tm.assert_produces_warning(exp_warning): pydt_min = Timestamp.min.to_pydatetime() # The next assertion can be enabled once GH#39221 is merged diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index d14261fef67a6..a3785518c860d 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -91,7 +91,7 @@ def test_astype_empty_constructor_equality(self, dtype): "m", # Generic timestamps raise a ValueError. Already tested. ): init_empty = Series([], dtype=dtype) - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): as_type_empty = Series([]).astype(dtype) tm.assert_series_equal(init_empty, as_type_empty) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 3f3a3af658969..69dd7d083119f 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -266,7 +266,7 @@ def test_replace_with_empty_dictlike(self): s = pd.Series(list("abcd")) tm.assert_series_equal(s, s.replace({})) - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): empty_series = pd.Series([]) tm.assert_series_equal(s, s.replace(empty_series)) @@ -457,6 +457,6 @@ def test_str_replace_regex_default_raises_warning(self, pattern): msg = r"The default value of regex will change from True to False" if len(pattern) == 1: msg += r".*single character regular expressions.*not.*literal strings" - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w: + with tm.assert_produces_warning(FutureWarning) as w: s.str.replace(pattern, "") assert re.match(msg, str(w[0].message)) diff --git a/pandas/tests/series/test_subclass.py b/pandas/tests/series/test_subclass.py index 86330b7cc6993..da5faeab49a8d 100644 --- a/pandas/tests/series/test_subclass.py +++ b/pandas/tests/series/test_subclass.py @@ -35,7 +35,7 @@ def test_subclass_unstack(self): tm.assert_frame_equal(res, exp) def test_subclass_empty_repr(self): - with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): + with tm.assert_produces_warning(DeprecationWarning): sub_series = tm.SubclassedSeries() assert "SubclassedSeries" in repr(sub_series) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 50bfc21637407..d36bea72908a3 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -194,7 +194,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, normalize=Fals exp_warning = UserWarning # test nanosecond is preserved - with tm.assert_produces_warning(exp_warning, check_stacklevel=False): + with tm.assert_produces_warning(exp_warning): result = func(ts) assert isinstance(result, Timestamp) if normalize is False: @@ -231,7 +231,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, normalize=Fals exp_warning = UserWarning # test nanosecond is preserved - with tm.assert_produces_warning(exp_warning, check_stacklevel=False): + with tm.assert_produces_warning(exp_warning): result = func(ts) assert isinstance(result, Timestamp) if normalize is False:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39901
2021-02-19T04:17:04Z
2021-02-19T14:22:19Z
2021-02-19T14:22:18Z
2021-02-19T15:45:38Z
REF: consolidate paths for astype
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 5dd55ff0f1fa2..8e1d7e607fb8a 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -60,6 +60,7 @@ Substitution, cache_readonly, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -397,12 +398,13 @@ def astype(self, dtype, copy=True): elif is_integer_dtype(dtype): # we deliberately ignore int32 vs. int64 here. # See https://github.com/pandas-dev/pandas/issues/24381 for more. + level = find_stack_level() warnings.warn( f"casting {self.dtype} values to int64 with .astype(...) is " "deprecated and will raise in a future version. " "Use .view(...) instead.", FutureWarning, - stacklevel=3, + stacklevel=level, ) values = self.asi8 diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 05184ea02e7a2..3982a7deca2bb 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -616,6 +616,10 @@ def astype(self, dtype, copy=True): elif is_datetime64_ns_dtype(dtype): return astype_dt64_to_dt64tz(self, dtype, copy, via_utc=False) + elif self.tz is None and is_datetime64_dtype(dtype) and dtype != self.dtype: + # unit conversion e.g. datetime64[s] + return self._data.astype(dtype) + elif is_period_dtype(dtype): return self.to_period(freq=dtype.freq) return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 4150ec745bd2e..0097959245686 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -309,6 +309,10 @@ def astype(self, dtype, copy=True): return self return self.copy() + if isinstance(dtype, np.dtype) and dtype.kind == "M" and dtype != "M8[ns]": + # For now Datetime supports this by unwrapping ndarray, but DTI doesn't + raise TypeError(f"Cannot cast {type(self._data).__name__} to dtype") + new_values = self._data.astype(dtype, copy=copy) # pass copy=False because any copying will be done in the diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2eb5be01c932c..1377928f71915 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -673,6 +673,18 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike: values = self.values + if values.dtype.kind in ["m", "M"]: + values = self.array_values() + + if ( + values.dtype.kind in ["m", "M"] + and dtype.kind in ["i", "u"] + and isinstance(dtype, np.dtype) + and dtype.itemsize != 8 + ): + # TODO(2.0) remove special case once deprecation on DTA/TDA is enforced + msg = rf"cannot astype a datetimelike from [{values.dtype}] to [{dtype}]" + raise TypeError(msg) if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype): return astype_dt64_to_dt64tz(values, dtype, copy, via_utc=True) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 46f5a20f38941..35e958ff3a2b1 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -432,19 +432,11 @@ def test_astype_to_incorrect_datetimelike(self, unit): other = f"m8[{unit}]" df = DataFrame(np.array([[1, 2, 3]], dtype=dtype)) - msg = ( - fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to " - fr"\[timedelta64\[{unit}\]\]" - fr"|(Cannot cast DatetimeArray to dtype timedelta64\[{unit}\])" - ) + msg = fr"Cannot cast DatetimeArray to dtype timedelta64\[{unit}\]" with pytest.raises(TypeError, match=msg): df.astype(other) - msg = ( - fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to " - fr"\[datetime64\[{unit}\]\]" - fr"|(Cannot cast TimedeltaArray to dtype datetime64\[{unit}\])" - ) + msg = 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) diff --git a/pandas/tests/indexes/datetimes/methods/test_astype.py b/pandas/tests/indexes/datetimes/methods/test_astype.py index bed7cb9b54eba..8eb0e086ec3f7 100644 --- a/pandas/tests/indexes/datetimes/methods/test_astype.py +++ b/pandas/tests/indexes/datetimes/methods/test_astype.py @@ -29,7 +29,7 @@ def test_astype(self): ) tm.assert_index_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = idx.astype(int) expected = Int64Index( [1463356800000000000] + [-9223372036854775808] * 3, @@ -39,7 +39,7 @@ def test_astype(self): tm.assert_index_equal(result, expected) rng = date_range("1/1/2000", periods=10, name="idx") - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = rng.astype("i8") tm.assert_index_equal(result, Index(rng.asi8, name="idx")) tm.assert_numpy_array_equal(result.values, rng.asi8) @@ -50,7 +50,7 @@ def test_astype_uint(self): np.array([946684800000000000, 946771200000000000], dtype="uint64"), name="idx", ) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): tm.assert_index_equal(arr.astype("uint64"), expected) tm.assert_index_equal(arr.astype("uint32"), expected) diff --git a/pandas/tests/indexes/period/methods/test_astype.py b/pandas/tests/indexes/period/methods/test_astype.py index 943b2605363c7..73439d349bebd 100644 --- a/pandas/tests/indexes/period/methods/test_astype.py +++ b/pandas/tests/indexes/period/methods/test_astype.py @@ -37,7 +37,7 @@ def test_astype_conversion(self): ) tm.assert_index_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = idx.astype(np.int64) expected = Int64Index( [16937] + [-9223372036854775808] * 3, dtype=np.int64, name="idx" @@ -49,7 +49,7 @@ def test_astype_conversion(self): tm.assert_index_equal(result, expected) idx = period_range("1990", "2009", freq="A", name="idx") - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = idx.astype("i8") tm.assert_index_equal(result, Index(idx.asi8, name="idx")) tm.assert_numpy_array_equal(result.values, idx.asi8) @@ -57,7 +57,7 @@ def test_astype_conversion(self): def test_astype_uint(self): arr = period_range("2000", periods=2, name="idx") expected = UInt64Index(np.array([10957, 10958], dtype="uint64"), name="idx") - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): tm.assert_index_equal(arr.astype("uint64"), expected) tm.assert_index_equal(arr.astype("uint32"), expected) diff --git a/pandas/tests/indexes/timedeltas/methods/test_astype.py b/pandas/tests/indexes/timedeltas/methods/test_astype.py index a849ffa98324c..c2c7a1f32ae6e 100644 --- a/pandas/tests/indexes/timedeltas/methods/test_astype.py +++ b/pandas/tests/indexes/timedeltas/methods/test_astype.py @@ -55,7 +55,7 @@ def test_astype(self): ) tm.assert_index_equal(result, expected) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = idx.astype(int) expected = Int64Index( [100000000000000] + [-9223372036854775808] * 3, dtype=np.int64, name="idx" @@ -67,7 +67,7 @@ def test_astype(self): tm.assert_index_equal(result, expected) rng = timedelta_range("1 days", periods=10) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): result = rng.astype("i8") tm.assert_index_equal(result, Index(rng.asi8)) tm.assert_numpy_array_equal(rng.asi8, result.values) @@ -77,7 +77,7 @@ def test_astype_uint(self): expected = pd.UInt64Index( np.array([3600000000000, 90000000000000], dtype="uint64") ) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + with tm.assert_produces_warning(FutureWarning): tm.assert_index_equal(arr.astype("uint64"), expected) tm.assert_index_equal(arr.astype("uint32"), expected) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 1daeee8645f2e..6cd2a1dd180c1 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1318,7 +1318,7 @@ def test_constructor_dtype_timedelta64(self): td.astype("int64") # invalid casting - msg = r"cannot astype a timedelta from \[timedelta64\[ns\]\] to \[int32\]" + msg = r"cannot astype a datetimelike from \[timedelta64\[ns\]\] to \[int32\]" with pytest.raises(TypeError, match=msg): td.astype("int32")
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39900
2021-02-19T04:15:49Z
2021-02-19T18:32:12Z
2021-02-19T18:32:12Z
2021-02-19T18:35:41Z
TYP: indexes/base.py
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 40533cdd554b3..50d016ce211d7 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -907,7 +907,7 @@ def value_counts_arraylike(values, dropna: bool): return keys, counts -def duplicated(values: ArrayLike, keep: str = "first") -> np.ndarray: +def duplicated(values: ArrayLike, keep: Union[str, bool] = "first") -> np.ndarray: """ Return boolean ndarray denoting duplicate values. diff --git a/pandas/core/base.py b/pandas/core/base.py index fd40e0467720d..9b2efeff76926 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1316,5 +1316,5 @@ def drop_duplicates(self, keep="first"): # error: Value of type "IndexOpsMixin" is not indexable return self[~duplicated] # type: ignore[index] - def duplicated(self, keep="first"): + def duplicated(self, keep: Union[str, bool] = "first") -> np.ndarray: return duplicated(self._values, keep=keep) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 71095b8f4113a..64b41c8614049 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -17,6 +17,7 @@ Sequence, Set, Tuple, + Type, TypeVar, Union, cast, @@ -47,6 +48,7 @@ Dtype, DtypeObj, Shape, + T, final, ) from pandas.compat.numpy import function as nv @@ -161,6 +163,7 @@ if TYPE_CHECKING: from pandas import ( CategoricalIndex, + DataFrame, IntervalIndex, MultiIndex, RangeIndex, @@ -278,16 +281,22 @@ class Index(IndexOpsMixin, PandasObject): # for why we need to wrap these instead of making them class attributes # Moreover, cython will choose the appropriate-dtyped sub-function # given the dtypes of the passed arguments - def _left_indexer_unique(self, left, right): + def _left_indexer_unique(self, left: np.ndarray, right: np.ndarray) -> np.ndarray: return libjoin.left_join_indexer_unique(left, right) - def _left_indexer(self, left, right): + def _left_indexer( + self, left: np.ndarray, right: np.ndarray + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: return libjoin.left_join_indexer(left, right) - def _inner_indexer(self, left, right): + def _inner_indexer( + self, left: np.ndarray, right: np.ndarray + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: return libjoin.inner_join_indexer(left, right) - def _outer_indexer(self, left, right): + def _outer_indexer( + self, left: np.ndarray, right: np.ndarray + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: return libjoin.outer_join_indexer(left, right) _typ = "index" @@ -548,7 +557,7 @@ def asi8(self): return None @classmethod - def _simple_new(cls, values, name: Hashable = None): + def _simple_new(cls: Type[_IndexT], values, name: Hashable = None) -> _IndexT: """ We require that we have a dtype compat for the values. If we are passed a non-dtype compat, then coerce using the constructor. @@ -571,11 +580,11 @@ def _simple_new(cls, values, name: Hashable = None): return result @cache_readonly - def _constructor(self): + def _constructor(self: _IndexT) -> Type[_IndexT]: return type(self) @final - def _maybe_check_unique(self): + def _maybe_check_unique(self) -> None: """ Check that an Index has no duplicates. @@ -626,13 +635,13 @@ def _format_duplicate_message(self): # Index Internals Methods @final - def _get_attributes_dict(self): + def _get_attributes_dict(self) -> Dict[str_t, Any]: """ Return an attributes dict for my class. """ return {k: getattr(self, k, None) for k in self._attributes} - def _shallow_copy(self, values, name: Hashable = no_default): + def _shallow_copy(self: _IndexT, values, name: Hashable = no_default) -> _IndexT: """ Create a new Index with the same class as the caller, don't copy the data, use the same object attributes with passed in attributes taking @@ -706,11 +715,11 @@ def _reset_identity(self) -> None: self._id = _Identity(object()) @final - def _cleanup(self): + def _cleanup(self) -> None: self._engine.clear_mapping() @cache_readonly - def _engine(self): + def _engine(self) -> libindex.ObjectEngine: # property, for now, slow to look up # to avoid a reference cycle, bind `target_values` to a local variable, so @@ -1243,7 +1252,7 @@ def to_flat_index(self): """ return self - def to_series(self, index=None, name=None): + def to_series(self, index=None, name: Hashable = None) -> Series: """ Create a Series with both index and values equal to the index keys. @@ -1306,7 +1315,7 @@ def to_series(self, index=None, name=None): return Series(self._values.copy(), index=index, name=name) - def to_frame(self, index: bool = True, name=None): + def to_frame(self, index: bool = True, name=None) -> DataFrame: """ Create a DataFrame with a column containing the Index. @@ -1421,10 +1430,10 @@ def _validate_names( return new_names - def _get_names(self): + def _get_names(self) -> FrozenList: return FrozenList((self.name,)) - def _set_names(self, values, level=None): + def _set_names(self, values, level=None) -> None: """ Set new names on index. Each name has to be a hashable type. @@ -1625,14 +1634,14 @@ def nlevels(self) -> int: """ return 1 - def _sort_levels_monotonic(self): + def _sort_levels_monotonic(self: _IndexT) -> _IndexT: """ Compat with MultiIndex. """ return self @final - def _validate_index_level(self, level): + def _validate_index_level(self, level) -> None: """ Validate index level. @@ -2369,7 +2378,7 @@ def hasnans(self) -> bool: return False @final - def isna(self): + def isna(self) -> np.ndarray: """ Detect missing values. @@ -2427,7 +2436,7 @@ def isna(self): isnull = isna @final - def notna(self): + def notna(self) -> np.ndarray: """ Detect existing (non-missing) values. @@ -2505,7 +2514,7 @@ def fillna(self, value=None, downcast=None): return Index(result, name=self.name) return self._view() - def dropna(self, how="any"): + def dropna(self: _IndexT, how: str_t = "any") -> _IndexT: """ Return Index without NA/NaN values. @@ -2530,7 +2539,7 @@ def dropna(self, how="any"): # -------------------------------------------------------------------- # Uniqueness Methods - def unique(self, level=None): + def unique(self: _IndexT, level: Optional[Hashable] = None) -> _IndexT: """ Return unique values in the index. @@ -2538,12 +2547,13 @@ def unique(self, level=None): Parameters ---------- - level : int or str, optional, default None + level : int or hashable, optional Only return values from specified level (for MultiIndex). + If int, gets the level by integer position, else by level name. Returns ------- - Index without duplicates + Index See Also -------- @@ -2560,7 +2570,7 @@ def unique(self, level=None): return self._shallow_copy(result) @final - def drop_duplicates(self, keep="first"): + def drop_duplicates(self: _IndexT, keep: Union[str_t, bool] = "first") -> _IndexT: """ Return Index with duplicate values removed. @@ -2611,7 +2621,7 @@ def drop_duplicates(self, keep="first"): return super().drop_duplicates(keep=keep) - def duplicated(self, keep="first"): + def duplicated(self, keep: Union[str_t, bool] = "first") -> np.ndarray: """ Indicate duplicate index values. @@ -3197,12 +3207,12 @@ def symmetric_difference(self, other, result_name=None, sort=None): return Index(the_diff, name=result_name) @final - def _assert_can_do_setop(self, other): + def _assert_can_do_setop(self, other) -> bool: if not is_list_like(other): raise TypeError("Input must be Index or array-like") return True - def _convert_can_do_setop(self, other): + def _convert_can_do_setop(self, other) -> Tuple[Index, Hashable]: if not isinstance(other, Index): other = Index(other, name=self.name) result_name = self.name @@ -3385,7 +3395,7 @@ def _get_indexer( return ensure_platform_int(indexer) @final - def _check_indexing_method(self, method): + def _check_indexing_method(self, method: Optional[str_t]) -> None: """ Raise if we have a get_indexer `method` that is not supported or valid. """ @@ -3403,7 +3413,9 @@ def _check_indexing_method(self, method): raise ValueError("Invalid fill method") - def _convert_tolerance(self, tolerance, target): + def _convert_tolerance( + self, tolerance, target: Union[np.ndarray, Index] + ) -> np.ndarray: # override this method on subclasses tolerance = np.asarray(tolerance) if target.size != tolerance.size and tolerance.size > 1: @@ -3506,7 +3518,7 @@ def _filter_indexer_tolerance( # -------------------------------------------------------------------- # Indexer Conversion Methods - def _get_partial_string_timestamp_match_key(self, key): + def _get_partial_string_timestamp_match_key(self, key: T) -> T: """ Translate any partial string timestamp matches in key, returning the new key. @@ -3517,7 +3529,7 @@ def _get_partial_string_timestamp_match_key(self, key): return key @final - def _validate_positional_slice(self, key: slice): + def _validate_positional_slice(self, key: slice) -> None: """ For positional indexing, a slice must have either int or None for each of start, stop, and step. @@ -3618,7 +3630,7 @@ def _convert_listlike_indexer(self, keyarr): indexer = self._convert_list_indexer(keyarr) return indexer, keyarr - def _convert_arr_indexer(self, keyarr): + def _convert_arr_indexer(self, keyarr) -> np.ndarray: """ Convert an array-like indexer to the appropriate dtype. @@ -3663,13 +3675,13 @@ def _invalid_indexer(self, form: str_t, key) -> TypeError: # Reindex Methods @final - def _can_reindex(self, indexer): + def _validate_can_reindex(self, indexer: np.ndarray) -> None: """ Check if we are allowing reindexing with this particular indexer. Parameters ---------- - indexer : an integer indexer + indexer : an integer ndarray Raises ------ @@ -6192,7 +6204,7 @@ def trim_front(strings: List[str]) -> List[str]: return strings -def _validate_join_method(method: str): +def _validate_join_method(method: str) -> None: if method not in ["left", "right", "inner", "outer"]: raise ValueError(f"do not recognize join method {method}") @@ -6404,7 +6416,7 @@ def get_unanimous_names(*indexes: Index) -> Tuple[Hashable, ...]: return names -def unpack_nested_dtype(other: Index) -> Index: +def unpack_nested_dtype(other: _IndexT) -> _IndexT: """ When checking if our dtype is comparable with another, we need to unpack CategoricalDtype to look at its categories.dtype. diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 7ef81b0947a22..39a15a8b54a92 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1109,7 +1109,7 @@ def _engine(self): return MultiIndexUIntEngine(self.levels, self.codes, offsets) @property - def _constructor(self): + def _constructor(self) -> Callable[..., MultiIndex]: return type(self).from_tuples @doc(Index._shallow_copy) diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index bd9a92a657991..a0f546a6bd748 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -10,6 +10,7 @@ List, Optional, Tuple, + Type, ) import warnings @@ -171,7 +172,7 @@ def _simple_new(cls, values: range, name: Hashable = None) -> RangeIndex: # -------------------------------------------------------------------- @cache_readonly - def _constructor(self): + def _constructor(self) -> Type[Int64Index]: """ return the class to use for construction """ return Int64Index diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 0e52ebf69137c..e09a434170780 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -802,7 +802,7 @@ def _reindex_indexer( # some axes don't allow reindexing with dups if not allow_dups: - self._axes[axis]._can_reindex(indexer) + self._axes[axis]._validate_can_reindex(indexer) # if axis >= self.ndim: # raise IndexError("Requested axis not found in manager") diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b3f0466f236b6..f72b288adf348 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1245,7 +1245,7 @@ def reindex_indexer( # some axes don't allow reindexing with dups if not allow_dups: - self.axes[axis]._can_reindex(indexer) + self.axes[axis]._validate_can_reindex(indexer) if axis >= self.ndim: raise IndexError("Requested axis not found in manager")
Add types to `pandas/core/indexes/base.py`.
https://api.github.com/repos/pandas-dev/pandas/pulls/39897
2021-02-18T22:17:10Z
2021-02-21T18:02:11Z
2021-02-21T18:02:11Z
2021-02-21T21:52:10Z
REF: share fillna TDBlock/DTBlock
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ae019c2f853a1..7b910824c208d 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2048,6 +2048,21 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Blo new_values = values.shift(periods, fill_value=fill_value, axis=axis) return [self.make_block_same_class(new_values)] + def fillna( + self, value, limit=None, inplace: bool = False, downcast=None + ) -> List[Block]: + + if not self._can_hold_element(value) and self.dtype.kind != "m": + # We support filling a DatetimeTZ with a `value` whose timezone + # is different by coercing to object. + # TODO: don't special-case td64 + return self.astype(object).fillna(value, limit, inplace, downcast) + + values = self.array_values() + values = values if inplace else values.copy() + new_values = values.fillna(value=value, limit=limit) + return [self.make_block_same_class(values=new_values)] + class DatetimeLikeBlockMixin(NDArrayBackedExtensionBlock): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" @@ -2134,6 +2149,7 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): fill_value = NaT where = DatetimeBlock.where putmask = DatetimeLikeBlockMixin.putmask + fillna = DatetimeLikeBlockMixin.fillna array_values = ExtensionBlock.array_values @@ -2172,19 +2188,6 @@ def external_values(self): # Avoid FutureWarning in .astype in casting from dt64tz to dt64 return self.values._data - def fillna( - self, value, limit=None, inplace: bool = False, downcast=None - ) -> List[Block]: - # We support filling a DatetimeTZ with a `value` whose timezone - # is different by coercing to object. - if self._can_hold_element(value): - return super().fillna(value, limit, inplace, downcast) - - # different timezones, or a non-tz - return self.astype(object).fillna( - value, limit=limit, inplace=inplace, downcast=downcast - ) - class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () @@ -2194,14 +2197,6 @@ class TimeDeltaBlock(DatetimeLikeBlockMixin): fill_value = np.timedelta64("NaT", "ns") _dtype = fill_value.dtype - def fillna( - self, value, limit=None, inplace: bool = False, downcast=None - ) -> List[Block]: - values = self.array_values() - values = values if inplace else values.copy() - new_values = values.fillna(value=value, limit=limit) - return [self.make_block_same_class(values=new_values)] - class ObjectBlock(Block): __slots__ = ()
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39893
2021-02-18T18:33:10Z
2021-02-19T01:02:55Z
2021-02-19T01:02:55Z
2021-02-19T01:42:22Z
REF: de-duplicate block_shape vs safe_reshape
diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index ff4e186e147d7..132598e03d6c0 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -11,7 +11,6 @@ ObjectBlock, TimeDeltaBlock, make_block, - safe_reshape, ) from pandas.core.internals.concat import concatenate_block_managers from pandas.core.internals.managers import ( @@ -31,7 +30,6 @@ "FloatBlock", "ObjectBlock", "TimeDeltaBlock", - "safe_reshape", "make_block", "DataManager", "ArrayManager", diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ae019c2f853a1..dee79efc538e3 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -308,7 +308,7 @@ def make_block(self, values, placement=None) -> Block: if placement is None: placement = self.mgr_locs if self.is_extension: - values = _block_shape(values, ndim=self.ndim) + values = ensure_block_shape(values, ndim=self.ndim) return make_block(values, placement=placement, ndim=self.ndim) @@ -533,7 +533,7 @@ def make_a_block(nv, ref_loc): else: # Put back the dimension that was taken from it and make # a block out of the result. - nv = _block_shape(nv, ndim=self.ndim) + nv = ensure_block_shape(nv, ndim=self.ndim) block = self.make_block(values=nv, placement=ref_loc) return block @@ -1569,7 +1569,9 @@ def putmask(self, mask, new) -> List[Block]: if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask): new = new[mask] - mask = safe_reshape(mask, new_values.shape) + if mask.ndim == new_values.ndim + 1: + # TODO(EA2D): unnecessary with 2D EAs + mask = mask.reshape(new_values.shape) new_values[mask] = new return [self.make_block(values=new_values)] @@ -2431,36 +2433,15 @@ def extend_blocks(result, blocks=None) -> List[Block]: return blocks -def _block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: - """ guarantee the shape of the values to be at least 1 d """ +def ensure_block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: + """ + Reshape if possible to have values.ndim == ndim. + """ if values.ndim < ndim: - shape = values.shape if not is_extension_array_dtype(values.dtype): # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. - # error: "ExtensionArray" has no attribute "reshape" - values = values.reshape(tuple((1,) + shape)) # type: ignore[attr-defined] + values = np.asarray(values).reshape(1, -1) return values - - -def safe_reshape(arr: ArrayLike, new_shape: Shape) -> ArrayLike: - """ - Reshape `arr` to have shape `new_shape`, unless it is an ExtensionArray, - in which case it will be returned unchanged (see gh-13012). - - Parameters - ---------- - arr : np.ndarray or ExtensionArray - new_shape : Tuple[int] - - Returns - ------- - np.ndarray or ExtensionArray - """ - if not is_extension_array_dtype(arr.dtype): - # Note: this will include TimedeltaArray and tz-naive DatetimeArray - # TODO(EA2D): special case will be unnecessary with 2D EAs - arr = np.asarray(arr).reshape(new_shape) - return arr diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b3f0466f236b6..4ad094f315c78 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -69,10 +69,10 @@ DatetimeTZBlock, ExtensionBlock, ObjectValuesExtensionBlock, + ensure_block_shape, extend_blocks, get_block_type, make_block, - safe_reshape, ) from pandas.core.internals.ops import ( blockwise_all, @@ -1042,7 +1042,7 @@ def value_getitem(placement): value = value.T if value.ndim == self.ndim - 1: - value = safe_reshape(value, (1,) + value.shape) + value = ensure_block_shape(value, ndim=2) def value_getitem(placement): return value @@ -1167,7 +1167,7 @@ def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False value = value.T elif value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype): # TODO(EA2D): special case not needed with 2D EAs - value = safe_reshape(value, (1,) + value.shape) + value = ensure_block_shape(value, ndim=2) block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39892
2021-02-18T18:28:43Z
2021-02-19T01:04:37Z
2021-02-19T01:04:37Z
2021-02-19T01:44:00Z
TST/REF: share pytables dateutil/pytz tests
diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 489352380b186..f67efb4cc60be 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -1,8 +1,12 @@ -import datetime +from datetime import ( + date, + timedelta, +) import numpy as np import pytest +from pandas._libs.tslibs.timezones import maybe_get_tz import pandas.util._test_decorators as td import pandas as pd @@ -36,200 +40,109 @@ def _compare_with_tz(a, b): raise AssertionError(f"invalid tz comparison [{a_e}] [{b_e}]") -def test_append_with_timezones_dateutil(setup_path): +# use maybe_get_tz instead of dateutil.tz.gettz to handle the windows +# filename issues. +gettz_dateutil = lambda x: maybe_get_tz("dateutil/" + x) +gettz_pytz = lambda x: x - from datetime import timedelta - # use maybe_get_tz instead of dateutil.tz.gettz to handle the windows - # filename issues. - from pandas._libs.tslibs.timezones import maybe_get_tz +@pytest.mark.parametrize("gettz", [gettz_dateutil, gettz_pytz]) +def test_append_with_timezones(setup_path, gettz): + # as columns - gettz = lambda x: maybe_get_tz("dateutil/" + x) + # Single-tzinfo, no DST transition + df_est = DataFrame( + { + "A": [ + Timestamp("20130102 2:00:00", tz=gettz("US/Eastern")) + + timedelta(hours=1) * i + for i in range(5) + ] + } + ) + + # frame with all columns having same tzinfo, but different sides + # of DST transition + df_crosses_dst = DataFrame( + { + "A": Timestamp("20130102", tz=gettz("US/Eastern")), + "B": Timestamp("20130603", tz=gettz("US/Eastern")), + }, + index=range(5), + ) + + df_mixed_tz = DataFrame( + { + "A": Timestamp("20130102", tz=gettz("US/Eastern")), + "B": Timestamp("20130102", tz=gettz("EET")), + }, + index=range(5), + ) + + df_different_tz = DataFrame( + { + "A": Timestamp("20130102", tz=gettz("US/Eastern")), + "B": Timestamp("20130102", tz=gettz("CET")), + }, + index=range(5), + ) - # as columns with ensure_clean_store(setup_path) as store: _maybe_remove(store, "df_tz") - df = DataFrame( - { - "A": [ - Timestamp("20130102 2:00:00", tz=gettz("US/Eastern")) - + timedelta(hours=1) * i - for i in range(5) - ] - } - ) - - store.append("df_tz", df, data_columns=["A"]) + store.append("df_tz", df_est, data_columns=["A"]) result = store["df_tz"] - _compare_with_tz(result, df) - tm.assert_frame_equal(result, df) + _compare_with_tz(result, df_est) + tm.assert_frame_equal(result, df_est) # select with tz aware - expected = df[df.A >= df.A[3]] - result = store.select("df_tz", where="A>=df.A[3]") + expected = df_est[df_est.A >= df_est.A[3]] + result = store.select("df_tz", where="A>=df_est.A[3]") _compare_with_tz(result, expected) # ensure we include dates in DST and STD time here. _maybe_remove(store, "df_tz") - df = DataFrame( - { - "A": Timestamp("20130102", tz=gettz("US/Eastern")), - "B": Timestamp("20130603", tz=gettz("US/Eastern")), - }, - index=range(5), - ) - store.append("df_tz", df) + store.append("df_tz", df_crosses_dst) result = store["df_tz"] - _compare_with_tz(result, df) - tm.assert_frame_equal(result, df) - - df = DataFrame( - { - "A": Timestamp("20130102", tz=gettz("US/Eastern")), - "B": Timestamp("20130102", tz=gettz("EET")), - }, - index=range(5), - ) + _compare_with_tz(result, df_crosses_dst) + tm.assert_frame_equal(result, df_crosses_dst) msg = ( r"invalid info for \[values_block_1\] for \[tz\], " - r"existing_value \[dateutil/.*US/Eastern\] " - r"conflicts with new value \[dateutil/.*EET\]" + r"existing_value \[(dateutil/.*)?US/Eastern\] " + r"conflicts with new value \[(dateutil/.*)?EET\]" ) with pytest.raises(ValueError, match=msg): - store.append("df_tz", df) + store.append("df_tz", df_mixed_tz) # this is ok _maybe_remove(store, "df_tz") - store.append("df_tz", df, data_columns=["A", "B"]) + store.append("df_tz", df_mixed_tz, data_columns=["A", "B"]) result = store["df_tz"] - _compare_with_tz(result, df) - tm.assert_frame_equal(result, df) + _compare_with_tz(result, df_mixed_tz) + tm.assert_frame_equal(result, df_mixed_tz) # can't append with diff timezone - df = DataFrame( - { - "A": Timestamp("20130102", tz=gettz("US/Eastern")), - "B": Timestamp("20130102", tz=gettz("CET")), - }, - index=range(5), - ) - msg = ( r"invalid info for \[B\] for \[tz\], " - r"existing_value \[dateutil/.*EET\] " - r"conflicts with new value \[dateutil/.*CET\]" + r"existing_value \[(dateutil/.*)?EET\] " + r"conflicts with new value \[(dateutil/.*)?CET\]" ) with pytest.raises(ValueError, match=msg): - store.append("df_tz", df) + store.append("df_tz", df_different_tz) - # as index - with ensure_clean_store(setup_path) as store: - dti = date_range("2000-1-1", periods=3, freq="H", tz=gettz("US/Eastern")) - dti = dti._with_freq(None) # freq doesnt round-trip +@pytest.mark.parametrize("gettz", [gettz_dateutil, gettz_pytz]) +def test_append_with_timezones_as_index(setup_path, gettz): + # GH#4098 example - # GH 4098 example - df = DataFrame({"A": Series(range(3), index=dti)}) - - _maybe_remove(store, "df") - store.put("df", df) - result = store.select("df") - tm.assert_frame_equal(result, df) - - _maybe_remove(store, "df") - store.append("df", df) - result = store.select("df") - tm.assert_frame_equal(result, df) + dti = date_range("2000-1-1", periods=3, freq="H", tz=gettz("US/Eastern")) + dti = dti._with_freq(None) # freq doesnt round-trip + df = DataFrame({"A": Series(range(3), index=dti)}) -def test_append_with_timezones_pytz(setup_path): - - from datetime import timedelta - - # as columns with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df_tz") - df = DataFrame( - { - "A": [ - Timestamp("20130102 2:00:00", tz="US/Eastern") - + timedelta(hours=1) * i - for i in range(5) - ] - } - ) - store.append("df_tz", df, data_columns=["A"]) - result = store["df_tz"] - _compare_with_tz(result, df) - tm.assert_frame_equal(result, df) - - # select with tz aware - _compare_with_tz(store.select("df_tz", where="A>=df.A[3]"), df[df.A >= df.A[3]]) - - _maybe_remove(store, "df_tz") - # ensure we include dates in DST and STD time here. - df = DataFrame( - { - "A": Timestamp("20130102", tz="US/Eastern"), - "B": Timestamp("20130603", tz="US/Eastern"), - }, - index=range(5), - ) - store.append("df_tz", df) - result = store["df_tz"] - _compare_with_tz(result, df) - tm.assert_frame_equal(result, df) - - df = DataFrame( - { - "A": Timestamp("20130102", tz="US/Eastern"), - "B": Timestamp("20130102", tz="EET"), - }, - index=range(5), - ) - - msg = ( - r"invalid info for \[values_block_1\] for \[tz\], " - r"existing_value \[US/Eastern\] conflicts with new value \[EET\]" - ) - with pytest.raises(ValueError, match=msg): - store.append("df_tz", df) - - # this is ok - _maybe_remove(store, "df_tz") - store.append("df_tz", df, data_columns=["A", "B"]) - result = store["df_tz"] - _compare_with_tz(result, df) - tm.assert_frame_equal(result, df) - - # can't append with diff timezone - df = DataFrame( - { - "A": Timestamp("20130102", tz="US/Eastern"), - "B": Timestamp("20130102", tz="CET"), - }, - index=range(5), - ) - - msg = ( - r"invalid info for \[B\] for \[tz\], " - r"existing_value \[EET\] conflicts with new value \[CET\]" - ) - with pytest.raises(ValueError, match=msg): - store.append("df_tz", df) - - # as index - with ensure_clean_store(setup_path) as store: - - dti = date_range("2000-1-1", periods=3, freq="H", tz="US/Eastern") - dti = dti._with_freq(None) # freq doesnt round-trip - - # GH 4098 example - df = DataFrame({"A": Series(range(3), index=dti)}) - _maybe_remove(store, "df") store.put("df", df) result = store.select("df") @@ -327,17 +240,19 @@ def test_timezones_fixed_format_frame_non_empty(setup_path): tm.assert_frame_equal(result, df) -def test_timezones_fixed_format_frame_empty(setup_path, tz_aware_fixture): +def test_timezones_fixed_format_empty(setup_path, tz_aware_fixture, frame_or_series): # GH 20594 dtype = pd.DatetimeTZDtype(tz=tz_aware_fixture) + obj = Series(dtype=dtype, name="A") + if frame_or_series is DataFrame: + obj = obj.to_frame() + with ensure_clean_store(setup_path) as store: - s = Series(dtype=dtype) - df = DataFrame({"A": s}) - store["df"] = df - result = store["df"] - tm.assert_frame_equal(result, df) + store["obj"] = obj + result = store["obj"] + tm.assert_equal(result, obj) def test_timezones_fixed_format_series_nonempty(setup_path, tz_aware_fixture): @@ -352,18 +267,6 @@ def test_timezones_fixed_format_series_nonempty(setup_path, tz_aware_fixture): tm.assert_series_equal(result, s) -def test_timezones_fixed_format_series_empty(setup_path, tz_aware_fixture): - # GH 20594 - - dtype = pd.DatetimeTZDtype(tz=tz_aware_fixture) - - with ensure_clean_store(setup_path) as store: - s = Series(dtype=dtype) - store["s"] = s - result = store["s"] - tm.assert_series_equal(result, s) - - def test_fixed_offset_tz(setup_path): rng = date_range("1/1/2000 00:00:00-07:00", "1/30/2000 00:00:00-07:00") frame = DataFrame(np.random.randn(len(rng), 4), index=rng) @@ -384,7 +287,7 @@ def test_store_timezone(setup_path): # original method with ensure_clean_store(setup_path) as store: - today = datetime.date(2013, 9, 10) + today = date(2013, 9, 10) df = DataFrame([1, 2, 3], index=[today, today, today]) store["obj1"] = df result = store["obj1"] @@ -394,7 +297,7 @@ def test_store_timezone(setup_path): with ensure_clean_store(setup_path) as store: with tm.set_timezone("EST5EDT"): - today = datetime.date(2013, 9, 10) + today = date(2013, 9, 10) df = DataFrame([1, 2, 3], index=[today, today, today]) store["obj1"] = df
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39891
2021-02-18T18:19:04Z
2021-02-18T22:24:03Z
2021-02-18T22:24:03Z
2021-02-18T23:50:20Z
BUG: Breaking change to offsets.pyx - quarter offset classes
diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst index e6271a7806706..c5ed8d718bfb7 100644 --- a/doc/source/reference/offset_frequency.rst +++ b/doc/source/reference/offset_frequency.rst @@ -655,7 +655,7 @@ Properties BQuarterEnd.normalize BQuarterEnd.rule_code BQuarterEnd.n - BQuarterEnd.startingMonth + BQuarterEnd.month Methods ~~~~~~~ @@ -690,7 +690,7 @@ Properties BQuarterBegin.normalize BQuarterBegin.rule_code BQuarterBegin.n - BQuarterBegin.startingMonth + BQuarterBegin.month Methods ~~~~~~~ @@ -725,7 +725,7 @@ Properties QuarterEnd.normalize QuarterEnd.rule_code QuarterEnd.n - QuarterEnd.startingMonth + QuarterEnd.month Methods ~~~~~~~ @@ -760,7 +760,7 @@ Properties QuarterBegin.normalize QuarterBegin.rule_code QuarterBegin.n - QuarterBegin.startingMonth + QuarterBegin.month Methods ~~~~~~~ diff --git a/doc/source/whatsnew/v0.18.0.rst b/doc/source/whatsnew/v0.18.0.rst index 829c04dac9f2d..349a718cf2172 100644 --- a/doc/source/whatsnew/v0.18.0.rst +++ b/doc/source/whatsnew/v0.18.0.rst @@ -686,6 +686,7 @@ when it is an anchor point (e.g., a quarter start date), and otherwise roll forward to the next anchor point. .. ipython:: python + :okwarning: d = pd.Timestamp('2014-02-01') d @@ -706,6 +707,7 @@ This behavior has been corrected in version 0.18.0, which is consistent with other anchored offsets like ``MonthBegin`` and ``YearBegin``. .. ipython:: python + :okwarning: d = pd.Timestamp('2014-02-15') d + pd.offsets.QuarterBegin(n=0, startingMonth=2) diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 38a1802340c69..618045b6ffa7d 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -458,6 +458,36 @@ with a :class:`MultiIndex` in the result. This can lead to a perceived duplicati df.groupby('label1').rolling(1).sum() +.. _whatsnew_130.notable_bug_fixes.quarterbegin_default_anchor: + +Changed default periods in :class:`~pandas.tseries.offsets.QuarterBegin` and :class:`~pandas.tseries.offsets.BQuarterBegin` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Quarter-based time offset classes :class:`~pandas.tseries.offsets.QuarterEnd`, +:class:`~pandas.tseries.offsets.QuarterBegin`, :class:`~pandas.tseries.offsets.BQuarterEnd`, +:class:`~pandas.tseries.offsets.BQuarterBegin` now use ``month`` instead of ``startingMonth`` +as a time anchor parameter (:issue:`5307`). The default value for :class:`~pandas.tseries.offsets.QuarterBegin` +and :class:`~pandas.tseries.offsets.BQuarterBegin` is now 1 (January) instead of 3 (March), +as a result these offsets are aligned with standard calendar quarters (:issue:`8435`). + +*pandas 1.2.x* + +.. code-block:: ipython + + In [1]: pd.Timestamp(2014, 10, 10) + pd.tseries.offsets.QuarterBegin() + Out[2]: Timestamp('2014-12-01 00:00:00') + In [3]: pd.Timestamp(2014, 10, 10) + pd.tseries.offsets.BQuarterBegin() + Out[4]: Timestamp('2014-12-01 00:00:00') + +*pandas 1.3.0* + +.. code-block:: ipython + + In [1]: pd.Timestamp(2014, 10, 10) + pd.tseries.offsets.QuarterBegin() + Out[2]: Timestamp('2015-01-01 00:00:00') + In [3]: pd.Timestamp(2014, 10, 10) + pd.tseries.offsets.BQuarterBegin() + Out[4]: Timestamp('2015-01-01 00:00:00') + .. _whatsnew_130.api_breaking.deps: Increased minimum versions for dependencies @@ -570,6 +600,7 @@ Deprecations - Deprecated allowing partial failure in :meth:`Series.transform` and :meth:`DataFrame.transform` when ``func`` is list-like or dict-like and raises anything but ``TypeError``; ``func`` raising anything but a ``TypeError`` will raise in a future version (:issue:`40211`) - Deprecated support for ``np.ma.mrecords.MaskedRecords`` in the :class:`DataFrame` constructor, pass ``{name: data[name] for name in data.dtype.names}`` instead (:issue:`40363`) - Deprecated the use of ``**kwargs`` in :class:`.ExcelWriter`; use the keyword argument ``engine_kwargs`` instead (:issue:`40430`) +- Deprecated the ``startingMonth`` keyword in quarter-based offsets :class:`QuarterBegin`, :class:`QuarterEnd`, :class:`BQuarterBegin`, :class:`BQuarterEnd`; use ``month`` instead (:issue:`5307`) - Deprecated the ``level`` keyword for :class:`DataFrame` and :class:`Series` aggregations; use groupby instead (:issue:`39983`) .. --------------------------------------------------------------------------- @@ -625,6 +656,7 @@ Datetimelike - Bug in :meth:`Timedelta.round`, :meth:`Timedelta.floor`, :meth:`Timedelta.ceil` for values near the implementation bounds of :class:`Timedelta` (:issue:`38964`) - Bug in :func:`date_range` incorrectly creating :class:`DatetimeIndex` containing ``NaT`` instead of raising ``OutOfBoundsDatetime`` in corner cases (:issue:`24124`) - Bug in :func:`infer_freq` incorrectly fails to infer 'H' frequency of :class:`DatetimeIndex` if the latter has a timezone and crosses DST boundaries (:issue:`39556`) +- Bug in offsets :class:`QuarterBegin` and :class:`BQuarterBegin` returning days that are not conventional quarter beginnings (:issue:`8435`) Timedelta ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 4e6e5485b2ade..be9d4a7ac04c6 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1986,52 +1986,88 @@ cdef class YearBegin(YearOffset): # Quarter-Based Offset Classes cdef class QuarterOffset(SingleConstructorOffset): - _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 + """ + Base for quarter-based offset classes. + + Parameters + ---------- + n : int, default 1 + Number of quarters to offset. + normalize : bool, default False + If true, the time component of the resulting date-time is converted + to 00:00:00, i.e. midnight (the start, not the end of date-time). + month : int + The calendar month number (1 for January) of the beginning or ending + month in a custom-defined quarter to be used as an offset. + + .. versionadded:: 1.3.0 + startingMonth : int + The calendar month number (1 for January) of the beginning or ending + month in a custom-defined quarter to be used as an offset. + + .. deprecated:: 1.3.0 + """ - # FIXME: python annotations here breaks things - # _default_starting_month: int - # _from_name_starting_month: int + _attributes = tuple(["n", "normalize", "month"]) + # TODO: Consider combining QuarterOffset and YearOffset __init__ at some + # point. Also apply_index, is_on_offset, rule_code. cdef readonly: - int startingMonth + int month - def __init__(self, n=1, normalize=False, startingMonth=None): + def __init__(self, n: int=1, normalize: bool=False, month: int=None, + *, startingMonth: int=None): + # GH#5307 startingMonth retained for backwards compatibility BaseOffset.__init__(self, n, normalize) - if startingMonth is None: - startingMonth = self._default_starting_month - self.startingMonth = startingMonth + # GH#5307 startingMonth retained for backwards compatibility + if month and startingMonth and month != startingMonth: + raise TypeError("Offset received both month and startingMonth") + elif month is None and startingMonth is not None: + warnings.warn( + "startingMonth is deprecated, use month instead.", + FutureWarning, stacklevel=2 + ) + month = startingMonth + + month = month if month is not None else self._default_month + self.month = month + + if month < 1 or month > 12: + raise ValueError("Month must go from 1 to 12.") cpdef __setstate__(self, state): - self.startingMonth = state.pop("startingMonth") + try: + self.month = state.pop("month") + except: + # Necessary for read_pickle of data pickled with pre-1.3 pandas + self.month = state.pop("startingMonth") self.n = state.pop("n") self.normalize = state.pop("normalize") + self._cache = {} @classmethod def _from_name(cls, suffix=None): kwargs = {} if suffix: - kwargs["startingMonth"] = MONTH_TO_CAL_NUM[suffix] + kwargs["month"] = MONTH_TO_CAL_NUM[suffix] else: - if cls._from_name_starting_month is not None: - kwargs["startingMonth"] = cls._from_name_starting_month + if cls._from_name_month is not None: + kwargs["month"] = cls._from_name_month return cls(**kwargs) @property def rule_code(self) -> str: - month = MONTH_ALIASES[self.startingMonth] + month = MONTH_ALIASES[self.month] return f"{self._prefix}-{month}" def is_anchored(self) -> bool: - return self.n == 1 and self.startingMonth is not None + return self.n == 1 and self.month is not None def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False - mod_month = (dt.month - self.startingMonth) % 3 + mod_month = (dt.month - self.month) % 3 return mod_month == 0 and dt.day == self._get_offset_day(dt) @apply_wraps @@ -2041,9 +2077,9 @@ cdef class QuarterOffset(SingleConstructorOffset): # Then find the month in that quarter containing an is_on_offset date for # self. `months_since` is the number of months to shift other.month # to get to this on-offset month. - months_since = other.month % 3 - self.startingMonth % 3 + months_since = other.month % 3 - self.month % 3 qtrs = roll_qtrday( - other, self.n, self.startingMonth, day_opt=self._day_opt, modby=3 + other, self.n, self.month, day_opt=self._day_opt, modby=3 ) months = qtrs * 3 - months_since return shift_month(other, months, self._day_opt) @@ -2055,35 +2091,53 @@ cdef class QuarterOffset(SingleConstructorOffset): @apply_array_wraps def _apply_array(self, dtarr): shifted = shift_quarters( - dtarr.view("i8"), self.n, self.startingMonth, self._day_opt + dtarr.view("i8"), self.n, self.month, self._day_opt ) return shifted cdef class BQuarterEnd(QuarterOffset): """ - DateOffset increments between the last business day of each Quarter. + DateOffset increments between the last business day of each quarter. - startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... - startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... - startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, ... + month = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... + month = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... + month = 3 corresponds to dates like 3/30/2007, 6/29/2007, ... + + Parameters + ---------- + n : int, default 1 + Number of business quarters to offset. + normalize : bool, default False + If true, the time component of the resulting date-time is converted + to 00:00:00, i.e. midnight (the start, not the end of date-time). + month : int, default 3 + The calendar month number (3 for March) of the last month + in a custom-defined business quarter to be used as an offset. + + .. versionadded:: 1.3.0 + startingMonth : int, default 3 + The calendar month number (3 for March) of the last month + in a custom-defined business quarter to be used as an offset. + + .. deprecated:: 1.3.0 Examples -------- - >>> from pandas.tseries.offset import BQuarterEnd + >>> from pandas.tseries.offsets import BQuarterEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BQuarterEnd() Timestamp('2020-06-30 05:01:15') >>> ts + BQuarterEnd(2) Timestamp('2020-09-30 05:01:15') - >>> ts + BQuarterEnd(1, startingMonth=2) + >>> ts + BQuarterEnd(1, month=2) Timestamp('2020-05-29 05:01:15') - >>> ts + BQuarterEnd(startingMonth=2) + >>> ts + BQuarterEnd(month=2) Timestamp('2020-05-29 05:01:15') """ _output_name = "BusinessQuarterEnd" - _default_starting_month = 3 - _from_name_starting_month = 12 + _default_month = 3 + _from_name_month = 3 _prefix = "BQ" _day_opt = "business_end" @@ -2092,26 +2146,44 @@ cdef class BQuarterBegin(QuarterOffset): """ DateOffset increments between the first business day of each Quarter. - startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... - startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... - startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + month = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... + month = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... + month = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + + Parameters + ---------- + n : int, default 1 + Number of business quarters to offset. + normalize : bool, default False + If true, the time component of the resulting date-time is converted + to 00:00:00, i.e. midnight (the start, not the end of date-time). + month : int, default 1 + The calendar month number (1 for January) of the first month + in a custom-defined business quarter to be used as an offset. + + .. versionadded:: 1.3.0 + startingMonth : int, default 1 + The calendar month number (1 for January) of the first month + in a custom-defined business quarter to be used as an offset. + + .. deprecated:: 1.3.0 Examples -------- - >>> from pandas.tseries.offset import BQuarterBegin + >>> from pandas.tseries.offsets import BQuarterBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BQuarterBegin() Timestamp('2020-06-01 05:01:15') >>> ts + BQuarterBegin(2) Timestamp('2020-09-01 05:01:15') - >>> ts + BQuarterBegin(startingMonth=2) + >>> ts + BQuarterBegin(month=2) Timestamp('2020-08-03 05:01:15') >>> ts + BQuarterBegin(-1) Timestamp('2020-03-02 05:01:15') """ _output_name = "BusinessQuarterBegin" - _default_starting_month = 3 - _from_name_starting_month = 1 + _default_month = 1 + _from_name_month = 1 _prefix = "BQS" _day_opt = "business_start" @@ -2120,34 +2192,73 @@ cdef class QuarterEnd(QuarterOffset): """ DateOffset increments between Quarter end dates. - startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... - startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... - startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... + month = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... + month = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... + month = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... + + Parameters + ---------- + n : int, default 1 + Number of quarters to offset. + normalize : bool, default False + If true, the time component of the resulting date-time is converted + to 00:00:00, i.e. midnight (the start, not the end of date-time). + month : int, default 3 + The calendar month number (3 for March) of the last month + in a custom-defined quarter to be used as an offset. + + .. versionadded:: 1.3.0 + startingMonth : int, default 3 + The calendar month number (3 for March) of the last month + in a custom-defined quarter to be used as an offset. + + .. deprecated:: 1.3.0 """ - _default_starting_month = 3 + _default_month = 3 + _from_name_month = 3 _prefix = "Q" _day_opt = "end" cdef readonly: int _period_dtype_code - def __init__(self, n=1, normalize=False, startingMonth=None): + def __init__(self, n: int=1, normalize: bool=False, month: int=None, + *, startingMonth: int=None): # GH#5307 backwards compatibility # 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 + QuarterOffset.__init__(self, n, normalize, month, + startingMonth=startingMonth) + self._period_dtype_code = PeriodDtypeCode.Q_DEC + self.month % 12 cdef class QuarterBegin(QuarterOffset): """ DateOffset increments between Quarter start dates. - startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... - startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... - startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + month = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... + month = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... + month = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + + Parameters + ---------- + n : int, default 1 + Number of quarters to offset. + normalize : bool, default False + If true, the time component of the resulting date-time is converted + to 00:00:00, i.e. midnight (the start, not the end of date-time). + month : int, default 1 + The calendar month number (1 for January) of the first month + in a custom-defined quarter to be used as an offset. + + .. versionadded:: 1.3.0 + startingMonth : int, default 1 + The calendar month number (1 for January) of the first month + in a custom-defined quarter to be used as an offset. + + .. deprecated:: 1.3.0 """ - _default_starting_month = 3 - _from_name_starting_month = 1 + _default_month = 1 + _from_name_month = 1 _prefix = "QS" _day_opt = "start" diff --git a/pandas/conftest.py b/pandas/conftest.py index 3fdde3261bd68..ec24215311915 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -172,7 +172,7 @@ def pytest_collection_modifyitems(items): cls, n=st.integers(-24, 24), normalize=st.booleans(), - startingMonth=st.integers(min_value=1, max_value=12), + month=st.integers(min_value=1, max_value=12), ), ) diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index bb78e29924ba2..58108c93afc6a 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -665,7 +665,7 @@ def test_sub_n_gt_1_ticks(self, tick_classes, n): "offset, kwd_name", [ (pd.offsets.YearEnd, "month"), - (pd.offsets.QuarterEnd, "startingMonth"), + (pd.offsets.QuarterEnd, "month"), (pd.offsets.MonthEnd, None), (pd.offsets.Week, "weekday"), ], @@ -839,8 +839,8 @@ def test_pi_add_offset_array(self, box): pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")]) offs = box( [ - pd.offsets.QuarterEnd(n=1, startingMonth=12), - pd.offsets.QuarterEnd(n=-2, startingMonth=12), + pd.offsets.QuarterEnd(n=1, month=12), + pd.offsets.QuarterEnd(n=-2, month=12), ] ) expected = PeriodIndex([Period("2015Q2"), Period("2015Q4")]) @@ -870,8 +870,8 @@ def test_pi_sub_offset_array(self, box): pi = PeriodIndex([Period("2015Q1"), Period("2016Q2")]) other = box( [ - pd.offsets.QuarterEnd(n=1, startingMonth=12), - pd.offsets.QuarterEnd(n=-2, startingMonth=12), + pd.offsets.QuarterEnd(n=1, month=12), + pd.offsets.QuarterEnd(n=-2, month=12), ] ) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index ec597b1468904..8c3aa45f0d324 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -1045,16 +1045,12 @@ def test_datetimeindex_constructor_misc(self): assert idx1.freq == idx2.freq idx1 = date_range(start=sdate, end=edate, freq="QS") - idx2 = date_range( - start=sdate, end=edate, freq=offsets.QuarterBegin(startingMonth=1) - ) + idx2 = date_range(start=sdate, end=edate, freq=offsets.QuarterBegin(month=1)) assert len(idx1) == len(idx2) assert idx1.freq == idx2.freq idx1 = date_range(start=sdate, end=edate, freq="BQ") - idx2 = date_range( - start=sdate, end=edate, freq=offsets.BQuarterEnd(startingMonth=12) - ) + idx2 = date_range(start=sdate, end=edate, freq=offsets.BQuarterEnd(month=3)) assert len(idx1) == len(idx2) assert idx1.freq == idx2.freq diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index c3736d588601b..c4eac92bf2009 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -247,7 +247,7 @@ def test_datetimeindex_accessors(self): tm.assert_index_equal(res, exp) def test_datetimeindex_accessors2(self): - dti = date_range(freq="BQ-FEB", start=datetime(1998, 1, 1), periods=4) + dti = date_range(freq="BQ-DEC", start=datetime(1998, 1, 1), periods=4) assert sum(dti.is_quarter_start) == 0 assert sum(dti.is_quarter_end) == 4 diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index e2b13f6a00677..401a912ec0799 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -130,7 +130,7 @@ def test_basic_downsample(self, simple_period_range_series): "rule,expected_error_msg", [ ("a-dec", "<YearEnd: month=12>"), - ("q-mar", "<QuarterEnd: startingMonth=3>"), + ("q-mar", "<QuarterEnd: month=3>"), ("M", "<MonthEnd>"), ("w-thu", "<Week: weekday=3>"), ], diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 3cc81ef851306..f1a97cf599dd1 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -198,10 +198,10 @@ def test_period_constructor_offsets(self): assert Period("3/10/12", freq=offsets.Day()) == Period("3/10/12", freq="D") assert Period( - year=2005, quarter=1, freq=offsets.QuarterEnd(startingMonth=12) + year=2005, quarter=1, freq=offsets.QuarterEnd(month=12) ) == Period(year=2005, quarter=1, freq="Q") assert Period( - year=2005, quarter=2, freq=offsets.QuarterEnd(startingMonth=12) + year=2005, quarter=2, freq=offsets.QuarterEnd(month=12) ) == Period(year=2005, quarter=2, freq="Q") assert Period(year=2005, month=3, day=1, freq=offsets.Day()) == Period( @@ -1252,7 +1252,7 @@ def test_sub_n_gt_1_ticks(self, tick_classes, n): "offset, kwd_name", [ (offsets.YearEnd, "month"), - (offsets.QuarterEnd, "startingMonth"), + (offsets.QuarterEnd, "month"), (offsets.MonthEnd, None), (offsets.Week, "weekday"), ], diff --git a/pandas/tests/tseries/offsets/test_dst.py b/pandas/tests/tseries/offsets/test_dst.py index 0ae94b6b57640..2039987e835b4 100644 --- a/pandas/tests/tseries/offsets/test_dst.py +++ b/pandas/tests/tseries/offsets/test_dst.py @@ -159,9 +159,9 @@ def test_springforward_singular(self): YearEnd: ["11/2/2012", "12/31/2012"], BYearBegin: ["11/2/2012", "1/1/2013"], BYearEnd: ["11/2/2012", "12/31/2012"], - QuarterBegin: ["11/2/2012", "12/1/2012"], + QuarterBegin: ["11/2/2012", "1/1/2013"], QuarterEnd: ["11/2/2012", "12/31/2012"], - BQuarterBegin: ["11/2/2012", "12/3/2012"], + BQuarterBegin: ["11/2/2021", "1/3/2022"], BQuarterEnd: ["11/2/2012", "12/31/2012"], Day: ["11/4/2012", "11/4/2012 23:00"], }.items() diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 3eb3892279832..75aa1a771bff6 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -84,8 +84,8 @@ class TestCommon(Base): "BYearBegin": Timestamp("2011-01-03 09:00:00"), "YearEnd": Timestamp("2011-12-31 09:00:00"), "BYearEnd": Timestamp("2011-12-30 09:00:00"), - "QuarterBegin": Timestamp("2011-03-01 09:00:00"), - "BQuarterBegin": Timestamp("2011-03-01 09:00:00"), + "QuarterBegin": Timestamp("2011-04-01 09:00:00"), + "BQuarterBegin": Timestamp("2011-01-03 09:00:00"), "QuarterEnd": Timestamp("2011-03-31 09:00:00"), "BQuarterEnd": Timestamp("2011-03-31 09:00:00"), "BusinessHour": Timestamp("2011-01-03 10:00:00"), @@ -260,6 +260,7 @@ def test_rollforward(self, offset_types): "Day", "MonthBegin", "SemiMonthBegin", + "QuarterBegin", "YearBegin", "Week", "Hour", @@ -286,6 +287,7 @@ def test_rollforward(self, offset_types): "DateOffset": Timestamp("2011-01-02 00:00:00"), "MonthBegin": Timestamp("2011-02-01 00:00:00"), "SemiMonthBegin": Timestamp("2011-01-15 00:00:00"), + "QuarterBegin": Timestamp("2011-04-01 00:00:00"), "YearBegin": Timestamp("2012-01-01 00:00:00"), "Week": Timestamp("2011-01-08 00:00:00"), "Hour": Timestamp("2011-01-01 00:00:00"), @@ -320,8 +322,7 @@ def test_rollback(self, offset_types): "BYearBegin": Timestamp("2010-01-01 09:00:00"), "YearEnd": Timestamp("2010-12-31 09:00:00"), "BYearEnd": Timestamp("2010-12-31 09:00:00"), - "QuarterBegin": Timestamp("2010-12-01 09:00:00"), - "BQuarterBegin": Timestamp("2010-12-01 09:00:00"), + "BQuarterBegin": Timestamp("2010-10-01 09:00:00"), "QuarterEnd": Timestamp("2010-12-31 09:00:00"), "BQuarterEnd": Timestamp("2010-12-31 09:00:00"), "BusinessHour": Timestamp("2010-12-31 17:00:00"), @@ -338,6 +339,7 @@ def test_rollback(self, offset_types): "Day", "MonthBegin", "SemiMonthBegin", + "QuarterBegin", "YearBegin", "Week", "Hour", @@ -360,6 +362,7 @@ def test_rollback(self, offset_types): "DateOffset": Timestamp("2010-12-31 00:00:00"), "MonthBegin": Timestamp("2010-12-01 00:00:00"), "SemiMonthBegin": Timestamp("2010-12-15 00:00:00"), + "QuarterBegin": Timestamp("2010-10-01 00:00:00"), "YearBegin": Timestamp("2010-01-01 00:00:00"), "Week": Timestamp("2010-12-25 00:00:00"), "Hour": Timestamp("2011-01-01 00:00:00"), @@ -870,3 +873,22 @@ def test_dateoffset_immutable(attribute): msg = "DateOffset objects are immutable" with pytest.raises(AttributeError, match=msg): setattr(offset, attribute, 5) + + +@pytest.mark.parametrize( + "offset_type", + [ + "QuarterBegin", + "QuarterEnd", + "BQuarterBegin", + "BQuarterEnd", + ], +) +def test_startingMonth_deprecation(offset_type): + # GH#5307 + with tm.assert_produces_warning(FutureWarning): + eval(f"offsets.{offset_type}(startingMonth=1)") + + msg = "Offset received both month and startingMonth" + with pytest.raises(TypeError, match=msg): + eval(f"offsets.{offset_type}(startingMonth=1,month=2)") diff --git a/pandas/tests/tseries/offsets/test_yqm_offsets.py b/pandas/tests/tseries/offsets/test_yqm_offsets.py index 260f7368123a4..6f601318b5a3d 100644 --- a/pandas/tests/tseries/offsets/test_yqm_offsets.py +++ b/pandas/tests/tseries/offsets/test_yqm_offsets.py @@ -436,27 +436,27 @@ def test_is_on_offset(self, case): class TestQuarterBegin(Base): def test_repr(self): - expected = "<QuarterBegin: startingMonth=3>" + expected = "<QuarterBegin: month=1>" assert repr(QuarterBegin()) == expected - expected = "<QuarterBegin: startingMonth=3>" - assert repr(QuarterBegin(startingMonth=3)) == expected - expected = "<QuarterBegin: startingMonth=1>" - assert repr(QuarterBegin(startingMonth=1)) == expected + expected = "<QuarterBegin: month=3>" + assert repr(QuarterBegin(month=3)) == expected + expected = "<QuarterBegin: month=1>" + assert repr(QuarterBegin(month=1)) == expected def test_is_anchored(self): - assert QuarterBegin(startingMonth=1).is_anchored() + assert QuarterBegin(month=1).is_anchored() assert QuarterBegin().is_anchored() - assert not QuarterBegin(2, startingMonth=1).is_anchored() + assert not QuarterBegin(2, month=1).is_anchored() def test_offset_corner_case(self): # corner - offset = QuarterBegin(n=-1, startingMonth=1) + offset = QuarterBegin(n=-1, month=1) assert datetime(2010, 2, 1) + offset == datetime(2010, 1, 1) offset_cases = [] offset_cases.append( ( - QuarterBegin(startingMonth=1), + QuarterBegin(month=1), { datetime(2007, 12, 1): datetime(2008, 1, 1), datetime(2008, 1, 1): datetime(2008, 4, 1), @@ -472,7 +472,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterBegin(startingMonth=2), + QuarterBegin(month=2), { datetime(2008, 1, 1): datetime(2008, 2, 1), datetime(2008, 1, 31): datetime(2008, 2, 1), @@ -488,7 +488,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterBegin(startingMonth=1, n=0), + QuarterBegin(month=1, n=0), { datetime(2008, 1, 1): datetime(2008, 1, 1), datetime(2008, 12, 1): datetime(2009, 1, 1), @@ -505,7 +505,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterBegin(startingMonth=1, n=-1), + QuarterBegin(month=1, n=-1), { datetime(2008, 1, 1): datetime(2007, 10, 1), datetime(2008, 1, 31): datetime(2008, 1, 1), @@ -522,7 +522,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterBegin(startingMonth=1, n=2), + QuarterBegin(month=1, n=2), { datetime(2008, 1, 1): datetime(2008, 7, 1), datetime(2008, 2, 15): datetime(2008, 7, 1), @@ -546,27 +546,27 @@ class TestQuarterEnd(Base): _offset = QuarterEnd def test_repr(self): - expected = "<QuarterEnd: startingMonth=3>" + expected = "<QuarterEnd: month=3>" assert repr(QuarterEnd()) == expected - expected = "<QuarterEnd: startingMonth=3>" - assert repr(QuarterEnd(startingMonth=3)) == expected - expected = "<QuarterEnd: startingMonth=1>" - assert repr(QuarterEnd(startingMonth=1)) == expected + expected = "<QuarterEnd: month=3>" + assert repr(QuarterEnd(month=3)) == expected + expected = "<QuarterEnd: month=1>" + assert repr(QuarterEnd(month=1)) == expected def test_is_anchored(self): - assert QuarterEnd(startingMonth=1).is_anchored() + assert QuarterEnd(month=1).is_anchored() assert QuarterEnd().is_anchored() - assert not QuarterEnd(2, startingMonth=1).is_anchored() + assert not QuarterEnd(2, month=1).is_anchored() def test_offset_corner_case(self): # corner - offset = QuarterEnd(n=-1, startingMonth=1) + offset = QuarterEnd(n=-1, month=1) assert datetime(2010, 2, 1) + offset == datetime(2010, 1, 31) offset_cases = [] offset_cases.append( ( - QuarterEnd(startingMonth=1), + QuarterEnd(month=1), { datetime(2008, 1, 1): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 4, 30), @@ -582,7 +582,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterEnd(startingMonth=2), + QuarterEnd(month=2), { datetime(2008, 1, 1): datetime(2008, 2, 29), datetime(2008, 1, 31): datetime(2008, 2, 29), @@ -598,7 +598,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterEnd(startingMonth=1, n=0), + QuarterEnd(month=1, n=0), { datetime(2008, 1, 1): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 1, 31), @@ -614,7 +614,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterEnd(startingMonth=1, n=-1), + QuarterEnd(month=1, n=-1), { datetime(2008, 1, 1): datetime(2007, 10, 31), datetime(2008, 1, 31): datetime(2007, 10, 31), @@ -631,7 +631,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - QuarterEnd(startingMonth=1, n=2), + QuarterEnd(month=1, n=2), { datetime(2008, 1, 31): datetime(2008, 7, 31), datetime(2008, 2, 15): datetime(2008, 7, 31), @@ -651,36 +651,36 @@ def test_offset(self, case): assert_offset_equal(offset, base, expected) on_offset_cases = [ - (QuarterEnd(1, startingMonth=1), datetime(2008, 1, 31), True), - (QuarterEnd(1, startingMonth=1), datetime(2007, 12, 31), False), - (QuarterEnd(1, startingMonth=1), datetime(2008, 2, 29), False), - (QuarterEnd(1, startingMonth=1), datetime(2007, 3, 30), False), - (QuarterEnd(1, startingMonth=1), datetime(2007, 3, 31), False), - (QuarterEnd(1, startingMonth=1), datetime(2008, 4, 30), True), - (QuarterEnd(1, startingMonth=1), datetime(2008, 5, 30), False), - (QuarterEnd(1, startingMonth=1), datetime(2008, 5, 31), False), - (QuarterEnd(1, startingMonth=1), datetime(2007, 6, 29), False), - (QuarterEnd(1, startingMonth=1), datetime(2007, 6, 30), False), - (QuarterEnd(1, startingMonth=2), datetime(2008, 1, 31), False), - (QuarterEnd(1, startingMonth=2), datetime(2007, 12, 31), False), - (QuarterEnd(1, startingMonth=2), datetime(2008, 2, 29), True), - (QuarterEnd(1, startingMonth=2), datetime(2007, 3, 30), False), - (QuarterEnd(1, startingMonth=2), datetime(2007, 3, 31), False), - (QuarterEnd(1, startingMonth=2), datetime(2008, 4, 30), False), - (QuarterEnd(1, startingMonth=2), datetime(2008, 5, 30), False), - (QuarterEnd(1, startingMonth=2), datetime(2008, 5, 31), True), - (QuarterEnd(1, startingMonth=2), datetime(2007, 6, 29), False), - (QuarterEnd(1, startingMonth=2), datetime(2007, 6, 30), False), - (QuarterEnd(1, startingMonth=3), datetime(2008, 1, 31), False), - (QuarterEnd(1, startingMonth=3), datetime(2007, 12, 31), True), - (QuarterEnd(1, startingMonth=3), datetime(2008, 2, 29), False), - (QuarterEnd(1, startingMonth=3), datetime(2007, 3, 30), False), - (QuarterEnd(1, startingMonth=3), datetime(2007, 3, 31), True), - (QuarterEnd(1, startingMonth=3), datetime(2008, 4, 30), False), - (QuarterEnd(1, startingMonth=3), datetime(2008, 5, 30), False), - (QuarterEnd(1, startingMonth=3), datetime(2008, 5, 31), False), - (QuarterEnd(1, startingMonth=3), datetime(2007, 6, 29), False), - (QuarterEnd(1, startingMonth=3), datetime(2007, 6, 30), True), + (QuarterEnd(1, month=1), datetime(2008, 1, 31), True), + (QuarterEnd(1, month=1), datetime(2007, 12, 31), False), + (QuarterEnd(1, month=1), datetime(2008, 2, 29), False), + (QuarterEnd(1, month=1), datetime(2007, 3, 30), False), + (QuarterEnd(1, month=1), datetime(2007, 3, 31), False), + (QuarterEnd(1, month=1), datetime(2008, 4, 30), True), + (QuarterEnd(1, month=1), datetime(2008, 5, 30), False), + (QuarterEnd(1, month=1), datetime(2008, 5, 31), False), + (QuarterEnd(1, month=1), datetime(2007, 6, 29), False), + (QuarterEnd(1, month=1), datetime(2007, 6, 30), False), + (QuarterEnd(1, month=2), datetime(2008, 1, 31), False), + (QuarterEnd(1, month=2), datetime(2007, 12, 31), False), + (QuarterEnd(1, month=2), datetime(2008, 2, 29), True), + (QuarterEnd(1, month=2), datetime(2007, 3, 30), False), + (QuarterEnd(1, month=2), datetime(2007, 3, 31), False), + (QuarterEnd(1, month=2), datetime(2008, 4, 30), False), + (QuarterEnd(1, month=2), datetime(2008, 5, 30), False), + (QuarterEnd(1, month=2), datetime(2008, 5, 31), True), + (QuarterEnd(1, month=2), datetime(2007, 6, 29), False), + (QuarterEnd(1, month=2), datetime(2007, 6, 30), False), + (QuarterEnd(1, month=3), datetime(2008, 1, 31), False), + (QuarterEnd(1, month=3), datetime(2007, 12, 31), True), + (QuarterEnd(1, month=3), datetime(2008, 2, 29), False), + (QuarterEnd(1, month=3), datetime(2007, 3, 30), False), + (QuarterEnd(1, month=3), datetime(2007, 3, 31), True), + (QuarterEnd(1, month=3), datetime(2008, 4, 30), False), + (QuarterEnd(1, month=3), datetime(2008, 5, 30), False), + (QuarterEnd(1, month=3), datetime(2008, 5, 31), False), + (QuarterEnd(1, month=3), datetime(2007, 6, 29), False), + (QuarterEnd(1, month=3), datetime(2007, 6, 30), True), ] @pytest.mark.parametrize("case", on_offset_cases) @@ -693,27 +693,27 @@ class TestBQuarterBegin(Base): _offset = BQuarterBegin def test_repr(self): - expected = "<BusinessQuarterBegin: startingMonth=3>" + expected = "<BusinessQuarterBegin: month=1>" assert repr(BQuarterBegin()) == expected - expected = "<BusinessQuarterBegin: startingMonth=3>" - assert repr(BQuarterBegin(startingMonth=3)) == expected - expected = "<BusinessQuarterBegin: startingMonth=1>" - assert repr(BQuarterBegin(startingMonth=1)) == expected + expected = "<BusinessQuarterBegin: month=3>" + assert repr(BQuarterBegin(month=3)) == expected + expected = "<BusinessQuarterBegin: month=1>" + assert repr(BQuarterBegin(month=1)) == expected def test_is_anchored(self): - assert BQuarterBegin(startingMonth=1).is_anchored() + assert BQuarterBegin(month=1).is_anchored() assert BQuarterBegin().is_anchored() - assert not BQuarterBegin(2, startingMonth=1).is_anchored() + assert not BQuarterBegin(2, month=1).is_anchored() def test_offset_corner_case(self): # corner - offset = BQuarterBegin(n=-1, startingMonth=1) + offset = BQuarterBegin(n=-1, month=1) assert datetime(2007, 4, 3) + offset == datetime(2007, 4, 2) offset_cases = [] offset_cases.append( ( - BQuarterBegin(startingMonth=1), + BQuarterBegin(month=1), { datetime(2008, 1, 1): datetime(2008, 4, 1), datetime(2008, 1, 31): datetime(2008, 4, 1), @@ -736,7 +736,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterBegin(startingMonth=2), + BQuarterBegin(month=2), { datetime(2008, 1, 1): datetime(2008, 2, 1), datetime(2008, 1, 31): datetime(2008, 2, 1), @@ -755,7 +755,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterBegin(startingMonth=1, n=0), + BQuarterBegin(month=1, n=0), { datetime(2008, 1, 1): datetime(2008, 1, 1), datetime(2007, 12, 31): datetime(2008, 1, 1), @@ -775,7 +775,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterBegin(startingMonth=1, n=-1), + BQuarterBegin(month=1, n=-1), { datetime(2008, 1, 1): datetime(2007, 10, 1), datetime(2008, 1, 31): datetime(2008, 1, 1), @@ -794,7 +794,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterBegin(startingMonth=1, n=2), + BQuarterBegin(month=1, n=2), { datetime(2008, 1, 1): datetime(2008, 7, 1), datetime(2008, 1, 15): datetime(2008, 7, 1), @@ -818,27 +818,27 @@ class TestBQuarterEnd(Base): _offset = BQuarterEnd def test_repr(self): - expected = "<BusinessQuarterEnd: startingMonth=3>" + expected = "<BusinessQuarterEnd: month=3>" assert repr(BQuarterEnd()) == expected - expected = "<BusinessQuarterEnd: startingMonth=3>" - assert repr(BQuarterEnd(startingMonth=3)) == expected - expected = "<BusinessQuarterEnd: startingMonth=1>" - assert repr(BQuarterEnd(startingMonth=1)) == expected + expected = "<BusinessQuarterEnd: month=3>" + assert repr(BQuarterEnd(month=3)) == expected + expected = "<BusinessQuarterEnd: month=1>" + assert repr(BQuarterEnd(month=1)) == expected def test_is_anchored(self): - assert BQuarterEnd(startingMonth=1).is_anchored() + assert BQuarterEnd(month=1).is_anchored() assert BQuarterEnd().is_anchored() - assert not BQuarterEnd(2, startingMonth=1).is_anchored() + assert not BQuarterEnd(2, month=1).is_anchored() def test_offset_corner_case(self): # corner - offset = BQuarterEnd(n=-1, startingMonth=1) + offset = BQuarterEnd(n=-1, month=1) assert datetime(2010, 1, 31) + offset == datetime(2010, 1, 29) offset_cases = [] offset_cases.append( ( - BQuarterEnd(startingMonth=1), + BQuarterEnd(month=1), { datetime(2008, 1, 1): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 4, 30), @@ -854,7 +854,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterEnd(startingMonth=2), + BQuarterEnd(month=2), { datetime(2008, 1, 1): datetime(2008, 2, 29), datetime(2008, 1, 31): datetime(2008, 2, 29), @@ -870,7 +870,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterEnd(startingMonth=1, n=0), + BQuarterEnd(month=1, n=0), { datetime(2008, 1, 1): datetime(2008, 1, 31), datetime(2008, 1, 31): datetime(2008, 1, 31), @@ -886,7 +886,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterEnd(startingMonth=1, n=-1), + BQuarterEnd(month=1, n=-1), { datetime(2008, 1, 1): datetime(2007, 10, 31), datetime(2008, 1, 31): datetime(2007, 10, 31), @@ -902,7 +902,7 @@ def test_offset_corner_case(self): offset_cases.append( ( - BQuarterEnd(startingMonth=1, n=2), + BQuarterEnd(month=1, n=2), { datetime(2008, 1, 31): datetime(2008, 7, 31), datetime(2008, 2, 15): datetime(2008, 7, 31), @@ -922,33 +922,33 @@ def test_offset(self, case): assert_offset_equal(offset, base, expected) on_offset_cases = [ - (BQuarterEnd(1, startingMonth=1), datetime(2008, 1, 31), True), - (BQuarterEnd(1, startingMonth=1), datetime(2007, 12, 31), False), - (BQuarterEnd(1, startingMonth=1), datetime(2008, 2, 29), False), - (BQuarterEnd(1, startingMonth=1), datetime(2007, 3, 30), False), - (BQuarterEnd(1, startingMonth=1), datetime(2007, 3, 31), False), - (BQuarterEnd(1, startingMonth=1), datetime(2008, 4, 30), True), - (BQuarterEnd(1, startingMonth=1), datetime(2008, 5, 30), False), - (BQuarterEnd(1, startingMonth=1), datetime(2007, 6, 29), False), - (BQuarterEnd(1, startingMonth=1), datetime(2007, 6, 30), False), - (BQuarterEnd(1, startingMonth=2), datetime(2008, 1, 31), False), - (BQuarterEnd(1, startingMonth=2), datetime(2007, 12, 31), False), - (BQuarterEnd(1, startingMonth=2), datetime(2008, 2, 29), True), - (BQuarterEnd(1, startingMonth=2), datetime(2007, 3, 30), False), - (BQuarterEnd(1, startingMonth=2), datetime(2007, 3, 31), False), - (BQuarterEnd(1, startingMonth=2), datetime(2008, 4, 30), False), - (BQuarterEnd(1, startingMonth=2), datetime(2008, 5, 30), True), - (BQuarterEnd(1, startingMonth=2), datetime(2007, 6, 29), False), - (BQuarterEnd(1, startingMonth=2), datetime(2007, 6, 30), False), - (BQuarterEnd(1, startingMonth=3), datetime(2008, 1, 31), False), - (BQuarterEnd(1, startingMonth=3), datetime(2007, 12, 31), True), - (BQuarterEnd(1, startingMonth=3), datetime(2008, 2, 29), False), - (BQuarterEnd(1, startingMonth=3), datetime(2007, 3, 30), True), - (BQuarterEnd(1, startingMonth=3), datetime(2007, 3, 31), False), - (BQuarterEnd(1, startingMonth=3), datetime(2008, 4, 30), False), - (BQuarterEnd(1, startingMonth=3), datetime(2008, 5, 30), False), - (BQuarterEnd(1, startingMonth=3), datetime(2007, 6, 29), True), - (BQuarterEnd(1, startingMonth=3), datetime(2007, 6, 30), False), + (BQuarterEnd(1, month=1), datetime(2008, 1, 31), True), + (BQuarterEnd(1, month=1), datetime(2007, 12, 31), False), + (BQuarterEnd(1, month=1), datetime(2008, 2, 29), False), + (BQuarterEnd(1, month=1), datetime(2007, 3, 30), False), + (BQuarterEnd(1, month=1), datetime(2007, 3, 31), False), + (BQuarterEnd(1, month=1), datetime(2008, 4, 30), True), + (BQuarterEnd(1, month=1), datetime(2008, 5, 30), False), + (BQuarterEnd(1, month=1), datetime(2007, 6, 29), False), + (BQuarterEnd(1, month=1), datetime(2007, 6, 30), False), + (BQuarterEnd(1, month=2), datetime(2008, 1, 31), False), + (BQuarterEnd(1, month=2), datetime(2007, 12, 31), False), + (BQuarterEnd(1, month=2), datetime(2008, 2, 29), True), + (BQuarterEnd(1, month=2), datetime(2007, 3, 30), False), + (BQuarterEnd(1, month=2), datetime(2007, 3, 31), False), + (BQuarterEnd(1, month=2), datetime(2008, 4, 30), False), + (BQuarterEnd(1, month=2), datetime(2008, 5, 30), True), + (BQuarterEnd(1, month=2), datetime(2007, 6, 29), False), + (BQuarterEnd(1, month=2), datetime(2007, 6, 30), False), + (BQuarterEnd(1, month=3), datetime(2008, 1, 31), False), + (BQuarterEnd(1, month=3), datetime(2007, 12, 31), True), + (BQuarterEnd(1, month=3), datetime(2008, 2, 29), False), + (BQuarterEnd(1, month=3), datetime(2007, 3, 30), True), + (BQuarterEnd(1, month=3), datetime(2007, 3, 31), False), + (BQuarterEnd(1, month=3), datetime(2008, 4, 30), False), + (BQuarterEnd(1, month=3), datetime(2008, 5, 30), False), + (BQuarterEnd(1, month=3), datetime(2007, 6, 29), True), + (BQuarterEnd(1, month=3), datetime(2007, 6, 30), False), ] @pytest.mark.parametrize("case", on_offset_cases) diff --git a/pandas/tests/tslibs/test_libfrequencies.py b/pandas/tests/tslibs/test_libfrequencies.py index 83f28f6b5dc01..0640d4da78772 100644 --- a/pandas/tests/tslibs/test_libfrequencies.py +++ b/pandas/tests/tslibs/test_libfrequencies.py @@ -13,9 +13,9 @@ ("D", "DEC"), (offsets.Day().freqstr, "DEC"), ("Q", "DEC"), - (offsets.QuarterEnd(startingMonth=12).freqstr, "DEC"), + (offsets.QuarterEnd(month=12).freqstr, "DEC"), ("Q-JAN", "JAN"), - (offsets.QuarterEnd(startingMonth=1).freqstr, "JAN"), + (offsets.QuarterEnd(month=1).freqstr, "JAN"), ("A-DEC", "DEC"), ("Y-DEC", "DEC"), (offsets.YearEnd().freqstr, "DEC"), diff --git a/pandas/tests/tslibs/test_to_offset.py b/pandas/tests/tslibs/test_to_offset.py index 27ddbb82f49a9..ec3b20a152f69 100644 --- a/pandas/tests/tslibs/test_to_offset.py +++ b/pandas/tests/tslibs/test_to_offset.py @@ -158,9 +158,9 @@ def test_to_offset_pd_timedelta(kwargs, expected): [ ("W", offsets.Week(weekday=6)), ("W-SUN", offsets.Week(weekday=6)), - ("Q", offsets.QuarterEnd(startingMonth=12)), - ("Q-DEC", offsets.QuarterEnd(startingMonth=12)), - ("Q-MAY", offsets.QuarterEnd(startingMonth=5)), + ("Q", offsets.QuarterEnd(month=12)), + ("Q-DEC", offsets.QuarterEnd(month=12)), + ("Q-MAY", offsets.QuarterEnd(month=5)), ("SM", offsets.SemiMonthEnd(day_of_month=15)), ("SM-15", offsets.SemiMonthEnd(day_of_month=15)), ("SM-1", offsets.SemiMonthEnd(day_of_month=1)),
Set default months for `BQuarterEnd`, `BQuarterBegin`, `QuarterEnd`, `QuarterBegin` classes in order; rename `startingMonth` parameter to `month` for those classes. Addresses #8435 and #5307 - [ ] closes #8435 #5307 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39890
2021-02-18T17:07:42Z
2021-08-17T00:30:49Z
null
2021-08-17T00:30:49Z
BUG: Bg gradient map text color fix
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 388c5dbf6a7ee..bdf1ea0f2ab6f 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -477,6 +477,7 @@ Other - Bug in :class:`Styler` where ``subset`` arg in methods raised an error for some valid multiindex slices (:issue:`33562`) - :class:`Styler` rendered HTML output minor alterations to support w3 good code standard (:issue:`39626`) - Bug in :class:`Styler` where rendered HTML was missing a column class identifier for certain header cells (:issue:`39716`) +- Bug in :meth:`Styler.background_gradient` where text-color was not determined correctly (:issue:`39888`) - Bug in :meth:`DataFrame.equals`, :meth:`Series.equals`, :meth:`Index.equals` with object-dtype containing ``np.datetime64("NaT")`` or ``np.timedelta64("NaT")`` (:issue:`39650`) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 877e146fd8681..18c1712dd617d 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1427,7 +1427,7 @@ def relative_luminance(rgba) -> float: The relative luminance as a value from 0 to 1 """ r, g, b = ( - x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4) + x / 12.92 if x <= 0.04045 else ((x + 0.055) / 1.055) ** 2.4 for x in rgba[:3] ) return 0.2126 * r + 0.7152 * g + 0.0722 * b diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index d134f33e15525..edb2592625a3d 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -1943,28 +1943,36 @@ def test_background_gradient(self): assert result[(1, 0)] == [("background-color", "#fff7fb"), ("color", "#000000")] @pytest.mark.parametrize( - "c_map,expected", + "cmap, expected", [ ( - None, + "PuBu", { - (0, 0): [("background-color", "#440154"), ("color", "#f1f1f1")], - (1, 0): [("background-color", "#fde725"), ("color", "#000000")], + (4, 5): [("background-color", "#86b0d3"), ("color", "#000000")], + (4, 6): [("background-color", "#83afd3"), ("color", "#f1f1f1")], }, ), ( "YlOrRd", { - (0, 0): [("background-color", "#ffffcc"), ("color", "#000000")], - (1, 0): [("background-color", "#800026"), ("color", "#f1f1f1")], + (4, 8): [("background-color", "#fd913e"), ("color", "#000000")], + (4, 9): [("background-color", "#fd8f3d"), ("color", "#f1f1f1")], + }, + ), + ( + None, + { + (7, 0): [("background-color", "#48c16e"), ("color", "#f1f1f1")], + (7, 1): [("background-color", "#4cc26c"), ("color", "#000000")], }, ), ], ) - def test_text_color_threshold(self, c_map, expected): - df = DataFrame([1, 2], columns=["A"]) - result = df.style.background_gradient(cmap=c_map)._compute().ctx - assert result == expected + def test_text_color_threshold(self, cmap, expected): + df = DataFrame(np.arange(100).reshape(10, 10)) + result = df.style.background_gradient(cmap=cmap, axis=None)._compute().ctx + for k in expected.keys(): + assert result[k] == expected[k] @pytest.mark.parametrize("text_color_threshold", [1.1, "1", -1, [2, 2]]) def test_text_color_threshold_raises(self, text_color_threshold):
- [x] closes #39888
https://api.github.com/repos/pandas-dev/pandas/pulls/39889
2021-02-18T16:50:29Z
2021-02-21T18:05:08Z
2021-02-21T18:05:08Z
2021-02-22T10:41:18Z
BUG: Breaking change to offsets.pyx - MonthOffset
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 34269185bccd6..cbd3b39a9a0f7 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -224,6 +224,7 @@ Other enhancements - :meth:`.GroupBy.any` and :meth:`.GroupBy.all` return a ``BooleanDtype`` for columns with nullable data types (:issue:`33449`) - Constructing a :class:`DataFrame` or :class:`Series` with the ``data`` argument being a Python iterable that is *not* a NumPy ``ndarray`` consisting of NumPy scalars will now result in a dtype with a precision the maximum of the NumPy scalars; this was already the case when ``data`` is a NumPy ``ndarray`` (:issue:`40908`) - Add keyword ``sort`` to :func:`pivot_table` to allow non-sorting of the result (:issue:`39143`) +- Date offset :class:`MonthBegin` can now be used as a period (:issue:`38859`) - .. --------------------------------------------------------------------------- @@ -801,7 +802,7 @@ I/O Period ^^^^^^ - Comparisons of :class:`Period` objects or :class:`Index`, :class:`Series`, or :class:`DataFrame` with mismatched ``PeriodDtype`` now behave like other mismatched-type comparisons, returning ``False`` for equals, ``True`` for not-equal, and raising ``TypeError`` for inequality checks (:issue:`39274`) -- +- Timestamp.to_period() fails for freq="MS" (:issue:`38914`) - Plotting diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx index 415bdf74db80a..c611a792f6756 100644 --- a/pandas/_libs/tslibs/dtypes.pyx +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -77,7 +77,7 @@ _period_code_map = { "Q-OCT": 2010, # Quarterly - October year end "Q-NOV": 2011, # Quarterly - November year end - "M": 3000, # Monthly + "M": 3000, # Monthly - month end "W-SUN": 4000, # Weekly - Sunday end of week "W-MON": 4001, # Weekly - Monday end of week @@ -110,6 +110,7 @@ _period_code_map.update({ "A": 1000, # Annual "W": 4000, # Weekly "C": 5000, # Custom Business Day + "MS": 3000, # Monthly - beginning of month }) cdef set _month_names = { diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 4e6e5485b2ade..8de885ee78306 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -2156,6 +2156,8 @@ cdef class QuarterBegin(QuarterOffset): # Month-Based Offset Classes cdef class MonthOffset(SingleConstructorOffset): + # _period_dtype_code = PeriodDtypeCode.M + def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False @@ -2185,21 +2187,44 @@ cdef class MonthOffset(SingleConstructorOffset): BaseOffset.__setstate__(self, state) +cdef class MonthBegin(MonthOffset): + """ + DateOffset of one month at beginning. + """ + + _period_dtype_code = PeriodDtypeCode.M + _prefix = "MS" + _day_opt = "start" + + cdef class MonthEnd(MonthOffset): """ DateOffset of one month end. """ + _period_dtype_code = PeriodDtypeCode.M _prefix = "M" _day_opt = "end" -cdef class MonthBegin(MonthOffset): +cdef class BusinessMonthBegin(MonthOffset): """ - DateOffset of one month at beginning. + DateOffset of one month at the first business day. + + Examples + -------- + >>> from pandas.tseries.offsets import BusinessMonthBegin + >>> ts=pd.Timestamp('2020-05-24 05:01:15') + >>> ts + BusinessMonthBegin() + Timestamp('2020-06-01 05:01:15') + >>> ts + BusinessMonthBegin(2) + Timestamp('2020-07-01 05:01:15') + >>> ts + BusinessMonthBegin(-3) + Timestamp('2020-03-02 05:01:15') """ - _prefix = "MS" - _day_opt = "start" + + _prefix = "BMS" + _day_opt = "business_start" cdef class BusinessMonthEnd(MonthOffset): @@ -2208,38 +2233,20 @@ cdef class BusinessMonthEnd(MonthOffset): Examples -------- - >>> from pandas.tseries.offset import BMonthEnd + >>> from pandas.tseries.offsets import BusinessMonthEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BMonthEnd() + >>> ts + BusinessMonthEnd() Timestamp('2020-05-29 05:01:15') - >>> ts + BMonthEnd(2) + >>> ts + BusinessMonthEnd(2) Timestamp('2020-06-30 05:01:15') - >>> ts + BMonthEnd(-2) + >>> ts + BusinessMonthEnd(-2) Timestamp('2020-03-31 05:01:15') """ + _prefix = "BM" _day_opt = "business_end" -cdef class BusinessMonthBegin(MonthOffset): - """ - DateOffset of one month at the first business day. - - Examples - -------- - >>> from pandas.tseries.offset import BMonthBegin - >>> ts=pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BMonthBegin() - Timestamp('2020-06-01 05:01:15') - >>> ts + BMonthBegin(2) - Timestamp('2020-07-01 05:01:15') - >>> ts + BMonthBegin(-3) - Timestamp('2020-03-02 05:01:15') - """ - _prefix = "BMS" - _day_opt = "business_start" - - # --------------------------------------------------------------------- # Semi-Month Based Offsets @@ -2261,7 +2268,7 @@ cdef class SemiMonthOffset(SingleConstructorOffset): if not self._min_day_of_month <= self.day_of_month <= 27: raise ValueError( "day_of_month must be " - f"{self._min_day_of_month}<=day_of_month<=27, " + f"{self._min_day_of_month} <= day_of_month <= 27, " f"got {self.day_of_month}" ) diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index 9110352d33c26..aecb95c5937f6 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -1,6 +1,5 @@ import pytest -from pandas._libs.tslibs.dtypes import _period_code_map from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG from pandas.errors import OutOfBoundsDatetime @@ -14,7 +13,7 @@ class TestFreqConversion: """Test frequency conversion of date objects""" - @pytest.mark.parametrize("freq", ["A", "Q", "M", "W", "B", "D"]) + @pytest.mark.parametrize("freq", ["A", "Q", "M", "MS", "W", "B", "D"]) def test_asfreq_near_zero(self, freq): # GH#19643, GH#19650 per = Period("0001-01-01", freq=freq) @@ -215,6 +214,7 @@ def test_conv_monthly(self): ival_M_to_S_end = Period( freq="S", year=2007, month=1, day=31, hour=23, minute=59, second=59 ) + ival_MS = Period(freq="MS", year=2007, month=1) assert ival_M.asfreq("A") == ival_M_to_A assert ival_M_end_of_year.asfreq("A") == ival_M_to_A @@ -235,6 +235,13 @@ def test_conv_monthly(self): assert ival_M.asfreq("S", "E") == ival_M_to_S_end assert ival_M.asfreq("M") == ival_M + assert ival_M.asfreq("M") != ival_MS + assert ival_M.asfreq("MS") == ival_MS + assert ival_M.asfreq("MS") != ival_M + assert ival_MS.asfreq("MS") == ival_MS + assert ival_MS.asfreq("MS") != ival_M + assert ival_MS.asfreq("M") == ival_M + assert ival_MS.asfreq("M") != ival_MS def test_conv_weekly(self): # frequency conversion tests: from Weekly Frequency @@ -269,6 +276,7 @@ def test_conv_weekly(self): ival_W_to_A = Period(freq="A", year=2007) ival_W_to_Q = Period(freq="Q", year=2007, quarter=1) ival_W_to_M = Period(freq="M", year=2007, month=1) + ival_W_to_MS = Period(freq="MS", year=2007, month=1) if Period(freq="D", year=2007, month=12, day=31).weekday == 6: ival_W_to_A_end_of_year = Period(freq="A", year=2007) @@ -311,6 +319,7 @@ def test_conv_weekly(self): assert ival_W_end_of_quarter.asfreq("Q") == ival_W_to_Q_end_of_quarter assert ival_W.asfreq("M") == ival_W_to_M + assert ival_W.asfreq("MS") == ival_W_to_MS assert ival_W_end_of_month.asfreq("M") == ival_W_to_M_end_of_month assert ival_W.asfreq("B", "S") == ival_W_to_B_start @@ -789,16 +798,19 @@ def test_asfreq_combined(self): assert result2.ordinal == expected.ordinal assert result2.freq == expected.freq - def test_asfreq_MS(self): - initial = Period("2013") - - assert initial.asfreq(freq="M", how="S") == Period("2013-01", "M") - - msg = INVALID_FREQ_ERR_MSG - with pytest.raises(ValueError, match=msg): - initial.asfreq(freq="MS", how="S") - - with pytest.raises(ValueError, match=msg): - Period("2013-01", "MS") - - assert _period_code_map.get("MS") is None + @pytest.mark.parametrize( + "year_month", ["2013-01", "2021-02", "2022-02", "2020-07", "2027-12"] + ) + def test_asfreq_M_vs_MS(self, year_month): + year = year_month.split("-")[0] + initial = Period(year) + ts0 = Period(year_month, freq="MS").to_timestamp() + ts1 = Period(year_month, freq="M").to_timestamp() + + assert initial.asfreq(freq="M", how="S") == Period(f"{year}-01", "M") + assert initial.asfreq(freq="M", how="S") != Period(f"{year}-01", "MS") + assert initial.asfreq(freq="MS", how="S") == Period(f"{year}-01", "MS") + assert initial.asfreq(freq="MS", how="S") != Period(f"{year}-01", "M") + assert initial.asfreq(freq="M", how="E") == Period(f"{year}-12", "M") + assert initial.asfreq(freq="MS", how="E") == Period(f"{year}-12", "MS") + assert ts0 == ts1 diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 3cc81ef851306..da2b9ec170cf0 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -220,6 +220,7 @@ def test_period_constructor_offsets(self): ) assert Period(200701, freq=offsets.MonthEnd()) == Period(200701, freq="M") + assert Period(200701, freq=offsets.MonthBegin()) == Period(200701, freq="MS") i1 = Period(ordinal=200701, freq=offsets.MonthEnd()) i2 = Period(ordinal=200701, freq="M")
Add ability to use class `MonthBegin` as a period. It would address #38914 and #38859. - [ ] closes #38914 #38859 - [x] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39887
2021-02-18T16:37:04Z
2021-08-17T00:29:21Z
null
2021-08-17T00:29:22Z
correction to get time interpolation correct
diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 2308f9edb4328..a234bf9800844 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -86,6 +86,8 @@ Tick, ) +from pandas.core.reshape.concat import concat + _shared_docs_kwargs: Dict[str, str] = {} @@ -859,6 +861,11 @@ def interpolate( Interpolate values according to different methods. """ result = self._upsample("asfreq") + if isinstance(result.index, DatetimeIndex): + obj = self._selected_obj + tmp = concat([obj, result]).sort_index().interpolate(method='time') + tmp = tmp[result.index] + result[...] = tmp[~tmp.index.duplicated(keep='first')] return result.interpolate( method=method, axis=axis, diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index cbf69696d5801..0b4a9bd10e0bf 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1816,3 +1816,14 @@ def test_resample_aggregate_functions_min_count(func): index=DatetimeIndex(["2020-03-31"], dtype="datetime64[ns]", freq="Q-DEC"), ) tm.assert_series_equal(result, expected) + + +def timeseries_interpolation(): + dates1 = date_range('2016-08-28', periods=4, freq='21H') + ts1 = Series([21 * i for i in range(4)], dates1, dtype=float) + nb_periods = (21 * 4) // 15 + dates2 = date_range('2016-08-28', periods=nb_periods, freq='15H') + expect = Series([15 * i for i in range(nb_periods)], dates2, dtype=float) + + result = ts1.resample('15H').interpolate(method='time') + tm.assert_series_equal(result, expect)
- [ ] closes #21351 - [ ] One test does not pass and I don't know why
https://api.github.com/repos/pandas-dev/pandas/pulls/39886
2021-02-18T15:24:43Z
2021-04-11T01:30:13Z
null
2021-04-11T01:30:13Z
[ArrayManager] GroupBy cython aggregations (no fallback)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a2162f2e66b36..b8ad3a96cae3d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -157,6 +157,7 @@ jobs: pytest pandas/tests/reductions/ --array-manager pytest pandas/tests/generic/test_generic.py --array-manager pytest pandas/tests/arithmetic/ --array-manager + pytest pandas/tests/groupby/aggregate/ --array-manager pytest pandas/tests/reshape/merge --array-manager # indexing subset (temporary since other tests don't pass yet) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 4df1d036e5321..45914519c0a94 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -41,6 +41,7 @@ ArrayLike, FrameOrSeries, FrameOrSeriesUnion, + Manager, ) from pandas.util._decorators import ( Appender, @@ -107,7 +108,10 @@ all_indexes_same, ) import pandas.core.indexes.base as ibase -from pandas.core.internals import BlockManager +from pandas.core.internals import ( + ArrayManager, + BlockManager, +) from pandas.core.series import Series from pandas.core.util.numba_ import maybe_use_numba @@ -1074,20 +1078,22 @@ def _iterate_slices(self) -> Iterable[Series]: def _cython_agg_general( self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1 ) -> DataFrame: - agg_mgr = self._cython_agg_blocks( + agg_mgr = self._cython_agg_manager( how, alt=alt, numeric_only=numeric_only, min_count=min_count ) return self._wrap_agged_manager(agg_mgr) - def _cython_agg_blocks( + def _cython_agg_manager( self, how: str, alt=None, numeric_only: bool = True, min_count: int = -1 - ) -> BlockManager: + ) -> Manager: - data: BlockManager = self._get_data_to_aggregate() + data: Manager = self._get_data_to_aggregate() if numeric_only: data = data.get_numeric_data(copy=False) + using_array_manager = isinstance(data, ArrayManager) + def cast_agg_result(result, values: ArrayLike, how: str) -> ArrayLike: # see if we can cast the values to the desired dtype # this may not be the original dtype @@ -1101,7 +1107,11 @@ def cast_agg_result(result, values: ArrayLike, how: str) -> ArrayLike: result = type(values)._from_sequence(result.ravel(), dtype=values.dtype) # Note this will have result.dtype == dtype from above - elif isinstance(result, np.ndarray) and result.ndim == 1: + elif ( + not using_array_manager + and isinstance(result, np.ndarray) + and result.ndim == 1 + ): # We went through a SeriesGroupByPath and need to reshape # GH#32223 includes case with IntegerArray values result = result.reshape(1, -1) @@ -1153,11 +1163,11 @@ def py_fallback(bvalues: ArrayLike) -> ArrayLike: result = mgr.blocks[0].values return result - def blk_func(bvalues: ArrayLike) -> ArrayLike: + def array_func(values: ArrayLike) -> ArrayLike: try: result = self.grouper._cython_operation( - "aggregate", bvalues, how, axis=1, min_count=min_count + "aggregate", values, how, axis=1, min_count=min_count ) except NotImplementedError: # generally if we have numeric_only=False @@ -1170,14 +1180,14 @@ def blk_func(bvalues: ArrayLike) -> ArrayLike: assert how == "ohlc" raise - result = py_fallback(bvalues) + result = py_fallback(values) - return cast_agg_result(result, bvalues, how) + return cast_agg_result(result, values, how) # TypeError -> we may have an exception in trying to aggregate # continue and exclude the block # NotImplementedError -> "ohlc" with wrong dtype - new_mgr = data.grouped_reduce(blk_func, ignore_failures=True) + new_mgr = data.grouped_reduce(array_func, ignore_failures=True) if not len(new_mgr): raise DataError("No numeric types to aggregate") @@ -1670,7 +1680,7 @@ def _wrap_frame_output(self, result, obj: DataFrame) -> DataFrame: else: return self.obj._constructor(result, index=obj.index, columns=result_index) - def _get_data_to_aggregate(self) -> BlockManager: + def _get_data_to_aggregate(self) -> Manager: obj = self._obj_with_exclusions if self.axis == 1: return obj.T._mgr @@ -1755,17 +1765,17 @@ def _wrap_transformed_output( return result - def _wrap_agged_manager(self, mgr: BlockManager) -> DataFrame: + def _wrap_agged_manager(self, mgr: Manager) -> DataFrame: if not self.as_index: index = np.arange(mgr.shape[1]) - mgr.axes[1] = ibase.Index(index) + mgr.set_axis(1, ibase.Index(index), verify_integrity=False) result = self.obj._constructor(mgr) self._insert_inaxis_grouper_inplace(result) result = result._consolidate() else: index = self.grouper.result_index - mgr.axes[1] = index + mgr.set_axis(1, index, verify_integrity=False) result = self.obj._constructor(mgr) if self.axis == 1: diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 97d1303824cd4..e0447378c4542 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -150,18 +150,20 @@ def _normalize_axis(axis): axis = 1 if axis == 0 else 0 return axis - # TODO can be shared - def set_axis(self, axis: int, new_labels: Index) -> None: + def set_axis( + self, axis: int, new_labels: Index, verify_integrity: bool = True + ) -> 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 verify_integrity: + 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" - ) + 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 @@ -254,6 +256,30 @@ def reduce( new_mgr = type(self)(result_arrays, [index, columns]) return new_mgr, indexer + def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: + """ + Apply grouped reduction function columnwise, returning a new ArrayManager. + + Parameters + ---------- + func : grouped reduction function + ignore_failures : bool, default False + Whether to drop columns where func raises TypeError. + + Returns + ------- + ArrayManager + """ + # TODO ignore_failures + result_arrays = [func(arr) for arr in self.arrays] + + if len(result_arrays) == 0: + index = Index([None]) # placeholder + else: + index = Index(range(result_arrays[0].shape[0])) + + return type(self)(result_arrays, [index, self.items]) + def operate_blockwise(self, other: ArrayManager, array_op) -> ArrayManager: """ Apply array_op blockwise with another (aligned) BlockManager. @@ -369,7 +395,7 @@ def apply_with_block(self: T, f, align_keys=None, **kwargs) -> T: 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": + elif arr.dtype.kind == "m" and not isinstance(arr, np.ndarray): # TimedeltaArray needs to be converted to ndarray for TimedeltaBlock arr = arr._data # type: ignore[union-attr] if isinstance(arr, np.ndarray): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index ab287ca4087bc..e013a7f680d6f 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -234,16 +234,19 @@ def shape(self) -> Shape: def ndim(self) -> int: return len(self.axes) - def set_axis(self, axis: int, new_labels: Index) -> None: + def set_axis( + self, axis: int, new_labels: Index, verify_integrity: bool = True + ) -> None: # Caller is responsible for ensuring we have an Index object. - old_len = len(self.axes[axis]) - new_len = len(new_labels) + if verify_integrity: + 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" - ) + 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 @@ -282,7 +285,7 @@ def get_dtypes(self): return algos.take_nd(dtypes, self.blknos, allow_fill=False) @property - def arrays(self): + def arrays(self) -> List[ArrayLike]: """ Quick access to the backing arrays of the Blocks. @@ -290,8 +293,7 @@ def arrays(self): Not to be used in actual code, and return value is not the same as the ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs). """ - for blk in self.blocks: - yield blk.values + return [blk.values for blk in self.blocks] def __getstate__(self): block_values = [b.values for b in self.blocks] diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 276c0adfdb485..96413758e9cb0 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -10,6 +10,7 @@ import pytest from pandas.errors import PerformanceWarning +import pandas.util._test_decorators as td from pandas.core.dtypes.common import is_integer_dtype @@ -45,6 +46,7 @@ def test_agg_regression1(tsframe): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) quantile/describe def test_agg_must_agg(df): grouped = df.groupby("A")["C"] @@ -134,6 +136,7 @@ def test_groupby_aggregation_multi_level_column(): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) non-cython agg def test_agg_apply_corner(ts, tsframe): # nothing to group, all NA grouped = ts.groupby(ts * np.nan) @@ -212,6 +215,7 @@ def test_aggregate_str_func(tsframe, groupbyfunc): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) non-cython agg def test_agg_str_with_kwarg_axis_1_raises(df, reduction_func): gb = df.groupby(level=0) if reduction_func in ("idxmax", "idxmin"): @@ -491,6 +495,7 @@ def test_agg_index_has_complex_internals(index): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) agg py_fallback def test_agg_split_block(): # https://github.com/pandas-dev/pandas/issues/31522 df = DataFrame( @@ -508,6 +513,7 @@ def test_agg_split_block(): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) agg py_fallback def test_agg_split_object_part_datetime(): # https://github.com/pandas-dev/pandas/pull/31616 df = DataFrame( @@ -1199,6 +1205,7 @@ def test_aggregate_datetime_objects(): tm.assert_series_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) agg py_fallback def test_aggregate_numeric_object_dtype(): # https://github.com/pandas-dev/pandas/issues/39329 # simplified case: multiple object columns where one is all-NaN diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index f9b45f4d9f4cf..4a8aabe41b754 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -281,7 +281,7 @@ def test_read_only_buffer_source_agg(agg): "species": ["setosa", "setosa", "setosa", "setosa", "setosa"], } ) - df._mgr.blocks[0].values.flags.writeable = False + df._mgr.arrays[0].flags.writeable = False result = df.groupby(["species"]).agg({"sepal_length": agg}) expected = df.copy().groupby(["species"]).agg({"sepal_length": agg}) diff --git a/pandas/tests/groupby/aggregate/test_other.py b/pandas/tests/groupby/aggregate/test_other.py index c566c45b582d7..8dd1ac33bf8ae 100644 --- a/pandas/tests/groupby/aggregate/test_other.py +++ b/pandas/tests/groupby/aggregate/test_other.py @@ -8,6 +8,8 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import ( DataFrame, @@ -412,6 +414,7 @@ def __call__(self, x): tm.assert_frame_equal(result, expected) +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) columns with ndarrays def test_agg_over_numpy_arrays(): # GH 3788 df = DataFrame(
xref https://github.com/pandas-dev/pandas/issues/39146/ This implements one aspect of groupby: basic cython-based aggregations (so not yet general apply, python fallback, or other methods, etc, only the basic aggregations that take the `_cython_agg_general` path). Similarly to how we currently have a `_cython_agg_blocks`, this PR adds an equivalent `_cython_agg_arrays` which calls the cython operation on each column instead of each block.
https://api.github.com/repos/pandas-dev/pandas/pulls/39885
2021-02-18T14:35:58Z
2021-02-25T13:29:09Z
2021-02-25T13:29:09Z
2021-02-25T17:49:00Z
CLN: remove redundant code related to Styler
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 93f63c23ac2d1..7b4921080e2e1 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2403,57 +2403,3 @@ def need_slice(obj) -> bool: or obj.stop is not None or (obj.step is not None and obj.step != 1) ) - - -def non_reducing_slice(slice_): - """ - Ensure that a slice doesn't reduce to a Series or Scalar. - - Any user-passed `subset` should have this called on it - to make sure we're always working with DataFrames. - """ - # default to column slice, like DataFrame - # ['A', 'B'] -> IndexSlices[:, ['A', 'B']] - kinds = (ABCSeries, np.ndarray, Index, list, str) - if isinstance(slice_, kinds): - slice_ = IndexSlice[:, slice_] - - def pred(part) -> bool: - """ - Returns - ------- - bool - True if slice does *not* reduce, - False if `part` is a tuple. - """ - # true when slice does *not* reduce, False when part is a tuple, - # i.e. MultiIndex slice - if isinstance(part, tuple): - # GH#39421 check for sub-slice: - return any((isinstance(s, slice) or is_list_like(s)) for s in part) - else: - return isinstance(part, slice) or is_list_like(part) - - if not is_list_like(slice_): - if not isinstance(slice_, slice): - # a 1-d slice, like df.loc[1] - slice_ = [[slice_]] - else: - # slice(a, b, c) - slice_ = [slice_] # to tuplize later - else: - slice_ = [part if pred(part) else [part] for part in slice_] - return tuple(slice_) - - -def maybe_numeric_slice(df, slice_, include_bool: bool = False): - """ - Want nice defaults for background_gradient that don't break - with non-numeric data. But if slice_ is passed go with that. - """ - if slice_ is None: - dtypes = [np.number] - if include_bool: - dtypes.append(bool) - slice_ = IndexSlice[:, df.select_dtypes(include=dtypes).columns] - return slice_ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 1e2148125a9d1..8000c3e508467 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -37,6 +37,7 @@ from pandas.util._decorators import doc from pandas.core.dtypes.common import is_float +from pandas.core.dtypes.generic import ABCSeries import pandas as pd from pandas.api.types import ( @@ -47,10 +48,7 @@ import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame -from pandas.core.indexing import ( - maybe_numeric_slice, - non_reducing_slice, -) +from pandas.core.indexes.api import Index jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.") CSSSequence = Sequence[Tuple[str, Union[str, int, float]]] @@ -625,7 +623,7 @@ def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> Styler row_locs = range(len(self.data)) col_locs = range(len(self.data.columns)) else: - subset = non_reducing_slice(subset) + subset = _non_reducing_slice(subset) if len(subset) == 1: subset = subset, self.data.columns @@ -851,7 +849,7 @@ def _apply( **kwargs, ) -> Styler: subset = slice(None) if subset is None else subset - subset = non_reducing_slice(subset) + subset = _non_reducing_slice(subset) data = self.data.loc[subset] if axis is not None: result = data.apply(func, axis=axis, result_type="expand", **kwargs) @@ -954,7 +952,7 @@ def _applymap(self, func: Callable, subset=None, **kwargs) -> Styler: func = partial(func, **kwargs) # applymap doesn't take kwargs? if subset is None: subset = pd.IndexSlice[:] - subset = non_reducing_slice(subset) + subset = _non_reducing_slice(subset) result = self.data.loc[subset].applymap(func) self._update_ctx(result) return self @@ -1304,7 +1302,7 @@ def hide_columns(self, subset) -> Styler: ------- self : Styler """ - subset = non_reducing_slice(subset) + subset = _non_reducing_slice(subset) hidden_df = self.data.loc[subset] self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns) return self @@ -1379,8 +1377,9 @@ def background_gradient( of the data is extended by ``low * (x.max() - x.min())`` and ``high * (x.max() - x.min())`` before normalizing. """ - subset = maybe_numeric_slice(self.data, subset) - subset = non_reducing_slice(subset) + if subset is None: + subset = self.data.select_dtypes(include=np.number).columns + self.apply( self._background_gradient, cmap=cmap, @@ -1613,8 +1612,9 @@ def bar( "(eg: color=['#d65f5f', '#5fba7d'])" ) - subset = maybe_numeric_slice(self.data, subset) - subset = non_reducing_slice(subset) + if subset is None: + subset = self.data.select_dtypes(include=np.number).columns + self.apply( self._bar, subset=subset, @@ -2088,3 +2088,44 @@ def _maybe_convert_css_to_tuples(style: CSSProperties) -> CSSSequence: f"for example 'attr: val;'. '{style}' was given." ) return style + + +def _non_reducing_slice(slice_): + """ + Ensure that a slice doesn't reduce to a Series or Scalar. + + Any user-passed `subset` should have this called on it + to make sure we're always working with DataFrames. + """ + # default to column slice, like DataFrame + # ['A', 'B'] -> IndexSlices[:, ['A', 'B']] + kinds = (ABCSeries, np.ndarray, Index, list, str) + if isinstance(slice_, kinds): + slice_ = pd.IndexSlice[:, slice_] + + def pred(part) -> bool: + """ + Returns + ------- + bool + True if slice does *not* reduce, + False if `part` is a tuple. + """ + # true when slice does *not* reduce, False when part is a tuple, + # i.e. MultiIndex slice + if isinstance(part, tuple): + # GH#39421 check for sub-slice: + return any((isinstance(s, slice) or is_list_like(s)) for s in part) + else: + return isinstance(part, slice) or is_list_like(part) + + if not is_list_like(slice_): + if not isinstance(slice_, slice): + # a 1-d slice, like df.loc[1] + slice_ = [[slice_]] + else: + # slice(a, b, c) + slice_ = [slice_] # to tuplize later + else: + slice_ = [part if pred(part) else [part] for part in slice_] + return tuple(slice_) diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index 377a0f11b17d8..4c3653b5cf64d 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -12,7 +12,6 @@ Timestamp, ) import pandas._testing as tm -from pandas.core.indexing import non_reducing_slice from pandas.tests.indexing.common import _mklbl @@ -769,59 +768,6 @@ def test_int_series_slicing(self, multiindex_year_month_day_dataframe_random_dat expected = ymd.reindex(s.index[5:]) tm.assert_frame_equal(result, expected) - def test_non_reducing_slice_on_multiindex(self): - # GH 19861 - dic = { - ("a", "d"): [1, 4], - ("a", "c"): [2, 3], - ("b", "c"): [3, 2], - ("b", "d"): [4, 1], - } - df = DataFrame(dic, index=[0, 1]) - idx = pd.IndexSlice - slice_ = idx[:, idx["b", "d"]] - tslice_ = non_reducing_slice(slice_) - - result = df.loc[tslice_] - expected = DataFrame({("b", "d"): [4, 1]}) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "slice_", - [ - pd.IndexSlice[:, :], - # check cols - pd.IndexSlice[:, pd.IndexSlice[["a"]]], # inferred deeper need list - pd.IndexSlice[:, pd.IndexSlice[["a"], ["c"]]], # inferred deeper need list - pd.IndexSlice[:, pd.IndexSlice["a", "c", :]], - pd.IndexSlice[:, pd.IndexSlice["a", :, "e"]], - pd.IndexSlice[:, pd.IndexSlice[:, "c", "e"]], - pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d"], :]], # check list - pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], :]], # allow missing - pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], "e"]], # no slice - # check rows - pd.IndexSlice[pd.IndexSlice[["U"]], :], # inferred deeper need list - pd.IndexSlice[pd.IndexSlice[["U"], ["W"]], :], # inferred deeper need list - pd.IndexSlice[pd.IndexSlice["U", "W", :], :], - pd.IndexSlice[pd.IndexSlice["U", :, "Y"], :], - pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], :], - pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z"]], :], # check list - pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z", "-"]], :], # allow missing - pd.IndexSlice[pd.IndexSlice["U", "W", ["Y", "Z", "-"]], :], # no slice - # check simultaneous - pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], pd.IndexSlice["a", "c", :]], - ], - ) - def test_non_reducing_multi_slice_on_multiindex(self, slice_): - # GH 33562 - cols = pd.MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]) - idxs = pd.MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]]) - df = DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs) - - expected = df.loc[slice_] - result = df.loc[non_reducing_slice(slice_)] - tm.assert_frame_equal(result, expected) - def test_loc_slice_negative_stepsize(self): # GH#38071 mi = MultiIndex.from_product([["a", "b"], [0, 1]]) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index efd99df9a5e4f..842394ac75f3e 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -23,10 +23,6 @@ timedelta_range, ) import pandas._testing as tm -from pandas.core.indexing import ( - maybe_numeric_slice, - non_reducing_slice, -) from pandas.tests.indexing.common import _mklbl from pandas.tests.indexing.test_floats import gen_obj @@ -794,53 +790,6 @@ def test_range_in_series_indexing(self, size): s.loc[range(2)] = 43 tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1])) - @pytest.mark.parametrize( - "slc", - [ - pd.IndexSlice[:, :], - pd.IndexSlice[:, 1], - pd.IndexSlice[1, :], - pd.IndexSlice[[1], [1]], - pd.IndexSlice[1, [1]], - pd.IndexSlice[[1], 1], - pd.IndexSlice[1], - pd.IndexSlice[1, 1], - slice(None, None, None), - [0, 1], - np.array([0, 1]), - Series([0, 1]), - ], - ) - def test_non_reducing_slice(self, slc): - df = DataFrame([[0, 1], [2, 3]]) - - tslice_ = non_reducing_slice(slc) - assert isinstance(df.loc[tslice_], DataFrame) - - @pytest.mark.parametrize("box", [list, Series, np.array]) - def test_list_slice(self, box): - # like dataframe getitem - subset = box(["A"]) - - df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"]) - expected = pd.IndexSlice[:, ["A"]] - - result = non_reducing_slice(subset) - tm.assert_frame_equal(df.loc[result], df.loc[expected]) - - def test_maybe_numeric_slice(self): - df = DataFrame({"A": [1, 2], "B": ["c", "d"], "C": [True, False]}) - result = maybe_numeric_slice(df, slice_=None) - expected = pd.IndexSlice[:, ["A"]] - assert result == expected - - result = maybe_numeric_slice(df, None, include_bool=True) - expected = pd.IndexSlice[:, ["A", "C"]] - assert all(result[1] == expected[1]) - result = maybe_numeric_slice(df, [1]) - expected = [1] - assert result == expected - def test_partial_boolean_frame_indexing(self): # GH 17170 df = DataFrame( diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index b8df18d593667..1e4a3b10bdb01 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -16,6 +16,7 @@ Styler, _get_level_lengths, _maybe_convert_css_to_tuples, + _non_reducing_slice, ) @@ -1975,6 +1976,93 @@ def test_w3_html_format(self): """ assert expected == s.render() + @pytest.mark.parametrize( + "slc", + [ + pd.IndexSlice[:, :], + pd.IndexSlice[:, 1], + pd.IndexSlice[1, :], + pd.IndexSlice[[1], [1]], + pd.IndexSlice[1, [1]], + pd.IndexSlice[[1], 1], + pd.IndexSlice[1], + pd.IndexSlice[1, 1], + slice(None, None, None), + [0, 1], + np.array([0, 1]), + pd.Series([0, 1]), + ], + ) + def test_non_reducing_slice(self, slc): + df = DataFrame([[0, 1], [2, 3]]) + + tslice_ = _non_reducing_slice(slc) + assert isinstance(df.loc[tslice_], DataFrame) + + @pytest.mark.parametrize("box", [list, pd.Series, np.array]) + def test_list_slice(self, box): + # like dataframe getitem + subset = box(["A"]) + + df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"]) + expected = pd.IndexSlice[:, ["A"]] + + result = _non_reducing_slice(subset) + tm.assert_frame_equal(df.loc[result], df.loc[expected]) + + def test_non_reducing_slice_on_multiindex(self): + # GH 19861 + dic = { + ("a", "d"): [1, 4], + ("a", "c"): [2, 3], + ("b", "c"): [3, 2], + ("b", "d"): [4, 1], + } + df = DataFrame(dic, index=[0, 1]) + idx = pd.IndexSlice + slice_ = idx[:, idx["b", "d"]] + tslice_ = _non_reducing_slice(slice_) + + result = df.loc[tslice_] + expected = DataFrame({("b", "d"): [4, 1]}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "slice_", + [ + pd.IndexSlice[:, :], + # check cols + pd.IndexSlice[:, pd.IndexSlice[["a"]]], # inferred deeper need list + pd.IndexSlice[:, pd.IndexSlice[["a"], ["c"]]], # inferred deeper need list + pd.IndexSlice[:, pd.IndexSlice["a", "c", :]], + pd.IndexSlice[:, pd.IndexSlice["a", :, "e"]], + pd.IndexSlice[:, pd.IndexSlice[:, "c", "e"]], + pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d"], :]], # check list + pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], :]], # allow missing + pd.IndexSlice[:, pd.IndexSlice["a", ["c", "d", "-"], "e"]], # no slice + # check rows + pd.IndexSlice[pd.IndexSlice[["U"]], :], # inferred deeper need list + pd.IndexSlice[pd.IndexSlice[["U"], ["W"]], :], # inferred deeper need list + pd.IndexSlice[pd.IndexSlice["U", "W", :], :], + pd.IndexSlice[pd.IndexSlice["U", :, "Y"], :], + pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], :], + pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z"]], :], # check list + pd.IndexSlice[pd.IndexSlice[:, "W", ["Y", "Z", "-"]], :], # allow missing + pd.IndexSlice[pd.IndexSlice["U", "W", ["Y", "Z", "-"]], :], # no slice + # check simultaneous + pd.IndexSlice[pd.IndexSlice[:, "W", "Y"], pd.IndexSlice["a", "c", :]], + ], + ) + def test_non_reducing_multi_slice_on_multiindex(self, slice_): + # GH 33562 + cols = pd.MultiIndex.from_product([["a", "b"], ["c", "d"], ["e", "f"]]) + idxs = pd.MultiIndex.from_product([["U", "V"], ["W", "X"], ["Y", "Z"]]) + df = DataFrame(np.arange(64).reshape(8, 8), columns=cols, index=idxs) + + expected = df.loc[slice_] + result = df.loc[_non_reducing_slice(slice_)] + tm.assert_frame_equal(result, expected) + @td.skip_if_no_mpl class TestStylerMatplotlibDep:
`non_reducing_slice` is performed within the `apply` so no need to execute twice. `maybe_numeric_slice` is a convoluted wrapper for selecting numeric columns so removed.
https://api.github.com/repos/pandas-dev/pandas/pulls/39884
2021-02-18T13:24:27Z
2021-02-19T01:32:02Z
2021-02-19T01:32:02Z
2021-02-19T06:11:37Z
Backport PR #39869 on branch 1.2.x (DOC: update link to user guide)
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 396108bab47b7..c5324165ef68e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3951,8 +3951,8 @@ def lookup(self, row_labels, col_labels) -> np.ndarray: .. deprecated:: 1.2.0 DataFrame.lookup is deprecated, use DataFrame.melt and DataFrame.loc instead. - For an example see :meth:`~pandas.DataFrame.lookup` - in the user guide. + For further details see + :ref:`Looking up values by index/column labels <indexing.lookup>`. Parameters ----------
Backport PR #39869: DOC: update link to user guide
https://api.github.com/repos/pandas-dev/pandas/pulls/39883
2021-02-18T10:10:27Z
2021-02-18T13:14:46Z
2021-02-18T13:14:46Z
2021-02-18T13:14:47Z
TST: port Dim2CompatTests
diff --git a/pandas/core/ops/mask_ops.py b/pandas/core/ops/mask_ops.py index a9edb2d138246..501bc0159e641 100644 --- a/pandas/core/ops/mask_ops.py +++ b/pandas/core/ops/mask_ops.py @@ -179,6 +179,6 @@ def kleene_and( return result, mask -def raise_for_nan(value, method): +def raise_for_nan(value, method: str): if lib.is_float(value) and np.isnan(value): raise ValueError(f"Cannot perform logical '{method}' with floating NaN") diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py index 9cf3bdab40d0b..910b43a2cd148 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -43,6 +43,7 @@ class TestMyDtype(BaseDtypeTests): """ from pandas.tests.extension.base.casting import BaseCastingTests # noqa from pandas.tests.extension.base.constructors import BaseConstructorsTests # noqa +from pandas.tests.extension.base.dim2 import Dim2CompatTests # noqa from pandas.tests.extension.base.dtype import BaseDtypeTests # noqa from pandas.tests.extension.base.getitem import BaseGetitemTests # noqa from pandas.tests.extension.base.groupby import BaseGroupbyTests # noqa diff --git a/pandas/tests/extension/base/dim2.py b/pandas/tests/extension/base/dim2.py new file mode 100644 index 0000000000000..c6455ce15533a --- /dev/null +++ b/pandas/tests/extension/base/dim2.py @@ -0,0 +1,217 @@ +""" +Tests for 2D compatibility. +""" +import numpy as np +import pytest + +from pandas.compat import np_version_under1p17 + +import pandas as pd +from pandas.core.arrays import ( + FloatingArray, + IntegerArray, +) +from pandas.tests.extension.base.base import BaseExtensionTests + + +def maybe_xfail_masked_reductions(arr, request): + if ( + isinstance(arr, (FloatingArray, IntegerArray)) + and np_version_under1p17 + and arr.ndim == 2 + ): + mark = pytest.mark.xfail(reason="masked_reductions does not implement") + request.node.add_marker(mark) + + +class Dim2CompatTests(BaseExtensionTests): + def test_take_2d(self, data): + arr2d = data.reshape(-1, 1) + + result = arr2d.take([0, 0, -1], axis=0) + + expected = data.take([0, 0, -1]).reshape(-1, 1) + self.assert_extension_array_equal(result, expected) + + def test_repr_2d(self, data): + # this could fail in a corner case where an element contained the name + res = repr(data.reshape(1, -1)) + assert res.count(f"<{type(data).__name__}") == 1 + + res = repr(data.reshape(-1, 1)) + assert res.count(f"<{type(data).__name__}") == 1 + + def test_reshape(self, data): + arr2d = data.reshape(-1, 1) + assert arr2d.shape == (data.size, 1) + assert len(arr2d) == len(data) + + arr2d = data.reshape((-1, 1)) + assert arr2d.shape == (data.size, 1) + assert len(arr2d) == len(data) + + with pytest.raises(ValueError): + data.reshape((data.size, 2)) + with pytest.raises(ValueError): + data.reshape(data.size, 2) + + def test_getitem_2d(self, data): + arr2d = data.reshape(1, -1) + + result = arr2d[0] + self.assert_extension_array_equal(result, data) + + with pytest.raises(IndexError): + arr2d[1] + + with pytest.raises(IndexError): + arr2d[-2] + + result = arr2d[:] + self.assert_extension_array_equal(result, arr2d) + + result = arr2d[:, :] + self.assert_extension_array_equal(result, arr2d) + + result = arr2d[:, 0] + expected = data[[0]] + self.assert_extension_array_equal(result, expected) + + # dimension-expanding getitem on 1D + result = data[:, np.newaxis] + self.assert_extension_array_equal(result, arr2d.T) + + def test_iter_2d(self, data): + arr2d = data.reshape(1, -1) + + objs = list(iter(arr2d)) + assert len(objs) == arr2d.shape[0] + + for obj in objs: + assert isinstance(obj, type(data)) + assert obj.dtype == data.dtype + assert obj.ndim == 1 + assert len(obj) == arr2d.shape[1] + + def test_concat_2d(self, data): + left = data.reshape(-1, 1) + right = left.copy() + + # axis=0 + result = left._concat_same_type([left, right], axis=0) + expected = data._concat_same_type([data, data]).reshape(-1, 1) + self.assert_extension_array_equal(result, expected) + + # axis=1 + result = left._concat_same_type([left, right], axis=1) + expected = data.repeat(2).reshape(-1, 2) + self.assert_extension_array_equal(result, expected) + + # axis > 1 -> invalid + with pytest.raises(ValueError): + left._concat_same_type([left, right], axis=2) + + @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) + def test_reductions_2d_axis_none(self, data, method, request): + if not hasattr(data, method): + pytest.skip("test is not applicable for this type/dtype") + + arr2d = data.reshape(1, -1) + maybe_xfail_masked_reductions(arr2d, request) + + err_expected = None + err_result = None + try: + expected = getattr(data, method)() + except Exception as err: + # if the 1D reduction is invalid, the 2D reduction should be as well + err_expected = err + try: + result = getattr(arr2d, method)(axis=None) + except Exception as err2: + err_result = err2 + + else: + result = getattr(arr2d, method)(axis=None) + + if err_result is not None or err_expected is not None: + assert type(err_result) == type(err_expected) + return + + assert result == expected # TODO: or matching NA + + @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) + def test_reductions_2d_axis0(self, data, method, request): + if not hasattr(data, method): + pytest.skip("test is not applicable for this type/dtype") + + arr2d = data.reshape(1, -1) + maybe_xfail_masked_reductions(arr2d, request) + + kwargs = {} + if method == "std": + # pass ddof=0 so we get all-zero std instead of all-NA std + kwargs["ddof"] = 0 + + try: + result = getattr(arr2d, method)(axis=0, **kwargs) + except Exception as err: + try: + getattr(data, method)() + except Exception as err2: + assert type(err) == type(err2) + return + else: + raise AssertionError("Both reductions should raise or neither") + + if method in ["mean", "median", "sum", "prod"]: + # std and var are not dtype-preserving + expected = data + if method in ["sum", "prod"] and data.dtype.kind in ["i", "u"]: + # FIXME: kludge + if data.dtype.kind == "i": + dtype = pd.Int64Dtype + else: + dtype = pd.UInt64Dtype + + expected = data.astype(dtype) + if type(expected) != type(data): + mark = pytest.mark.xfail( + reason="IntegerArray.astype is broken GH#38983" + ) + request.node.add_marker(mark) + assert type(expected) == type(data), type(expected) + assert dtype == expected.dtype + + self.assert_extension_array_equal(result, expected) + elif method == "std": + self.assert_extension_array_equal(result, data - data) + # punt on method == "var" + + @pytest.mark.parametrize("method", ["mean", "median", "var", "std", "sum", "prod"]) + def test_reductions_2d_axis1(self, data, method, request): + if not hasattr(data, method): + pytest.skip("test is not applicable for this type/dtype") + + arr2d = data.reshape(1, -1) + maybe_xfail_masked_reductions(arr2d, request) + + try: + result = getattr(arr2d, method)(axis=1) + except Exception as err: + try: + getattr(data, method)() + except Exception as err2: + assert type(err) == type(err2) + return + else: + raise AssertionError("Both reductions should raise or neither") + + # not necesarrily type/dtype-preserving, so weaker assertions + assert result.shape == (1,) + expected_scalar = getattr(data, method)() + if pd.isna(result[0]): + # TODO: require matching NA + assert pd.isna(expected_scalar), expected_scalar + else: + assert result[0] == expected_scalar diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index 6c5963402b3d7..33589027c0d0f 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -235,3 +235,7 @@ class TestGroupby(BaseDatetimeTests, base.BaseGroupbyTests): class TestPrinting(BaseDatetimeTests, base.BasePrintingTests): pass + + +class Test2DCompat(BaseDatetimeTests, base.Dim2CompatTests): + pass diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index 17f29e02a2883..ef6a6e6098a19 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -415,3 +415,7 @@ def test_setitem_loc_iloc_slice(self, data): @skip_nested class TestParsing(BaseNumPyTests, base.BaseParsingTests): pass + + +class Test2DCompat(BaseNumPyTests, base.Dim2CompatTests): + pass diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index bbb991259ac29..4c845055b56c4 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -184,3 +184,7 @@ class TestParsing(BasePeriodTests, base.BaseParsingTests): @pytest.mark.parametrize("engine", ["c", "python"]) def test_EA_types(self, engine, data): super().test_EA_types(engine, data) + + +class Test2DCompat(BasePeriodTests, base.Dim2CompatTests): + pass
broken off from #38992
https://api.github.com/repos/pandas-dev/pandas/pulls/39880
2021-02-18T02:03:01Z
2021-02-25T00:36:57Z
2021-02-25T00:36:57Z
2021-02-25T01:50:25Z
Revert accidental commit
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index e091eec4e2c41..b41c432dff172 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -225,66 +225,51 @@ def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion: results = [] keys = [] - ndims = [] # degenerate case - # if selected_obj.ndim == 1: - for a in arg: - # colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj) - try: - # new_res = colg.aggregate(a) - print('selected_obj:', type(selected_obj)) - print(selected_obj) - print('###') - new_res = selected_obj.aggregate(a) - print(new_res) - - except TypeError: - pass - else: - results.append(new_res) - if isinstance(new_res, ABCNDFrame): - ndims.append(new_res.ndim) + if selected_obj.ndim == 1: + for a in arg: + colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj) + try: + new_res = colg.aggregate(a) + + except TypeError: + pass else: - ndims.append(0) + results.append(new_res) - # make sure we find a good name - name = com.get_callable_name(a) or a - keys.append(name) + # make sure we find a good name + name = com.get_callable_name(a) or a + keys.append(name) # multiples - # else: - # for index, col in enumerate(selected_obj): - # colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index]) - # try: - # new_res = colg.aggregate(arg) - # except (TypeError, DataError): - # pass - # except ValueError as err: - # # cannot aggregate - # if "Must produce aggregated value" in str(err): - # # raised directly in _aggregate_named - # pass - # elif "no results" in str(err): - # # raised directly in _aggregate_multiple_funcs - # pass - # else: - # raise - # else: - # results.append(new_res) - # keys.append(col) + else: + for index, col in enumerate(selected_obj): + colg = obj._gotitem(col, ndim=1, subset=selected_obj.iloc[:, index]) + try: + new_res = colg.aggregate(arg) + except (TypeError, DataError): + pass + except ValueError as err: + # cannot aggregate + if "Must produce aggregated value" in str(err): + # raised directly in _aggregate_named + pass + elif "no results" in str(err): + # raised directly in _aggregate_multiple_funcs + pass + else: + raise + else: + results.append(new_res) + keys.append(col) # if we are empty if not len(results): raise ValueError("no results") try: - # if len(results) == 0: - # result = results[0] - # else: - result = concat(results, keys=keys, axis=1, sort=False) - if all([e == 1 for e in ndims]): - result = result.T.infer_objects() + return concat(results, keys=keys, axis=1, sort=False) except TypeError as err: # we are concatting non-NDFrame objects, @@ -297,12 +282,7 @@ def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion: raise ValueError( "cannot combine transform and aggregation operations" ) from err - else: - if result.columns.nlevels > 1: - new_order = [-1] + list(range(result.columns.nlevels - 1)) - result = result.reorder_levels(new_order, axis='columns') - result = result[selected_obj.columns] - return result + return result def agg_dict_like(self, _axis: int) -> FrameOrSeriesUnion: """ diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index 70b4c8890ea43..3ac9d98874f86 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -1101,7 +1101,6 @@ def test_consistency_for_boxed(self, box, int_frame_const_col): class TestDataFrameAggregate: def test_agg_transform(self, axis, float_frame): - float_frame = float_frame.head() other_axis = 1 if axis in {0, "index"} else 0 with np.errstate(all="ignore"): @@ -1125,16 +1124,11 @@ def test_agg_transform(self, axis, float_frame): expected.index = pd.MultiIndex.from_product( [float_frame.index, ["sqrt"]] ) - print("result") - print(result) - print('expected') - print(expected) tm.assert_frame_equal(result, expected) # multiple items in list # these are in the order as if we are applying both # functions per series and then concatting - print('marker') result = float_frame.apply([np.abs, np.sqrt], axis=axis) expected = zip_frames([f_abs, f_sqrt], axis=other_axis) if axis in {0, "index"}: @@ -1145,10 +1139,6 @@ def test_agg_transform(self, axis, float_frame): expected.index = pd.MultiIndex.from_product( [float_frame.index, ["absolute", "sqrt"]] ) - print() - print(result) - print() - print(expected) tm.assert_frame_equal(result, expected) def test_transform_and_agg_err(self, axis, float_frame): @@ -1156,13 +1146,13 @@ def test_transform_and_agg_err(self, axis, float_frame): msg = "cannot combine transform and aggregation operations" with pytest.raises(ValueError, match=msg): with np.errstate(all="ignore"): - print(float_frame.agg(["max", "sqrt"], axis=axis)) + float_frame.agg(["max", "sqrt"], axis=axis) df = DataFrame({"A": range(5), "B": 5}) def f(): with np.errstate(all="ignore"): - print(df.agg({"A": ["abs", "sum"], "B": ["mean", "max"]}, axis=axis)) + df.agg({"A": ["abs", "sum"], "B": ["mean", "max"]}, axis=axis) def test_demo(self): # demonstration tests
https://api.github.com/repos/pandas-dev/pandas/pulls/39879
2021-02-18T02:01:31Z
2021-02-18T02:18:14Z
2021-02-18T02:18:14Z
2021-02-18T02:18:21Z
Cleaning yearly, quarterly and monthly date offsets
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 4e6e5485b2ade..1ee1297ee7565 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1838,21 +1838,28 @@ cdef class YearOffset(SingleConstructorOffset): """ DateOffset that just needs a month. """ - _attributes = tuple(["n", "normalize", "month"]) - # _default_month: int # FIXME: python annotation here breaks things + _attributes = tuple(["n", "normalize", "month"]) + _default_month = 1 - cdef readonly: - int month + cdef: + readonly int month, _period_dtype_code + # public int _period_dtype_code def __init__(self, n=1, normalize=False, month=None): BaseOffset.__init__(self, n, normalize) - month = month if month is not None else self._default_month - self.month = month + if month is not None: + if isinstance(month, str): + self.month = MONTH_TO_CAL_NUM[month] + elif month >= 1 and month <= 12: + self.month = month + else: + raise ValueError("Month must go from 1 to 12.") + else: + self.month = self._default_month - if month < 1 or month > 12: - raise ValueError("Month must go from 1 to 12") + self._period_dtype_code = PeriodDtypeCode.A + self.month % 12 cpdef __setstate__(self, state): self.month = state.pop("month") @@ -1865,6 +1872,9 @@ cdef class YearOffset(SingleConstructorOffset): kwargs = {} if suffix: kwargs["month"] = MONTH_TO_CAL_NUM[suffix] + else: + if cls._default_month is not None: + kwargs["month"] = cls._default_month return cls(**kwargs) @property @@ -1903,30 +1913,44 @@ cdef class YearOffset(SingleConstructorOffset): return shifted -cdef class BYearEnd(YearOffset): +cdef class YearBegin(YearOffset): """ - DateOffset increments between the last business day of the year. + DateOffset increments between calendar year begin dates. Examples -------- - >>> from pandas.tseries.offset import BYearEnd + >>> from pandas.tseries.offsets import YearBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts - BYearEnd() - Timestamp('2019-12-31 05:01:15') - >>> ts + BYearEnd() + >>> ts + YearBegin() + Timestamp('2021-01-01 05:01:15') + >>> ts + YearBegin(normalize = True) + Timestamp('2021-01-01 00:00:00') + """ + + _outputName = "YearBegin" + _default_month = 1 + _prefix = "AS" + _day_opt = "start" + + +cdef class YearEnd(YearOffset): + """ + DateOffset increments between calendar year ends. + + Examples + -------- + >>> from pandas.tseries.offsets import YearEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + YearEnd() Timestamp('2020-12-31 05:01:15') - >>> ts + BYearEnd(3) - Timestamp('2022-12-30 05:01:15') - >>> ts + BYearEnd(-3) - Timestamp('2017-12-29 05:01:15') - >>> ts + BYearEnd(month=11) - Timestamp('2020-11-30 05:01:15') + >>> ts + YearEnd(normalize = True) + Timestamp('2020-12-31 00:00:00') """ - _outputName = "BusinessYearEnd" + _outputName = "YearEnd" _default_month = 12 - _prefix = "BA" - _day_opt = "business_end" + _prefix = "A" + _day_opt = "end" cdef class BYearBegin(YearOffset): @@ -1935,7 +1959,7 @@ cdef class BYearBegin(YearOffset): Examples -------- - >>> from pandas.tseries.offset import BYearBegin + >>> from pandas.tseries.offsets import BYearBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BYearBegin() Timestamp('2021-01-01 05:01:15') @@ -1947,63 +1971,86 @@ cdef class BYearBegin(YearOffset): Timestamp('2022-01-03 05:01:15') """ + # del(self._period_dtype_code) _outputName = "BusinessYearBegin" _default_month = 1 _prefix = "BAS" _day_opt = "business_start" -cdef class YearEnd(YearOffset): - """ - DateOffset increments between calendar year ends. +cdef class BYearEnd(YearOffset): """ + DateOffset increments between the last business days of offset years. + Here, the year is a period of 12 consecutive calendar months + (January - December by default). The "month" parameter allows custom setting + of the final month in a year (and correspondingly - the year start month). - _default_month = 12 - _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 - + Parameters + ---------- + n : int, default 1 + Number of years to offset. + normalize : bool, default False + If true, the time component of the resulting date-time is converted to + 00:00:00, i.e. midnight (the start, not the end of date-time). + month : int, default 12 + The calendar month number (12 for December) of the ending month + in a custom-defined year to be used as offset. -cdef class YearBegin(YearOffset): - """ - DateOffset increments between calendar year begin dates. + Examples + -------- + >>> from pandas.tseries.offsets import BYearEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts - BYearEnd() + Timestamp('2019-12-31 05:01:15') + >>> ts + BYearEnd() + Timestamp('2020-12-31 05:01:15') + >>> ts + BYearEnd(3) + Timestamp('2022-12-30 05:01:15') + >>> ts + BYearEnd(-3) + Timestamp('2017-12-29 05:01:15') + >>> ts + BYearEnd(month=11) + Timestamp('2020-11-30 05:01:15') """ - _default_month = 1 - _prefix = "AS" - _day_opt = "start" + # del(self._period_dtype_code) + _outputName = "BusinessYearEnd" + _default_month = 12 + _prefix = "BA" + _day_opt = "business_end" # ---------------------------------------------------------------------- # Quarter-Based Offset Classes cdef class QuarterOffset(SingleConstructorOffset): - _attributes = tuple(["n", "normalize", "startingMonth"]) + """ + The baseline quarterly DateOffset that just needs a month. + """ # 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 - # FIXME: python annotations here breaks things - # _default_starting_month: int - # _from_name_starting_month: int + _attributes = tuple(["n", "normalize", "startingMonth"]) + _default_month = 1 - cdef readonly: - int startingMonth + cdef: + readonly int startingMonth, _period_dtype_code + # public int _period_dtype_code def __init__(self, n=1, normalize=False, startingMonth=None): BaseOffset.__init__(self, n, normalize) - if startingMonth is None: - startingMonth = self._default_starting_month - self.startingMonth = startingMonth + if startingMonth is not None: + if isinstance(startingMonth, str): + self.startingMonth = MONTH_TO_CAL_NUM[startingMonth] + elif startingMonth >= 1 and startingMonth <= 12: + self.startingMonth = startingMonth + else: + raise ValueError("Month must go from 1 to 12.") + else: + self.startingMonth = self._default_month + + self._period_dtype_code = PeriodDtypeCode.Q_DEC + self.startingMonth % 12 cpdef __setstate__(self, state): self.startingMonth = state.pop("startingMonth") @@ -2060,32 +2107,53 @@ cdef class QuarterOffset(SingleConstructorOffset): return shifted -cdef class BQuarterEnd(QuarterOffset): +cdef class QuarterBegin(QuarterOffset): """ - DateOffset increments between the last business day of each Quarter. + DateOffset increments between Quarter start dates. + + startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... + startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... + startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + + Examples + -------- + >>> from pandas.tseries.offsets import QuarterBegin + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + QuarterBegin(2, startingMonth = 2) + Timestamp('2020-11-01 05:01:15') + """ + + _output_name = "QuarterBegin" + _default_month = 3 # should be 1 + _from_name_starting_month = 1 + _prefix = "QS" + _day_opt = "start" + + +cdef class QuarterEnd(QuarterOffset): + """ + DateOffset increments between Quarter end dates. startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... - startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, ... + startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... Examples -------- - >>> from pandas.tseries.offset import BQuarterEnd + >>> from pandas.tseries.offsets import QuarterEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BQuarterEnd() - Timestamp('2020-06-30 05:01:15') - >>> ts + BQuarterEnd(2) + >>> ts + QuarterEnd(2) Timestamp('2020-09-30 05:01:15') - >>> ts + BQuarterEnd(1, startingMonth=2) - Timestamp('2020-05-29 05:01:15') - >>> ts + BQuarterEnd(startingMonth=2) - Timestamp('2020-05-29 05:01:15') + >>> ts + QuarterEnd(1, normalize = True) + Timestamp('2020-06-30 00:00:00') + >>> ts + QuarterEnd(-2, startingMonth = 2) + Timestamp('2019-11-30 05:01:15') """ - _output_name = "BusinessQuarterEnd" - _default_starting_month = 3 - _from_name_starting_month = 12 - _prefix = "BQ" - _day_opt = "business_end" + + _output_name = "QuarterEnd" + _default_month = 3 + _prefix = "Q" + _day_opt = "end" cdef class BQuarterBegin(QuarterOffset): @@ -2098,64 +2166,56 @@ cdef class BQuarterBegin(QuarterOffset): Examples -------- - >>> from pandas.tseries.offset import BQuarterBegin + >>> from pandas.tseries.offsets import BQuarterBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BQuarterBegin() - Timestamp('2020-06-01 05:01:15') - >>> ts + BQuarterBegin(2) - Timestamp('2020-09-01 05:01:15') >>> ts + BQuarterBegin(startingMonth=2) Timestamp('2020-08-03 05:01:15') - >>> ts + BQuarterBegin(-1) - Timestamp('2020-03-02 05:01:15') """ + + # del(self._period_dtype_code) _output_name = "BusinessQuarterBegin" - _default_starting_month = 3 + _default_month = 3 # Should be 1 _from_name_starting_month = 1 _prefix = "BQS" _day_opt = "business_start" -cdef class QuarterEnd(QuarterOffset): +cdef class BQuarterEnd(QuarterOffset): """ - DateOffset increments between Quarter end dates. + DateOffset increments between the last business day of each Quarter. startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... - startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... - """ - _default_starting_month = 3 - _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 - + startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, ... -cdef class QuarterBegin(QuarterOffset): + Examples + -------- + >>> from pandas.tseries.offsets import BQuarterEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + BQuarterEnd() + Timestamp('2020-06-30 05:01:15') + >>> ts + BQuarterEnd(2) + Timestamp('2020-09-30 05:01:15') + >>> ts + BQuarterEnd(1, startingMonth = 2) + Timestamp('2020-05-29 05:01:15') + >>> ts + BQuarterEnd(startingMonth=2) + Timestamp('2020-05-29 05:01:15') """ - DateOffset increments between Quarter start dates. - startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... - startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... - startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... - """ - _default_starting_month = 3 - _from_name_starting_month = 1 - _prefix = "QS" - _day_opt = "start" + # del(self._period_dtype_code) + _output_name = "BusinessQuarterEnd" + _default_month = 3 + _from_name_starting_month = 12 + _prefix = "BQ" + _day_opt = "business_end" # ---------------------------------------------------------------------- # Month-Based Offset Classes cdef class MonthOffset(SingleConstructorOffset): + # _period_dtype_code = PeriodDtypeCode.M + def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False @@ -2185,21 +2245,43 @@ cdef class MonthOffset(SingleConstructorOffset): BaseOffset.__setstate__(self, state) +cdef class MonthBegin(MonthOffset): + """ + DateOffset of one month at beginning. + """ + + _prefix = "MS" + _day_opt = "start" + + cdef class MonthEnd(MonthOffset): """ DateOffset of one month end. """ + _period_dtype_code = PeriodDtypeCode.M _prefix = "M" _day_opt = "end" -cdef class MonthBegin(MonthOffset): +cdef class BusinessMonthBegin(MonthOffset): """ - DateOffset of one month at beginning. + DateOffset of one month at the first business day. + + Examples + -------- + >>> from pandas.tseries.offset import BMonthBegin + >>> ts=pd.Timestamp('2020-05-24 05:01:15') + >>> ts + BMonthBegin() + Timestamp('2020-06-01 05:01:15') + >>> ts + BMonthBegin(2) + Timestamp('2020-07-01 05:01:15') + >>> ts + BMonthBegin(-3) + Timestamp('2020-03-02 05:01:15') """ - _prefix = "MS" - _day_opt = "start" + + _prefix = "BMS" + _day_opt = "business_start" cdef class BusinessMonthEnd(MonthOffset): @@ -2217,29 +2299,12 @@ cdef class BusinessMonthEnd(MonthOffset): >>> ts + BMonthEnd(-2) Timestamp('2020-03-31 05:01:15') """ + + _period_dtype_code = PeriodDtypeCode.M _prefix = "BM" _day_opt = "business_end" -cdef class BusinessMonthBegin(MonthOffset): - """ - DateOffset of one month at the first business day. - - Examples - -------- - >>> from pandas.tseries.offset import BMonthBegin - >>> ts=pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BMonthBegin() - Timestamp('2020-06-01 05:01:15') - >>> ts + BMonthBegin(2) - Timestamp('2020-07-01 05:01:15') - >>> ts + BMonthBegin(-3) - Timestamp('2020-03-02 05:01:15') - """ - _prefix = "BMS" - _day_opt = "business_start" - - # --------------------------------------------------------------------- # Semi-Month Based Offsets @@ -2261,7 +2326,7 @@ cdef class SemiMonthOffset(SingleConstructorOffset): if not self._min_day_of_month <= self.day_of_month <= 27: raise ValueError( "day_of_month must be " - f"{self._min_day_of_month}<=day_of_month<=27, " + f"{self._min_day_of_month} <= day_of_month <= 27, " f"got {self.day_of_month}" )
- Ability to use `YearBegin` and `QuarterBegin` DateOffset classes as Period `freq`, along with offset aliases. - Ability to use three-letter month short names as `month` / `startingMonth` arguments of year- / quarter-based offset classes (as already used in their `_from_name` class method). - Expanded docstrings with, e.g., additional examples. - Partial refactorization, as a step toward combining `QuarterOffset` and `YearOffset` `__init__` (mentioned as TO DO in the code). - [ ] xref #38859 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39878
2021-02-18T00:18:33Z
2021-06-16T13:27:04Z
null
2021-06-16T13:27:04Z
TST: collect indexing tests by method
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 657faa0f9b505..6763113036de8 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -445,6 +445,15 @@ def test_setitem_intervals(self): tm.assert_series_equal(df["C"], df["C"]) tm.assert_series_equal(df["C"], df["E"], check_names=False) + def test_setitem_categorical(self): + # GH#35369 + df = DataFrame({"h": Series(list("mn")).astype("category")}) + df.h = df.h.cat.reorder_categories(["n", "m"]) + expected = DataFrame( + {"h": Categorical(["m", "n"]).reorder_categories(["n", "m"])} + ) + tm.assert_frame_equal(df, expected) + class TestSetitemTZAwareValues: @pytest.fixture diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py index aea2cf42751db..34dc5d604e90d 100644 --- a/pandas/tests/indexing/interval/test_interval_new.py +++ b/pandas/tests/indexing/interval/test_interval_new.py @@ -198,7 +198,7 @@ def test_non_unique_moar(self, indexer_sl): result = indexer_sl(ser)[[Interval(1, 3)]] tm.assert_series_equal(expected, result) - def test_missing_key_error_message( + def test_loc_getitem_missing_key_error_message( self, frame_or_series, series_with_interval_index ): # GH#27365 diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py index 954ef63bc2802..f07bf3464b74c 100644 --- a/pandas/tests/indexing/multiindex/test_getitem.py +++ b/pandas/tests/indexing/multiindex/test_getitem.py @@ -62,26 +62,22 @@ def test_series_getitem_duplicates_multiindex(level0_value): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("indexer", [lambda s: s[2000, 3], lambda s: s.loc[2000, 3]]) -def test_series_getitem(multiindex_year_month_day_dataframe_random_data, indexer): +def test_series_getitem(multiindex_year_month_day_dataframe_random_data, indexer_sl): s = multiindex_year_month_day_dataframe_random_data["A"] expected = s.reindex(s.index[42:65]) expected.index = expected.index.droplevel(0).droplevel(0) - result = indexer(s) + result = indexer_sl(s)[2000, 3] tm.assert_series_equal(result, expected) -@pytest.mark.parametrize( - "indexer", [lambda s: s[2000, 3, 10], lambda s: s.loc[2000, 3, 10]] -) def test_series_getitem_returns_scalar( - multiindex_year_month_day_dataframe_random_data, indexer + multiindex_year_month_day_dataframe_random_data, indexer_sl ): s = multiindex_year_month_day_dataframe_random_data["A"] expected = s.iloc[49] - result = indexer(s) + result = indexer_sl(s)[2000, 3, 10] assert result == expected diff --git a/pandas/tests/indexing/multiindex/test_iloc.py b/pandas/tests/indexing/multiindex/test_iloc.py index 1a7f93596773a..db91d5ad88252 100644 --- a/pandas/tests/indexing/multiindex/test_iloc.py +++ b/pandas/tests/indexing/multiindex/test_iloc.py @@ -17,14 +17,10 @@ def simple_multiindex_dataframe(): random data by default. """ - def _simple_multiindex_dataframe(data=None): - if data is None: - data = np.random.randn(3, 3) - return DataFrame( - data, columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]] - ) - - return _simple_multiindex_dataframe + data = np.random.randn(3, 3) + return DataFrame( + data, columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]] + ) @pytest.mark.parametrize( @@ -45,23 +41,23 @@ def _simple_multiindex_dataframe(data=None): ], ) def test_iloc_returns_series(indexer, expected, simple_multiindex_dataframe): - arr = np.random.randn(3, 3) - df = simple_multiindex_dataframe(arr) + df = simple_multiindex_dataframe + arr = df.values result = indexer(df) expected = expected(arr) tm.assert_series_equal(result, expected) def test_iloc_returns_dataframe(simple_multiindex_dataframe): - df = simple_multiindex_dataframe() + df = simple_multiindex_dataframe result = df.iloc[[0, 1]] expected = df.xs(4, drop_level=False) tm.assert_frame_equal(result, expected) def test_iloc_returns_scalar(simple_multiindex_dataframe): - arr = np.random.randn(3, 3) - df = simple_multiindex_dataframe(arr) + df = simple_multiindex_dataframe + arr = df.values result = df.iloc[2, 2] expected = arr[2, 2] assert result == expected diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py index cca31c1e81f84..a38b5f6cc449a 100644 --- a/pandas/tests/indexing/multiindex/test_indexing_slow.py +++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py @@ -40,49 +40,49 @@ b = df.drop_duplicates(subset=cols[:-1]) -@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") -@pytest.mark.parametrize("lexsort_depth", list(range(5))) -@pytest.mark.parametrize("key", keys) -@pytest.mark.parametrize("frame", [a, b]) -def test_multiindex_get_loc(lexsort_depth, key, frame): - # GH7724, GH2646 +def validate(mi, df, key): + # check indexing into a multi-index before & past the lexsort depth - with warnings.catch_warnings(record=True): + mask = np.ones(len(df)).astype("bool") - # test indexing into a multi-index before & past the lexsort depth + # test for all partials of this key + for i, k in enumerate(key): + mask &= df.iloc[:, i] == k - def validate(mi, df, key): - mask = np.ones(len(df)).astype("bool") + if not mask.any(): + assert key[: i + 1] not in mi.index + continue - # test for all partials of this key - for i, k in enumerate(key): - mask &= df.iloc[:, i] == k + assert key[: i + 1] in mi.index + right = df[mask].copy() - if not mask.any(): - assert key[: i + 1] not in mi.index - continue + if i + 1 != len(key): # partial key + return_value = right.drop(cols[: i + 1], axis=1, inplace=True) + assert return_value is None + return_value = right.set_index(cols[i + 1 : -1], inplace=True) + assert return_value is None + tm.assert_frame_equal(mi.loc[key[: i + 1]], right) - assert key[: i + 1] in mi.index - right = df[mask].copy() + else: # full key + return_value = right.set_index(cols[:-1], inplace=True) + assert return_value is None + if len(right) == 1: # single hit + right = Series( + right["jolia"].values, name=right.index[0], index=["jolia"] + ) + tm.assert_series_equal(mi.loc[key[: i + 1]], right) + else: # multi hit + tm.assert_frame_equal(mi.loc[key[: i + 1]], right) - if i + 1 != len(key): # partial key - return_value = right.drop(cols[: i + 1], axis=1, inplace=True) - assert return_value is None - return_value = right.set_index(cols[i + 1 : -1], inplace=True) - assert return_value is None - tm.assert_frame_equal(mi.loc[key[: i + 1]], right) - else: # full key - return_value = right.set_index(cols[:-1], inplace=True) - assert return_value is None - if len(right) == 1: # single hit - right = Series( - right["jolia"].values, name=right.index[0], index=["jolia"] - ) - tm.assert_series_equal(mi.loc[key[: i + 1]], right) - else: # multi hit - tm.assert_frame_equal(mi.loc[key[: i + 1]], right) +@pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") +@pytest.mark.parametrize("lexsort_depth", list(range(5))) +@pytest.mark.parametrize("key", keys) +@pytest.mark.parametrize("frame", [a, b]) +def test_multiindex_get_loc(lexsort_depth, key, frame): + # GH7724, GH2646 + with warnings.catch_warnings(record=True): if lexsort_depth == 0: df = frame.copy() else: diff --git a/pandas/tests/indexing/multiindex/test_insert.py b/pandas/tests/indexing/multiindex/test_insert.py deleted file mode 100644 index b62f0be5a4f10..0000000000000 --- a/pandas/tests/indexing/multiindex/test_insert.py +++ /dev/null @@ -1,35 +0,0 @@ -import numpy as np - -from pandas import ( - DataFrame, - MultiIndex, - Series, -) -import pandas._testing as tm - - -class TestMultiIndexInsertion: - def test_setitem_mixed_depth(self): - arrays = [ - ["a", "top", "top", "routine1", "routine1", "routine2"], - ["", "OD", "OD", "result1", "result2", "result1"], - ["", "wx", "wy", "", "", ""], - ] - - tuples = sorted(zip(*arrays)) - index = MultiIndex.from_tuples(tuples) - df = DataFrame(np.random.randn(4, 6), columns=index) - - result = df.copy() - expected = df.copy() - result["b"] = [1, 2, 3, 4] - expected["b", "", ""] = [1, 2, 3, 4] - tm.assert_frame_equal(result, expected) - - def test_dataframe_insert_column_all_na(self): - # GH #1534 - mix = MultiIndex.from_tuples([("1a", "2a"), ("1a", "2b"), ("1a", "2c")]) - df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix) - s = Series({(1, 1): 1, (1, 2): 2}) - df["new"] = s - assert df["new"].isna().all() diff --git a/pandas/tests/indexing/multiindex/test_ix.py b/pandas/tests/indexing/multiindex/test_ix.py deleted file mode 100644 index b8d30337dbe16..0000000000000 --- a/pandas/tests/indexing/multiindex/test_ix.py +++ /dev/null @@ -1,67 +0,0 @@ -import numpy as np -import pytest - -from pandas.errors import PerformanceWarning - -from pandas import ( - DataFrame, - MultiIndex, -) -import pandas._testing as tm - - -class TestMultiIndex: - def test_frame_setitem_loc(self, multiindex_dataframe_random_data): - frame = multiindex_dataframe_random_data - frame.loc[("bar", "two"), "B"] = 5 - assert frame.loc[("bar", "two"), "B"] == 5 - - # with integer labels - df = frame.copy() - df.columns = list(range(3)) - df.loc[("bar", "two"), 1] = 7 - assert df.loc[("bar", "two"), 1] == 7 - - def test_loc_general(self): - - # GH 2817 - data = { - "amount": {0: 700, 1: 600, 2: 222, 3: 333, 4: 444}, - "col": {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0}, - "year": {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}, - } - df = DataFrame(data).set_index(keys=["col", "year"]) - key = 4.0, 2012 - - # emits a PerformanceWarning, ok - with tm.assert_produces_warning(PerformanceWarning): - tm.assert_frame_equal(df.loc[key], df.iloc[2:]) - - # this is ok - return_value = df.sort_index(inplace=True) - assert return_value is None - res = df.loc[key] - - # col has float dtype, result should be Float64Index - index = MultiIndex.from_arrays([[4.0] * 3, [2012] * 3], names=["col", "year"]) - expected = DataFrame({"amount": [222, 333, 444]}, index=index) - tm.assert_frame_equal(res, expected) - - def test_loc_multiindex_missing_label_raises(self): - # GH 21593 - df = DataFrame( - np.random.randn(3, 3), - columns=[[2, 2, 4], [6, 8, 10]], - index=[[4, 4, 8], [8, 10, 12]], - ) - - with pytest.raises(KeyError, match=r"^2$"): - df.loc[2] - - def test_series_loc_getitem_fancy( - self, multiindex_year_month_day_dataframe_random_data - ): - s = multiindex_year_month_day_dataframe_random_data["A"] - expected = s.reindex(s.index[49:51]) - result = s.loc[[(2000, 3, 10), (2000, 3, 13)]] - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 3e912eedb0232..07503b5b34176 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas.errors import PerformanceWarning + import pandas as pd from pandas import ( DataFrame, @@ -29,6 +31,61 @@ def frame_random_data_integer_multi_index(): class TestMultiIndexLoc: + def test_loc_setitem_frame_with_multiindex(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + frame.loc[("bar", "two"), "B"] = 5 + assert frame.loc[("bar", "two"), "B"] == 5 + + # with integer labels + df = frame.copy() + df.columns = list(range(3)) + df.loc[("bar", "two"), 1] = 7 + assert df.loc[("bar", "two"), 1] == 7 + + def test_loc_getitem_general(self): + + # GH#2817 + data = { + "amount": {0: 700, 1: 600, 2: 222, 3: 333, 4: 444}, + "col": {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0}, + "year": {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}, + } + df = DataFrame(data).set_index(keys=["col", "year"]) + key = 4.0, 2012 + + # emits a PerformanceWarning, ok + with tm.assert_produces_warning(PerformanceWarning): + tm.assert_frame_equal(df.loc[key], df.iloc[2:]) + + # this is ok + return_value = df.sort_index(inplace=True) + assert return_value is None + res = df.loc[key] + + # col has float dtype, result should be Float64Index + index = MultiIndex.from_arrays([[4.0] * 3, [2012] * 3], names=["col", "year"]) + expected = DataFrame({"amount": [222, 333, 444]}, index=index) + tm.assert_frame_equal(res, expected) + + def test_loc_getitem_multiindex_missing_label_raises(self): + # GH#21593 + df = DataFrame( + np.random.randn(3, 3), + columns=[[2, 2, 4], [6, 8, 10]], + index=[[4, 4, 8], [8, 10, 12]], + ) + + with pytest.raises(KeyError, match=r"^2$"): + df.loc[2] + + def test_loc_getitem_list_of_tuples_with_multiindex( + self, multiindex_year_month_day_dataframe_random_data + ): + ser = multiindex_year_month_day_dataframe_random_data["A"] + expected = ser.reindex(ser.index[49:51]) + result = ser.loc[[(2000, 3, 10), (2000, 3, 13)]] + tm.assert_series_equal(result, expected) + def test_loc_getitem_series(self): # GH14730 # passing a series as a key with a MultiIndex diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index a360a53ca7672..9e85f9f65a3bc 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -15,114 +15,109 @@ import pandas.core.common as com +def assert_equal(a, b): + assert a == b + + class TestMultiIndexSetItem: + def check(self, target, indexers, value, compare_fn=assert_equal, expected=None): + target.loc[indexers] = value + result = target.loc[indexers] + if expected is None: + expected = value + compare_fn(result, expected) + def test_setitem_multiindex(self): - for index_fn in ("loc",): - - def assert_equal(a, b): - assert a == b - - def check(target, indexers, value, compare_fn, expected=None): - fn = getattr(target, index_fn) - fn.__setitem__(indexers, value) - result = fn.__getitem__(indexers) - if expected is None: - expected = value - compare_fn(result, expected) - - # GH7190 - index = MultiIndex.from_product( - [np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"] - ) - t, n = 0, 2 - df = DataFrame( - np.nan, - columns=["A", "w", "l", "a", "x", "X", "d", "profit"], - index=index, - ) - check(target=df, indexers=((t, n), "X"), value=0, compare_fn=assert_equal) - - df = DataFrame( - -999, columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index - ) - check(target=df, indexers=((t, n), "X"), value=1, compare_fn=assert_equal) - - df = DataFrame( - columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index - ) - check(target=df, indexers=((t, n), "X"), value=2, compare_fn=assert_equal) - - # gh-7218: assigning with 0-dim arrays - df = DataFrame( - -999, columns=["A", "w", "l", "a", "x", "X", "d", "profit"], index=index - ) - check( - target=df, - indexers=((t, n), "X"), - value=np.array(3), - compare_fn=assert_equal, - expected=3, - ) - - # GH5206 - df = DataFrame( - np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float - ) - df["F"] = 99 - row_selection = df["A"] % 2 == 0 - col_selection = ["B", "C"] - df.loc[row_selection, col_selection] = df["F"] - output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"]) - tm.assert_frame_equal(df.loc[row_selection, col_selection], output) - check( - target=df, - indexers=(row_selection, col_selection), - value=df["F"], - compare_fn=tm.assert_frame_equal, - expected=output, - ) - - # GH11372 - idx = MultiIndex.from_product( - [["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")] - ) - cols = MultiIndex.from_product( - [["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")] - ) - - df = DataFrame(np.random.random((12, 4)), index=idx, columns=cols) - - subidx = MultiIndex.from_tuples( - [("A", Timestamp("2015-01-01")), ("A", Timestamp("2015-02-01"))] - ) - subcols = MultiIndex.from_tuples( - [("foo", Timestamp("2016-01-01")), ("foo", Timestamp("2016-02-01"))] - ) - - vals = DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols) - check( - target=df, - indexers=(subidx, subcols), - value=vals, - compare_fn=tm.assert_frame_equal, - ) - # set all columns - vals = DataFrame(np.random.random((2, 4)), index=subidx, columns=cols) - check( - target=df, - indexers=(subidx, slice(None, None, None)), - value=vals, - compare_fn=tm.assert_frame_equal, - ) - # identity - copy = df.copy() - check( - target=df, - indexers=(df.index, df.columns), - value=df, - compare_fn=tm.assert_frame_equal, - expected=copy, - ) + # GH#7190 + cols = ["A", "w", "l", "a", "x", "X", "d", "profit"] + index = MultiIndex.from_product( + [np.arange(0, 100), np.arange(0, 80)], names=["time", "firm"] + ) + t, n = 0, 2 + + df = DataFrame( + np.nan, + columns=cols, + index=index, + ) + self.check(target=df, indexers=((t, n), "X"), value=0) + + df = DataFrame(-999, columns=cols, index=index) + self.check(target=df, indexers=((t, n), "X"), value=1) + + df = DataFrame(columns=cols, index=index) + self.check(target=df, indexers=((t, n), "X"), value=2) + + # gh-7218: assigning with 0-dim arrays + df = DataFrame(-999, columns=cols, index=index) + self.check( + target=df, + indexers=((t, n), "X"), + value=np.array(3), + expected=3, + ) + + def test_setitem_multiindex2(self): + # GH#5206 + df = DataFrame( + np.arange(25).reshape(5, 5), columns="A,B,C,D,E".split(","), dtype=float + ) + df["F"] = 99 + row_selection = df["A"] % 2 == 0 + col_selection = ["B", "C"] + df.loc[row_selection, col_selection] = df["F"] + output = DataFrame(99.0, index=[0, 2, 4], columns=["B", "C"]) + tm.assert_frame_equal(df.loc[row_selection, col_selection], output) + self.check( + target=df, + indexers=(row_selection, col_selection), + value=df["F"], + compare_fn=tm.assert_frame_equal, + expected=output, + ) + + def test_setitem_multiindex3(self): + # GH#11372 + idx = MultiIndex.from_product( + [["A", "B", "C"], date_range("2015-01-01", "2015-04-01", freq="MS")] + ) + cols = MultiIndex.from_product( + [["foo", "bar"], date_range("2016-01-01", "2016-02-01", freq="MS")] + ) + + df = DataFrame(np.random.random((12, 4)), index=idx, columns=cols) + + subidx = MultiIndex.from_tuples( + [("A", Timestamp("2015-01-01")), ("A", Timestamp("2015-02-01"))] + ) + subcols = MultiIndex.from_tuples( + [("foo", Timestamp("2016-01-01")), ("foo", Timestamp("2016-02-01"))] + ) + + vals = DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols) + self.check( + target=df, + indexers=(subidx, subcols), + value=vals, + compare_fn=tm.assert_frame_equal, + ) + # set all columns + vals = DataFrame(np.random.random((2, 4)), index=subidx, columns=cols) + self.check( + target=df, + indexers=(subidx, slice(None, None, None)), + value=vals, + compare_fn=tm.assert_frame_equal, + ) + # identity + copy = df.copy() + self.check( + target=df, + indexers=(df.index, df.columns), + value=df, + compare_fn=tm.assert_frame_equal, + expected=copy, + ) def test_multiindex_setitem(self): @@ -148,6 +143,8 @@ def test_multiindex_setitem(self): with pytest.raises(TypeError, match=msg): df.loc["bar"] *= 2 + def test_multiindex_setitem2(self): + # from SO # https://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation df_orig = DataFrame.from_dict( @@ -239,17 +236,6 @@ def test_groupby_example(self): grp = df.groupby(level=index_cols[:4]) df["new_col"] = np.nan - f_index = np.arange(5) - - def f(name, df2): - return Series(np.arange(df2.shape[0]), name=df2.index.values[0]).reindex( - f_index - ) - - # FIXME: dont leave commented-out - # TODO(wesm): unused? - # new_df = pd.concat([f(name, df2) for name, df2 in grp], axis=1).T - # we are actually operating on a copy here # but in this case, that's ok for name, df2 in grp: @@ -334,8 +320,10 @@ def test_frame_setitem_multi_column(self): cp["a"] = cp["b"].values tm.assert_frame_equal(cp["a"], cp["b"]) + def test_frame_setitem_multi_column2(self): + # --------------------------------------- - # #1803 + # GH#1803 columns = MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]) df = DataFrame(index=[1, 3, 5], columns=columns) @@ -356,6 +344,7 @@ def test_frame_setitem_multi_column(self): assert sliced_a2.name == ("A", "2") assert sliced_b1.name == ("B", "1") + # TODO: no setitem here? def test_getitem_setitem_tuple_plus_columns( self, multiindex_year_month_day_dataframe_random_data ): @@ -367,29 +356,23 @@ def test_getitem_setitem_tuple_plus_columns( expected = df.loc[2000, 1, 6][["A", "B", "C"]] tm.assert_series_equal(result, expected) - def test_getitem_setitem_slice_integers(self): + def test_loc_getitem_setitem_slice_integers(self, frame_or_series): index = MultiIndex( levels=[[0, 1, 2], [0, 2]], codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]] ) - frame = DataFrame( + obj = DataFrame( np.random.randn(len(index), 4), index=index, columns=["a", "b", "c", "d"] ) - res = frame.loc[1:2] - exp = frame.reindex(frame.index[2:]) - tm.assert_frame_equal(res, exp) + if frame_or_series is not DataFrame: + obj = obj["a"] - frame.loc[1:2] = 7 - assert (frame.loc[1:2] == 7).values.all() + res = obj.loc[1:2] + exp = obj.reindex(obj.index[2:]) + tm.assert_equal(res, exp) - series = Series(np.random.randn(len(index)), index=index) - - res = series.loc[1:2] - exp = series.reindex(series.index[2:]) - tm.assert_series_equal(res, exp) - - series.loc[1:2] = 7 - assert (series.loc[1:2] == 7).values.all() + obj.loc[1:2] = 7 + assert (obj.loc[1:2] == 7).values.all() def test_setitem_change_dtype(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data @@ -419,9 +402,9 @@ def test_nonunique_assignment_1750(self): ) df = df.set_index(["A", "B"]) - ix = MultiIndex.from_tuples([(1, 1)]) + mi = MultiIndex.from_tuples([(1, 1)]) - df.loc[ix, "C"] = "_" + df.loc[mi, "C"] = "_" assert (df.xs((1, 1))["C"] == "_").all() @@ -447,6 +430,33 @@ def test_setitem_nonmonotonic(self): tm.assert_frame_equal(df, expected) +class TestSetitemWithExpansionMultiIndex: + def test_setitem_new_column_mixed_depth(self): + arrays = [ + ["a", "top", "top", "routine1", "routine1", "routine2"], + ["", "OD", "OD", "result1", "result2", "result1"], + ["", "wx", "wy", "", "", ""], + ] + + tuples = sorted(zip(*arrays)) + index = MultiIndex.from_tuples(tuples) + df = DataFrame(np.random.randn(4, 6), columns=index) + + result = df.copy() + expected = df.copy() + result["b"] = [1, 2, 3, 4] + expected["b", "", ""] = [1, 2, 3, 4] + tm.assert_frame_equal(result, expected) + + def test_setitem_new_column_all_na(self): + # GH#1534 + mix = MultiIndex.from_tuples([("1a", "2a"), ("1a", "2b"), ("1a", "2c")]) + df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mix) + s = Series({(1, 1): 1, (1, 2): 2}) + df["new"] = s + assert df["new"].isna().all() + + def test_frame_setitem_view_direct(multiindex_dataframe_random_data): # this works because we are modifying the underlying array # really a no-no diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index efd99df9a5e4f..07c9c181584dc 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -1064,52 +1064,3 @@ def test_extension_array_cross_section_converts(): result = df.iloc[0] tm.assert_series_equal(result, expected) - - -def test_setitem_with_bool_mask_and_values_matching_n_trues_in_length(): - # GH 30567 - ser = Series([None] * 10) - mask = [False] * 3 + [True] * 5 + [False] * 2 - ser[mask] = range(5) - result = ser - expected = Series([None] * 3 + list(range(5)) + [None] * 2).astype("object") - tm.assert_series_equal(result, expected) - - -def test_missing_labels_inside_loc_matched_in_error_message(): - # GH34272 - s = Series({"a": 1, "b": 2, "c": 3}) - error_message_regex = "missing_0.*missing_1.*missing_2" - with pytest.raises(KeyError, match=error_message_regex): - s.loc[["a", "b", "missing_0", "c", "missing_1", "missing_2"]] - - -def test_many_missing_labels_inside_loc_error_message_limited(): - # GH34272 - n = 10000 - missing_labels = [f"missing_{label}" for label in range(n)] - s = Series({"a": 1, "b": 2, "c": 3}) - # regex checks labels between 4 and 9995 are replaced with ellipses - error_message_regex = "missing_4.*\\.\\.\\..*missing_9995" - with pytest.raises(KeyError, match=error_message_regex): - s.loc[["a", "c"] + missing_labels] - - -def test_long_text_missing_labels_inside_loc_error_message_limited(): - # GH34272 - s = Series({"a": 1, "b": 2, "c": 3}) - missing_labels = [f"long_missing_label_text_{i}" * 5 for i in range(3)] - # regex checks for very long labels there are new lines between each - error_message_regex = "long_missing_label_text_0.*\\\\n.*long_missing_label_text_1" - with pytest.raises(KeyError, match=error_message_regex): - s.loc[["a", "c"] + missing_labels] - - -def test_setitem_categorical(): - # https://github.com/pandas-dev/pandas/issues/35369 - df = DataFrame({"h": Series(list("mn")).astype("category")}) - df.h = df.h.cat.reorder_categories(["n", "m"]) - expected = DataFrame( - {"h": pd.Categorical(["m", "n"]).reorder_categories(["n", "m"])} - ) - tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 55a979859a12a..c98666b38b8b8 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1808,25 +1808,51 @@ def test_loc_getitem_list_of_labels_categoricalindex_with_na(self, box): with pytest.raises(KeyError, match=msg): ser2.to_frame().loc[box(ci2)] + def test_loc_getitem_many_missing_labels_inside_error_message_limited(self): + # GH#34272 + n = 10000 + missing_labels = [f"missing_{label}" for label in range(n)] + ser = Series({"a": 1, "b": 2, "c": 3}) + # regex checks labels between 4 and 9995 are replaced with ellipses + error_message_regex = "missing_4.*\\.\\.\\..*missing_9995" + with pytest.raises(KeyError, match=error_message_regex): + ser.loc[["a", "c"] + missing_labels] + + def test_loc_getitem_missing_labels_inside_matched_in_error_message(self): + # GH#34272 + ser = Series({"a": 1, "b": 2, "c": 3}) + error_message_regex = "missing_0.*missing_1.*missing_2" + with pytest.raises(KeyError, match=error_message_regex): + ser.loc[["a", "b", "missing_0", "c", "missing_1", "missing_2"]] + + def test_loc_getitem_long_text_missing_labels_inside_error_message_limited(self): + # GH#34272 + ser = Series({"a": 1, "b": 2, "c": 3}) + missing_labels = [f"long_missing_label_text_{i}" * 5 for i in range(3)] + # regex checks for very long labels there are new lines between each + error_message_regex = ( + "long_missing_label_text_0.*\\\\n.*long_missing_label_text_1" + ) + with pytest.raises(KeyError, match=error_message_regex): + ser.loc[["a", "c"] + missing_labels] + + def test_loc_getitem_series_label_list_missing_values(self): + # gh-11428 + key = np.array( + ["2001-01-04", "2001-01-02", "2001-01-04", "2001-01-14"], dtype="datetime64" + ) + ser = Series([2, 5, 8, 11], date_range("2001-01-01", freq="D", periods=4)) + with pytest.raises(KeyError, match="with any missing labels"): + ser.loc[key] -def test_series_loc_getitem_label_list_missing_values(): - # gh-11428 - key = np.array( - ["2001-01-04", "2001-01-02", "2001-01-04", "2001-01-14"], dtype="datetime64" - ) - s = Series([2, 5, 8, 11], date_range("2001-01-01", freq="D", periods=4)) - with pytest.raises(KeyError, match="with any missing labels"): - s.loc[key] - - -def test_series_getitem_label_list_missing_integer_values(): - # GH: 25927 - s = Series( - index=np.array([9730701000001104, 10049011000001109]), - data=np.array([999000011000001104, 999000011000001104]), - ) - with pytest.raises(KeyError, match="with any missing labels"): - s.loc[np.array([9730701000001104, 10047311000001102])] + def test_loc_getitem_series_label_list_missing_integer_values(self): + # GH: 25927 + ser = Series( + index=np.array([9730701000001104, 10049011000001109]), + data=np.array([999000011000001104, 999000011000001104]), + ) + with pytest.raises(KeyError, match="with any missing labels"): + ser.loc[np.array([9730701000001104, 10047311000001102])] @pytest.mark.parametrize( diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 35f6647b631aa..3a3dffb0ce9e8 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -186,6 +186,15 @@ def test_setitem_boolean_nullable_int_types(self, any_nullable_numeric_dtype): ser.loc[ser > 6] = loc_ser.loc[loc_ser > 1] tm.assert_series_equal(ser, expected) + def test_setitem_with_bool_mask_and_values_matching_n_trues_in_length(self): + # GH#30567 + ser = Series([None] * 10) + mask = [False] * 3 + [True] * 5 + [False] * 2 + ser[mask] = range(5) + result = ser + expected = Series([None] * 3 + list(range(5)) + [None] * 2).astype("object") + tm.assert_series_equal(result, expected) + class TestSetitemViewCopySemantics: def test_setitem_invalidates_datetime_index_freq(self):
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39876
2021-02-17T23:51:40Z
2021-02-21T18:14:57Z
2021-02-21T18:14:57Z
2021-02-21T19:52:00Z
Improvements to yearly, quarterly and monthly offsets
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 2d4704ad3bda6..6312f4b6a3a1d 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1838,9 +1838,10 @@ cdef class YearOffset(SingleConstructorOffset): """ DateOffset that just needs a month. """ + _attributes = tuple(["n", "normalize", "month"]) - - # _default_month: int # FIXME: python annotation here breaks things + _default_month = 1 + cdef int _period_dtype_code cdef readonly: int month @@ -1852,7 +1853,9 @@ cdef class YearOffset(SingleConstructorOffset): self.month = month if month < 1 or month > 12: - raise ValueError("Month must go from 1 to 12") + raise ValueError("Month must go from 1 to 12.") + + self._period_dtype_code = PeriodDtypeCode.A + self.month % 12 cpdef __setstate__(self, state): self.month = state.pop("month") @@ -1865,8 +1868,11 @@ cdef class YearOffset(SingleConstructorOffset): kwargs = {} if suffix: kwargs["month"] = MONTH_TO_CAL_NUM[suffix] + else: + if cls._default_month is not None: + kwargs["month"] = cls._default_month return cls(**kwargs) - + @property def rule_code(self) -> str: month = MONTH_ALIASES[self.month] @@ -1902,40 +1908,58 @@ cdef class YearOffset(SingleConstructorOffset): ) return shifted - -cdef class BYearEnd(YearOffset): + +cdef class YearBegin(YearOffset): + """ + DateOffset increments between calendar year begin dates. + + Examples + -------- + >>> from pandas.tseries.offsets import YearBegin + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + YearBegin() + Timestamp('2021-01-01 05:01:15') + >>> ts + YearBegin(normalize = True) + Timestamp('2021-01-01 00:00:00') + >>> ts + YearBegin()._from_name('APR') + Timestamp('2021-04-01 05:01:15') """ - DateOffset increments between the last business day of the year. + _outputName = "YearBegin" + _default_month = 1 + _prefix = "AS" + _day_opt = "start" + + +cdef class YearEnd(YearOffset): + """ + DateOffset increments between calendar year ends. + Examples -------- - >>> from pandas.tseries.offset import BYearEnd + >>> from pandas.tseries.offsets import YearEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts - BYearEnd() - Timestamp('2019-12-31 05:01:15') - >>> ts + BYearEnd() + >>> ts + YearEnd() Timestamp('2020-12-31 05:01:15') - >>> ts + BYearEnd(3) - Timestamp('2022-12-30 05:01:15') - >>> ts + BYearEnd(-3) - Timestamp('2017-12-29 05:01:15') - >>> ts + BYearEnd(month=11) - Timestamp('2020-11-30 05:01:15') + >>> ts + YearEnd(normalize = True) + Timestamp('2020-12-31 00:00:00') + >>> ts + YearEnd()._from_name('AUG') + Timestamp('2020-08-31 05:01:15') """ - _outputName = "BusinessYearEnd" + _outputName = "YearEnd" _default_month = 12 - _prefix = "BA" - _day_opt = "business_end" - - + _prefix = "A" + _day_opt = "end" + + cdef class BYearBegin(YearOffset): """ DateOffset increments between the first business day of the year. Examples -------- - >>> from pandas.tseries.offset import BYearBegin + >>> from pandas.tseries.offsets import BYearBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BYearBegin() Timestamp('2021-01-01 05:01:15') @@ -1951,59 +1975,77 @@ cdef class BYearBegin(YearOffset): _default_month = 1 _prefix = "BAS" _day_opt = "business_start" + - -cdef class YearEnd(YearOffset): - """ - DateOffset increments between calendar year ends. +cdef class BYearEnd(YearOffset): """ + DateOffset increments between the last business days of offset years. + Here, the year is a period of 12 consecutive calendar months + (January - December by default). The "month" parameter allows custom setting + of the final month in a year (and correspondingly - the year start month). + + Parameters + ---------- + n : int, default 1 + Number of years to offset. + normalize: bool, default False + If true, the time component of the resulting date-time is converted to + 00:00:00, i.e. midnight (the start, not the end of date-time). + month: int, default 12 + The calendar month number (12 for December) of the ending month + in a custom-defined year to be used as offset. - _default_month = 12 - _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): - """ - DateOffset increments between calendar year begin dates. + Examples + -------- + >>> from pandas.tseries.offsets import BYearEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts - BYearEnd() + Timestamp('2019-12-31 05:01:15') + >>> ts + BYearEnd() + Timestamp('2020-12-31 05:01:15') + >>> ts + BYearEnd(3) + Timestamp('2022-12-30 05:01:15') + >>> ts + BYearEnd(-3) + Timestamp('2017-12-29 05:01:15') + >>> ts + BYearEnd(month=11) + Timestamp('2020-11-30 05:01:15') """ - _default_month = 1 - _prefix = "AS" - _day_opt = "start" - + _outputName = "BusinessYearEnd" + _default_month = 12 + _prefix = "BA" + _day_opt = "business_end" + # ---------------------------------------------------------------------- # Quarter-Based Offset Classes cdef class QuarterOffset(SingleConstructorOffset): - _attributes = tuple(["n", "normalize", "startingMonth"]) + """ + The baseline quarterly DateOffset that just needs a month. + """ # 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 - - # FIXME: python annotations here breaks things - # _default_starting_month: int - # _from_name_starting_month: int + + _attributes = tuple(["n", "normalize", "startingMonth"]) + _default_month = 1 + cdef int _period_dtype_code cdef readonly: int startingMonth def __init__(self, n=1, normalize=False, startingMonth=None): BaseOffset.__init__(self, n, normalize) - - if startingMonth is None: - startingMonth = self._default_starting_month - self.startingMonth = startingMonth + + if startingMonth is not None: + if startingMonth < 1 or startingMonth > 12: + raise ValueError("Month must go from 1 to 12.") + self.startingMonth = startingMonth + else: + self.startingMonth = self._default_month + + self._period_dtype_code = PeriodDtypeCode.Q_DEC + self.startingMonth % 12 cpdef __setstate__(self, state): self.startingMonth = state.pop("startingMonth") @@ -2016,8 +2058,8 @@ cdef class QuarterOffset(SingleConstructorOffset): if suffix: kwargs["startingMonth"] = MONTH_TO_CAL_NUM[suffix] else: - if cls._from_name_starting_month is not None: - kwargs["startingMonth"] = cls._from_name_starting_month + if cls._default_month is not None: + kwargs["startingMonth"] = cls._default_month return cls(**kwargs) @property @@ -2059,34 +2101,62 @@ cdef class QuarterOffset(SingleConstructorOffset): ) return shifted + +cdef class QuarterBegin(QuarterOffset): + """ + DateOffset increments between Quarter start dates. -cdef class BQuarterEnd(QuarterOffset): + startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... + startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... + startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + + Examples + -------- + >>> from pandas.tseries.offsets import QuarterBegin + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + QuarterBegin()._from_name('MAR') + Timestamp('2020-06-01 05:01:15') + >>> ts + QuarterBegin() + Timestamp('2020-07-01 05:01:15') + >>> ts + QuarterBegin(2) + Timestamp('2020-10-01 05:01:15') + >>> ts + QuarterBegin(2, startingMonth = 2) + Timestamp('2020-11-01 05:01:15') """ - DateOffset increments between the last business day of each Quarter. + + _output_name = "QuarterBegin" + _default_month = 1 + _prefix = "QS" + _day_opt = "start" + + +cdef class QuarterEnd(QuarterOffset): + """ + DateOffset increments between Quarter end dates. startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... - startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, ... - + startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... + Examples -------- - >>> from pandas.tseries.offset import BQuarterEnd + >>> from pandas.tseries.offsets import QuarterEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BQuarterEnd() - Timestamp('2020-06-30 05:01:15') - >>> ts + BQuarterEnd(2) + >>> ts + QuarterEnd(2) Timestamp('2020-09-30 05:01:15') - >>> ts + BQuarterEnd(1, startingMonth=2) - Timestamp('2020-05-29 05:01:15') - >>> ts + BQuarterEnd(startingMonth=2) - Timestamp('2020-05-29 05:01:15') + >>> ts + QuarterEnd()._from_name('JUN') + Timestamp('2020-06-30 05:01:15') + >>> ts + QuarterEnd(1, normalize = True) + Timestamp('2020-06-30 00:00:00') + >>> ts + QuarterEnd(-2, startingMonth = 2) + Timestamp('2019-11-30 05:01:15') """ - _output_name = "BusinessQuarterEnd" - _default_starting_month = 3 - _from_name_starting_month = 12 - _prefix = "BQ" - _day_opt = "business_end" - + + _output_name = "QuarterEnd" + _default_month = 3 + _prefix = "Q" + _day_opt = "end" + cdef class BQuarterBegin(QuarterOffset): """ @@ -2098,64 +2168,58 @@ cdef class BQuarterBegin(QuarterOffset): Examples -------- - >>> from pandas.tseries.offset import BQuarterBegin + >>> from pandas.tseries.offsets import BQuarterBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BQuarterBegin() - Timestamp('2020-06-01 05:01:15') + Timestamp('2020-07-01 05:01:15') >>> ts + BQuarterBegin(2) - Timestamp('2020-09-01 05:01:15') + Timestamp('2020-10-01 05:01:15') >>> ts + BQuarterBegin(startingMonth=2) Timestamp('2020-08-03 05:01:15') >>> ts + BQuarterBegin(-1) - Timestamp('2020-03-02 05:01:15') + Timestamp('2020-04-01 05:01:15') """ + _output_name = "BusinessQuarterBegin" - _default_starting_month = 3 - _from_name_starting_month = 1 + _default_month = 1 _prefix = "BQS" _day_opt = "business_start" - -cdef class QuarterEnd(QuarterOffset): + +cdef class BQuarterEnd(QuarterOffset): """ - DateOffset increments between Quarter end dates. + DateOffset increments between the last business day of each Quarter. startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... - startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... - """ - _default_starting_month = 3 - _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): - """ - DateOffset increments between Quarter start dates. + startingMonth = 3 corresponds to dates like 3/30/2007, 6/29/2007, ... - startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... - startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... - startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + Examples + -------- + >>> from pandas.tseries.offsets import BQuarterEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + BQuarterEnd() + Timestamp('2020-06-30 05:01:15') + >>> ts + BQuarterEnd(2) + Timestamp('2020-09-30 05:01:15') + >>> ts + BQuarterEnd(1, startingMonth=2) + Timestamp('2020-05-29 05:01:15') + >>> ts + BQuarterEnd(startingMonth=2) + Timestamp('2020-05-29 05:01:15') """ - _default_starting_month = 3 - _from_name_starting_month = 1 - _prefix = "QS" - _day_opt = "start" + + _output_name = "BusinessQuarterEnd" + _default_month = 3 + _prefix = "BQ" + _day_opt = "business_end" # ---------------------------------------------------------------------- # Month-Based Offset Classes cdef class MonthOffset(SingleConstructorOffset): + _period_dtype_code = PeriodDtypeCode.M + def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False @@ -2184,22 +2248,43 @@ cdef class MonthOffset(SingleConstructorOffset): BaseOffset.__setstate__(self, state) + +cdef class MonthBegin(MonthOffset): + """ + DateOffset of one month at beginning. + """ + _prefix = "MS" + _day_opt = "start" + + cdef class MonthEnd(MonthOffset): """ DateOffset of one month end. """ - _period_dtype_code = PeriodDtypeCode.M + _prefix = "M" _day_opt = "end" -cdef class MonthBegin(MonthOffset): +cdef class BusinessMonthBegin(MonthOffset): """ - DateOffset of one month at beginning. + DateOffset of one month at the first business day. + + Examples + -------- + >>> from pandas.tseries.offset import BMonthBegin + >>> ts=pd.Timestamp('2020-05-24 05:01:15') + >>> ts + BMonthBegin() + Timestamp('2020-06-01 05:01:15') + >>> ts + BMonthBegin(2) + Timestamp('2020-07-01 05:01:15') + >>> ts + BMonthBegin(-3) + Timestamp('2020-03-02 05:01:15') """ - _prefix = "MS" - _day_opt = "start" + + _prefix = "BMS" + _day_opt = "business_start" cdef class BusinessMonthEnd(MonthOffset): @@ -2217,29 +2302,11 @@ cdef class BusinessMonthEnd(MonthOffset): >>> ts + BMonthEnd(-2) Timestamp('2020-03-31 05:01:15') """ + _prefix = "BM" _day_opt = "business_end" -cdef class BusinessMonthBegin(MonthOffset): - """ - DateOffset of one month at the first business day. - - Examples - -------- - >>> from pandas.tseries.offset import BMonthBegin - >>> ts=pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BMonthBegin() - Timestamp('2020-06-01 05:01:15') - >>> ts + BMonthBegin(2) - Timestamp('2020-07-01 05:01:15') - >>> ts + BMonthBegin(-3) - Timestamp('2020-03-02 05:01:15') - """ - _prefix = "BMS" - _day_opt = "business_start" - - # --------------------------------------------------------------------- # Semi-Month Based Offsets @@ -2261,7 +2328,7 @@ cdef class SemiMonthOffset(SingleConstructorOffset): if not self._min_day_of_month <= self.day_of_month <= 27: raise ValueError( "day_of_month must be " - f"{self._min_day_of_month}<=day_of_month<=27, " + f"{self._min_day_of_month} <= day_of_month <= 27, " f"got {self.day_of_month}" )
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39875
2021-02-17T23:24:01Z
2021-02-17T23:38:43Z
null
2021-02-17T23:38:43Z
TST/REF: collect Index tests by method
diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 0354e362dc4ac..f8daf23fb08a3 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -243,11 +243,6 @@ def test_copy_name2(self, index): with pytest.raises(TypeError, match=msg): index.copy(name=[["mario"]]) - def test_copy_dtype_deprecated(self, index): - # GH35853 - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - index.copy(dtype=object) - def test_ensure_copied_data(self, index): # Check the "copy" argument of each Index.__new__ is honoured # GH12309 @@ -504,10 +499,9 @@ def test_format_empty(self): assert empty_idx.format() == [] assert empty_idx.format(name=True) == [""] - def test_hasnans_isnans(self, index): + def test_hasnans_isnans(self, index_flat): # GH 11343, added tests for hasnans / isnans - if isinstance(index, MultiIndex): - return + index = index_flat # cases in indices doesn't include NaN idx = index.copy(deep=True) diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/methods/test_insert.py similarity index 100% rename from pandas/tests/indexes/datetimes/test_insert.py rename to pandas/tests/indexes/datetimes/methods/test_insert.py diff --git a/pandas/tests/indexes/datetimes/methods/test_to_frame.py b/pandas/tests/indexes/datetimes/methods/test_to_frame.py new file mode 100644 index 0000000000000..ec6254f52f4d5 --- /dev/null +++ b/pandas/tests/indexes/datetimes/methods/test_to_frame.py @@ -0,0 +1,14 @@ +from pandas import ( + DataFrame, + date_range, +) +import pandas._testing as tm + + +class TestToFrame: + def test_to_frame_datetime_tz(self): + # GH#25809 + idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") + result = idx.to_frame() + expected = DataFrame(idx, index=idx) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_asof.py b/pandas/tests/indexes/datetimes/test_asof.py new file mode 100644 index 0000000000000..c794aefc6a48b --- /dev/null +++ b/pandas/tests/indexes/datetimes/test_asof.py @@ -0,0 +1,14 @@ +from pandas import ( + Index, + Timestamp, + date_range, +) + + +class TestAsOf: + def test_asof_partial(self): + index = date_range("2010-01-01", periods=2, freq="m") + expected = Timestamp("2010-02-28") + result = index.asof("2010-02") + assert result == expected + assert not isinstance(result, Index) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index a93c68e0c6d9a..6eef43fe496dd 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -240,10 +240,3 @@ def test_asarray_tz_aware(self): result = np.asarray(idx, dtype=object) tm.assert_numpy_array_equal(result, expected) - - def test_to_frame_datetime_tz(self): - # GH 25809 - idx = date_range(start="2019-01-01", end="2019-01-30", freq="D", tz="UTC") - result = idx.to_frame() - expected = DataFrame(idx, index=idx) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/period/methods/test_insert.py b/pandas/tests/indexes/period/methods/test_insert.py new file mode 100644 index 0000000000000..32bbe09d92567 --- /dev/null +++ b/pandas/tests/indexes/period/methods/test_insert.py @@ -0,0 +1,18 @@ +import numpy as np +import pytest + +from pandas import ( + NaT, + PeriodIndex, + period_range, +) +import pandas._testing as tm + + +class TestInsert: + @pytest.mark.parametrize("na", [np.nan, NaT, None]) + def test_insert(self, na): + # GH#18295 (test missing) + expected = PeriodIndex(["2017Q1", NaT, "2017Q2", "2017Q3", "2017Q4"], freq="Q") + result = period_range("2017Q1", periods=4, freq="Q").insert(1, na) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index c5018bd0e66d2..54e61b35eb70f 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -512,6 +512,27 @@ def test_map_with_string_constructor(self): tm.assert_index_equal(res, expected) +class TestShallowCopy: + def test_shallow_copy_empty(self): + # GH#13067 + idx = PeriodIndex([], freq="M") + result = idx._view() + expected = idx + + tm.assert_index_equal(result, expected) + + def test_shallow_copy_disallow_i8(self): + # GH#24391 + pi = period_range("2018-01-01", periods=3, freq="2D") + with pytest.raises(AssertionError, match="ndarray"): + pi._shallow_copy(pi.asi8) + + def test_shallow_copy_requires_disallow_period_index(self): + pi = period_range("2018-01-01", periods=3, freq="2D") + with pytest.raises(AssertionError, match="PeriodIndex"): + pi._shallow_copy(pi) + + class TestSeriesPeriod: def setup_method(self, method): self.series = Series(period_range("2000-01-01", periods=10, freq="D")) diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index af5ce1945a671..aabc837e25b4b 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -79,25 +79,6 @@ def test_make_time_series(self): series = Series(1, index=index) assert isinstance(series, Series) - def test_shallow_copy_empty(self): - # GH13067 - idx = PeriodIndex([], freq="M") - result = idx._view() - expected = idx - - tm.assert_index_equal(result, expected) - - def test_shallow_copy_disallow_i8(self): - # GH-24391 - pi = period_range("2018-01-01", periods=3, freq="2D") - with pytest.raises(AssertionError, match="ndarray"): - pi._shallow_copy(pi.asi8) - - def test_shallow_copy_requires_disallow_period_index(self): - pi = period_range("2018-01-01", periods=3, freq="2D") - with pytest.raises(AssertionError, match="PeriodIndex"): - pi._shallow_copy(pi) - def test_view_asi8(self): idx = PeriodIndex([], freq="M") @@ -411,7 +392,7 @@ def test_convert_array_of_periods(self): result = Index(periods) assert isinstance(result, PeriodIndex) - def test_append_concat(self): + def test_append_concat(self): # TODO: pd.concat test # #1815 d1 = date_range("12/31/1990", "12/31/1999", freq="A-DEC") d2 = date_range("12/31/2000", "12/31/2009", freq="A-DEC") @@ -442,13 +423,6 @@ def test_map(self): exp = Index([x.ordinal for x in index]) tm.assert_index_equal(result, exp) - def test_insert(self): - # GH 18295 (test missing) - expected = PeriodIndex(["2017Q1", NaT, "2017Q2", "2017Q3", "2017Q4"], freq="Q") - for na in (np.nan, NaT, None): - result = period_range("2017Q1", periods=4, freq="Q").insert(1, na) - tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( "msg, key", [ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 127f0432efa01..0b43b6b1ead9c 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -5,7 +5,6 @@ ) from io import StringIO import math -import operator import re import numpy as np @@ -573,25 +572,19 @@ def test_asof_numeric_vs_bool_raises(self): with pytest.raises(TypeError, match=msg): right.asof(left) - def test_asof_datetime_partial(self): - index = date_range("2010-01-01", periods=2, freq="m") - expected = Timestamp("2010-02-28") - result = index.asof("2010-02") - assert result == expected - assert not isinstance(result, Index) - - def test_nanosecond_index_access(self): - s = Series([Timestamp("20130101")]).values.view("i8")[0] + # TODO: this tests Series.asof + def test_asof_nanosecond_index_access(self): + s = Timestamp("20130101").value r = DatetimeIndex([s + 50 + i for i in range(100)]) - x = Series(np.random.randn(100), index=r) + ser = Series(np.random.randn(100), index=r) - first_value = x.asof(x.index[0]) + first_value = ser.asof(ser.index[0]) # this does not yet work, as parsing strings is done via dateutil # assert first_value == x['2013-01-01 00:00:00.000000050+0000'] expected_ts = np_datetime64_compat("2013-01-01 00:00:00.000000050+0000", "ns") - assert first_value == x[Timestamp(expected_ts)] + assert first_value == ser[Timestamp(expected_ts)] @pytest.mark.parametrize("index", ["string"], indirect=True) def test_booleanindex(self, index): @@ -635,110 +628,6 @@ def test_empty_fancy_raises(self, index): with pytest.raises(IndexError, match=msg): index[empty_farr] - @pytest.mark.parametrize("index", ["string"], indirect=True) - def test_intersection(self, index, sort): - first = index[:20] - second = index[:10] - intersect = first.intersection(second, sort=sort) - if sort is None: - tm.assert_index_equal(intersect, second.sort_values()) - assert tm.equalContents(intersect, second) - - # Corner cases - inter = first.intersection(first, sort=sort) - assert inter is first - - @pytest.mark.parametrize( - "index2,keeps_name", - [ - (Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name - (Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names - (Index([3, 4, 5, 6, 7]), False), - ], - ) - def test_intersection_name_preservation(self, index2, keeps_name, sort): - index1 = Index([1, 2, 3, 4, 5], name="index") - expected = Index([3, 4, 5]) - result = index1.intersection(index2, sort) - - if keeps_name: - expected.name = "index" - - assert result.name == expected.name - tm.assert_index_equal(result, expected) - - @pytest.mark.parametrize("index", ["string"], indirect=True) - @pytest.mark.parametrize( - "first_name,second_name,expected_name", - [("A", "A", "A"), ("A", "B", None), (None, "B", None)], - ) - def test_intersection_name_preservation2( - self, index, first_name, second_name, expected_name, sort - ): - first = index[5:20] - second = index[:10] - first.name = first_name - second.name = second_name - intersect = first.intersection(second, sort=sort) - assert intersect.name == expected_name - - def test_chained_union(self, sort): - # Chained unions handles names correctly - i1 = Index([1, 2], name="i1") - i2 = Index([5, 6], name="i2") - i3 = Index([3, 4], name="i3") - union = i1.union(i2.union(i3, sort=sort), sort=sort) - expected = i1.union(i2, sort=sort).union(i3, sort=sort) - tm.assert_index_equal(union, expected) - - j1 = Index([1, 2], name="j1") - j2 = Index([], name="j2") - j3 = Index([], name="j3") - union = j1.union(j2.union(j3, sort=sort), sort=sort) - expected = j1.union(j2, sort=sort).union(j3, sort=sort) - tm.assert_index_equal(union, expected) - - @pytest.mark.parametrize("index", ["string"], indirect=True) - def test_union(self, index, sort): - first = index[5:20] - second = index[:10] - everything = index[:20] - - union = first.union(second, sort=sort) - if sort is None: - tm.assert_index_equal(union, everything.sort_values()) - assert tm.equalContents(union, everything) - - @pytest.mark.parametrize("klass", [np.array, Series, list]) - @pytest.mark.parametrize("index", ["string"], indirect=True) - def test_union_from_iterables(self, index, klass, sort): - # GH 10149 - first = index[5:20] - second = index[:10] - everything = index[:20] - - case = klass(second.values) - result = first.union(case, sort=sort) - if sort is None: - tm.assert_index_equal(result, everything.sort_values()) - assert tm.equalContents(result, everything) - - @pytest.mark.parametrize("index", ["string"], indirect=True) - def test_union_identity(self, index, sort): - first = index[5:20] - - union = first.union(first, sort=sort) - # i.e. identity is not preserved when sort is True - assert (union is first) is (not sort) - - # This should no longer be the same object, since [] is not consistent, - # both objects will be recast to dtype('O') - union = first.union([], sort=sort) - assert (union is first) is (not sort) - - union = Index([]).union(first, sort=sort) - assert (union is first) is (not sort) - def test_union_dt_as_obj(self, sort): # TODO: Replace with fixturesult index = self.create_index() @@ -865,123 +754,6 @@ def test_append_empty_preserve_name(self, name, expected): result = left.append(right) assert result.name == expected - @pytest.mark.parametrize("index", ["string"], indirect=True) - @pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")]) - def test_difference_name_preservation(self, index, second_name, expected, sort): - first = index[5:20] - second = index[:10] - answer = index[10:20] - - first.name = "name" - second.name = second_name - result = first.difference(second, sort=sort) - - assert tm.equalContents(result, answer) - - if expected is None: - assert result.name is None - else: - assert result.name == expected - - def test_difference_empty_arg(self, index, sort): - first = index[5:20] - first.name = "name" - result = first.difference([], sort) - - tm.assert_index_equal(result, first) - - @pytest.mark.parametrize("index", ["string"], indirect=True) - def test_difference_identity(self, index, sort): - first = index[5:20] - first.name = "name" - result = first.difference(first, sort) - - assert len(result) == 0 - assert result.name == first.name - - @pytest.mark.parametrize("index", ["string"], indirect=True) - def test_difference_sort(self, index, sort): - first = index[5:20] - second = index[:10] - - result = first.difference(second, sort) - expected = index[10:20] - - if sort is None: - expected = expected.sort_values() - - tm.assert_index_equal(result, expected) - - @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) - def test_difference_incomparable(self, opname): - a = Index([3, Timestamp("2000"), 1]) - b = Index([2, Timestamp("1999"), 1]) - op = operator.methodcaller(opname, b) - - with tm.assert_produces_warning(RuntimeWarning): - # sort=None, the default - result = op(a) - expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")]) - if opname == "difference": - expected = expected[:2] - tm.assert_index_equal(result, expected) - - # sort=False - op = operator.methodcaller(opname, b, sort=False) - result = op(a) - tm.assert_index_equal(result, expected) - - @pytest.mark.xfail(reason="Not implemented") - @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) - def test_difference_incomparable_true(self, opname): - # TODO decide on True behaviour - # # sort=True, raises - a = Index([3, Timestamp("2000"), 1]) - b = Index([2, Timestamp("1999"), 1]) - op = operator.methodcaller(opname, b, sort=True) - - with pytest.raises(TypeError, match="Cannot compare"): - op(a) - - def test_symmetric_difference_mi(self, sort): - index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])) - index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)]) - result = index1.symmetric_difference(index2, sort=sort) - expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)]) - if sort is None: - expected = expected.sort_values() - tm.assert_index_equal(result, expected) - assert tm.equalContents(result, expected) - - @pytest.mark.parametrize( - "index2,expected", - [ - (Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])), - (Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])), - ], - ) - def test_symmetric_difference_missing(self, index2, expected, sort): - # GH 13514 change: {nan} - {nan} == {} - # (GH 6444, sorting of nans, is no longer an issue) - index1 = Index([1, np.nan, 2, 3]) - - result = index1.symmetric_difference(index2, sort=sort) - if sort is None: - expected = expected.sort_values() - tm.assert_index_equal(result, expected) - - def test_symmetric_difference_non_index(self, sort): - index1 = Index([1, 2, 3, 4], name="index1") - index2 = np.array([2, 3, 4, 5]) - expected = Index([1, 5]) - result = index1.symmetric_difference(index2, sort=sort) - assert tm.equalContents(result, expected) - assert result.name == "index1" - - result = index1.symmetric_difference(index2, result_name="new_name", sort=sort) - assert tm.equalContents(result, expected) - assert result.name == "new_name" - def test_is_mixed_deprecated(self): # GH#32922 index = self.create_index() @@ -1035,7 +807,7 @@ def test_is_all_dates(self, index, expected): assert index.is_all_dates is expected def test_summary(self, index): - self._check_method_works(Index._summary, index) + index._summary() def test_summary_bug(self): # GH3869` @@ -1098,9 +870,6 @@ def test_logical_compat(self, op): index = self.create_index() assert getattr(index, op)() == getattr(index.values, op)() - def _check_method_works(self, method, index): - method(index) - @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) def test_drop_by_str_label(self, index): n = len(index) @@ -1776,11 +1545,6 @@ def test_dropna_invalid_how_raises(self): with pytest.raises(ValueError, match=msg): Index([1, 2, 3]).dropna(how="xxx") - def test_get_combined_index(self): - result = _get_combined_index([]) - expected = Index([]) - tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( "index", [ @@ -1813,16 +1577,6 @@ def test_str_to_bytes_raises(self): with pytest.raises(TypeError, match=msg): bytes(index) - def test_intersect_str_dates(self): - dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] - - index1 = Index(dt_dates, dtype=object) - index2 = Index(["aa"], dtype=object) - result = index2.intersection(index1) - - expected = Index([], dtype=object) - tm.assert_index_equal(result, expected) - @pytest.mark.filterwarnings("ignore:elementwise comparison failed:FutureWarning") def test_index_with_tuple_bool(self): # GH34123 @@ -1868,6 +1622,11 @@ def test_ensure_index_mixed_closed_intervals(self): expected = Index(intervals, dtype=object) tm.assert_index_equal(result, expected) + def test_get_combined_index(self): + result = _get_combined_index([]) + expected = Index([]) + tm.assert_index_equal(result, expected) + @pytest.mark.parametrize( "opname", diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 11514b9f04b59..b2bab2e720146 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -2,21 +2,25 @@ The tests in this package are to ensure the proper resultant dtypes of set operations. """ +from datetime import datetime +import operator + import numpy as np import pytest from pandas.core.dtypes.common import is_dtype_equal -import pandas as pd from pandas import ( CategoricalIndex, DatetimeIndex, Float64Index, + Index, Int64Index, MultiIndex, RangeIndex, Series, TimedeltaIndex, + Timestamp, UInt64Index, ) import pandas._testing as tm @@ -113,8 +117,8 @@ def test_compatible_inconsistent_pairs(idx_fact1, idx_fact2): def test_union_dtypes(left, right, expected, names): left = pandas_dtype(left) right = pandas_dtype(right) - a = pd.Index([], dtype=left, name=names[0]) - b = pd.Index([], dtype=right, name=names[1]) + a = Index([], dtype=left, name=names[0]) + b = Index([], dtype=right, name=names[1]) result = a.union(b) assert result.dtype == expected assert result.name == names[2] @@ -141,10 +145,10 @@ def test_dunder_inplace_setops_deprecated(index): @pytest.mark.parametrize("values", [[1, 2, 2, 3], [3, 3]]) def test_intersection_duplicates(values): # GH#31326 - a = pd.Index(values) - b = pd.Index([3, 3]) + a = Index(values) + b = Index([3, 3]) result = a.intersection(b) - expected = pd.Index([3]) + expected = Index([3]) tm.assert_index_equal(result, expected) @@ -495,3 +499,238 @@ def check_intersection_commutative(left, right): check_intersection_commutative(idx, idx_non_unique) assert idx.intersection(idx_non_unique).is_unique + + +class TestSetOpsUnsorted: + # These may eventually belong in a dtype-specific test_setops, or + # parametrized over a more general fixture + def test_intersect_str_dates(self): + dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] + + index1 = Index(dt_dates, dtype=object) + index2 = Index(["aa"], dtype=object) + result = index2.intersection(index1) + + expected = Index([], dtype=object) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_intersection(self, index, sort): + first = index[:20] + second = index[:10] + intersect = first.intersection(second, sort=sort) + if sort is None: + tm.assert_index_equal(intersect, second.sort_values()) + assert tm.equalContents(intersect, second) + + # Corner cases + inter = first.intersection(first, sort=sort) + assert inter is first + + @pytest.mark.parametrize( + "index2,keeps_name", + [ + (Index([3, 4, 5, 6, 7], name="index"), True), # preserve same name + (Index([3, 4, 5, 6, 7], name="other"), False), # drop diff names + (Index([3, 4, 5, 6, 7]), False), + ], + ) + def test_intersection_name_preservation(self, index2, keeps_name, sort): + index1 = Index([1, 2, 3, 4, 5], name="index") + expected = Index([3, 4, 5]) + result = index1.intersection(index2, sort) + + if keeps_name: + expected.name = "index" + + assert result.name == expected.name + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + @pytest.mark.parametrize( + "first_name,second_name,expected_name", + [("A", "A", "A"), ("A", "B", None), (None, "B", None)], + ) + def test_intersection_name_preservation2( + self, index, first_name, second_name, expected_name, sort + ): + first = index[5:20] + second = index[:10] + first.name = first_name + second.name = second_name + intersect = first.intersection(second, sort=sort) + assert intersect.name == expected_name + + def test_chained_union(self, sort): + # Chained unions handles names correctly + i1 = Index([1, 2], name="i1") + i2 = Index([5, 6], name="i2") + i3 = Index([3, 4], name="i3") + union = i1.union(i2.union(i3, sort=sort), sort=sort) + expected = i1.union(i2, sort=sort).union(i3, sort=sort) + tm.assert_index_equal(union, expected) + + j1 = Index([1, 2], name="j1") + j2 = Index([], name="j2") + j3 = Index([], name="j3") + union = j1.union(j2.union(j3, sort=sort), sort=sort) + expected = j1.union(j2, sort=sort).union(j3, sort=sort) + tm.assert_index_equal(union, expected) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union(self, index, sort): + first = index[5:20] + second = index[:10] + everything = index[:20] + + union = first.union(second, sort=sort) + if sort is None: + tm.assert_index_equal(union, everything.sort_values()) + assert tm.equalContents(union, everything) + + @pytest.mark.parametrize("klass", [np.array, Series, list]) + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union_from_iterables(self, index, klass, sort): + # GH#10149 + first = index[5:20] + second = index[:10] + everything = index[:20] + + case = klass(second.values) + result = first.union(case, sort=sort) + if sort is None: + tm.assert_index_equal(result, everything.sort_values()) + assert tm.equalContents(result, everything) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_union_identity(self, index, sort): + first = index[5:20] + + union = first.union(first, sort=sort) + # i.e. identity is not preserved when sort is True + assert (union is first) is (not sort) + + # This should no longer be the same object, since [] is not consistent, + # both objects will be recast to dtype('O') + union = first.union([], sort=sort) + assert (union is first) is (not sort) + + union = Index([]).union(first, sort=sort) + assert (union is first) is (not sort) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + @pytest.mark.parametrize("second_name,expected", [(None, None), ("name", "name")]) + def test_difference_name_preservation(self, index, second_name, expected, sort): + first = index[5:20] + second = index[:10] + answer = index[10:20] + + first.name = "name" + second.name = second_name + result = first.difference(second, sort=sort) + + assert tm.equalContents(result, answer) + + if expected is None: + assert result.name is None + else: + assert result.name == expected + + def test_difference_empty_arg(self, index, sort): + first = index[5:20] + first.name = "name" + result = first.difference([], sort) + + tm.assert_index_equal(result, first) + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_identity(self, index, sort): + first = index[5:20] + first.name = "name" + result = first.difference(first, sort) + + assert len(result) == 0 + assert result.name == first.name + + @pytest.mark.parametrize("index", ["string"], indirect=True) + def test_difference_sort(self, index, sort): + first = index[5:20] + second = index[:10] + + result = first.difference(second, sort) + expected = index[10:20] + + if sort is None: + expected = expected.sort_values() + + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) + def test_difference_incomparable(self, opname): + a = Index([3, Timestamp("2000"), 1]) + b = Index([2, Timestamp("1999"), 1]) + op = operator.methodcaller(opname, b) + + with tm.assert_produces_warning(RuntimeWarning): + # sort=None, the default + result = op(a) + expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")]) + if opname == "difference": + expected = expected[:2] + tm.assert_index_equal(result, expected) + + # sort=False + op = operator.methodcaller(opname, b, sort=False) + result = op(a) + tm.assert_index_equal(result, expected) + + @pytest.mark.xfail(reason="Not implemented") + @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) + def test_difference_incomparable_true(self, opname): + # TODO: decide on True behaviour + # # sort=True, raises + a = Index([3, Timestamp("2000"), 1]) + b = Index([2, Timestamp("1999"), 1]) + op = operator.methodcaller(opname, b, sort=True) + + with pytest.raises(TypeError, match="Cannot compare"): + op(a) + + def test_symmetric_difference_mi(self, sort): + index1 = MultiIndex.from_tuples(zip(["foo", "bar", "baz"], [1, 2, 3])) + index2 = MultiIndex.from_tuples([("foo", 1), ("bar", 3)]) + result = index1.symmetric_difference(index2, sort=sort) + expected = MultiIndex.from_tuples([("bar", 2), ("baz", 3), ("bar", 3)]) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + assert tm.equalContents(result, expected) + + @pytest.mark.parametrize( + "index2,expected", + [ + (Index([0, 1, np.nan]), Index([2.0, 3.0, 0.0])), + (Index([0, 1]), Index([np.nan, 2.0, 3.0, 0.0])), + ], + ) + def test_symmetric_difference_missing(self, index2, expected, sort): + # GH#13514 change: {nan} - {nan} == {} + # (GH#6444, sorting of nans, is no longer an issue) + index1 = Index([1, np.nan, 2, 3]) + + result = index1.symmetric_difference(index2, sort=sort) + if sort is None: + expected = expected.sort_values() + tm.assert_index_equal(result, expected) + + def test_symmetric_difference_non_index(self, sort): + index1 = Index([1, 2, 3, 4], name="index1") + index2 = np.array([2, 3, 4, 5]) + expected = Index([1, 5]) + result = index1.symmetric_difference(index2, sort=sort) + assert tm.equalContents(result, expected) + assert result.name == "index1" + + result = index1.symmetric_difference(index2, result_name="new_name", sort=sort) + assert tm.equalContents(result, expected) + assert result.name == "new_name" diff --git a/pandas/tests/indexes/timedeltas/test_insert.py b/pandas/tests/indexes/timedeltas/methods/test_insert.py similarity index 100% rename from pandas/tests/indexes/timedeltas/test_insert.py rename to pandas/tests/indexes/timedeltas/methods/test_insert.py
https://api.github.com/repos/pandas-dev/pandas/pulls/39873
2021-02-17T22:24:01Z
2021-02-21T17:20:16Z
2021-02-21T17:20:16Z
2021-02-21T17:23:18Z
Backport PR #39858 on branch 1.2.x (DOC: Update matplotlib canonical)
diff --git a/doc/source/conf.py b/doc/source/conf.py index 8ab1c8c2f3428..e3cb6cf7fadd0 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -409,7 +409,7 @@ if pattern is None: intersphinx_mapping = { "dateutil": ("https://dateutil.readthedocs.io/en/latest/", None), - "matplotlib": ("https://matplotlib.org/", None), + "matplotlib": ("https://matplotlib.org/stable/", None), "numpy": ("https://numpy.org/doc/stable/", None), "pandas-gbq": ("https://pandas-gbq.readthedocs.io/en/latest/", None), "py": ("https://pylib.readthedocs.io/en/latest/", None),
Backport PR #39858: DOC: Update matplotlib canonical
https://api.github.com/repos/pandas-dev/pandas/pulls/39871
2021-02-17T20:11:52Z
2021-02-18T09:38:40Z
2021-02-18T09:38:40Z
2021-02-18T09:38:40Z
Backport PR #39868 on branch 1.2.x (CI: filter json DeprecationWarning)
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index dba4b9214e50c..aaf97b16aaefe 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -745,6 +745,9 @@ def test_read_json_table_timezones_orient(self, idx, vals, recwarn): result = pd.read_json(out, orient="table") tm.assert_frame_equal(df, result) + @pytest.mark.filterwarnings( + "ignore:an integer is required (got type float)*:DeprecationWarning" + ) def test_comprehensive(self): df = DataFrame( {
Backport PR #39868: CI: filter json DeprecationWarning
https://api.github.com/repos/pandas-dev/pandas/pulls/39870
2021-02-17T20:11:40Z
2021-02-18T09:42:50Z
2021-02-18T09:42:49Z
2021-02-18T09:42:50Z
DOC: update link to user guide
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 060652c9f94ae..f1328b0eeee5e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4066,8 +4066,8 @@ def lookup(self, row_labels, col_labels) -> np.ndarray: .. deprecated:: 1.2.0 DataFrame.lookup is deprecated, use DataFrame.melt and DataFrame.loc instead. - For an example see :meth:`~pandas.DataFrame.lookup` - in the user guide. + For further details see + :ref:`Looking up values by index/column labels <indexing.lookup>`. Parameters ----------
- [x] closes #39863
https://api.github.com/repos/pandas-dev/pandas/pulls/39869
2021-02-17T18:29:39Z
2021-02-17T20:56:47Z
2021-02-17T20:56:47Z
2021-02-18T10:13:36Z
CI: filter json DeprecationWarning
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index d967897e16676..9d955545aede3 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -753,6 +753,9 @@ def test_read_json_table_timezones_orient(self, idx, vals, recwarn): result = pd.read_json(out, orient="table") tm.assert_frame_equal(df, result) + @pytest.mark.filterwarnings( + "ignore:an integer is required (got type float)*:DeprecationWarning" + ) def test_comprehensive(self): df = DataFrame( {
- [x] closes #39854 - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry We're already using the same filter in two other places in this file.
https://api.github.com/repos/pandas-dev/pandas/pulls/39868
2021-02-17T18:01:26Z
2021-02-17T20:10:20Z
2021-02-17T20:10:19Z
2021-02-17T21:01:30Z
[WIP] ENH: Groupby mode
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 43bf6d9dd1fee..eeb5592d744d6 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -1,6 +1,7 @@ import cython from cython import Py_ssize_t +from cpython.ref cimport PyObject from cython cimport floating from libc.stdlib cimport ( free, @@ -56,6 +57,7 @@ cdef enum InterpolationEnumType: INTERPOLATION_NEAREST, INTERPOLATION_MIDPOINT +include "groupby_mode_helper.pxi" cdef inline float64_t median_linear(float64_t* a, int n) nogil: cdef: diff --git a/pandas/_libs/groupby_mode_helper.pxi.in b/pandas/_libs/groupby_mode_helper.pxi.in new file mode 100644 index 0000000000000..de784a9ce7d09 --- /dev/null +++ b/pandas/_libs/groupby_mode_helper.pxi.in @@ -0,0 +1,177 @@ +{{py: + +# name +cimported_types = [#'complex64', + #'complex128', + 'float32', + 'float64', + 'int8', + 'int16', + 'int32', + 'int64', + 'pymap', + 'str', + 'strbox', + 'uint8', + 'uint16', + 'uint32', + 'uint64'] +}} + +{{for name in cimported_types}} +from pandas._libs.khash cimport ( + kh_destroy_{{name}}, + kh_exist_{{name}}, + kh_get_{{name}}, + kh_init_{{name}}, + kh_put_{{name}}, + kh_resize_{{name}}, + kh_{{name}}_t, +) + +{{endfor}} + +from pandas._libs.khash cimport ( + #khcomplex64_t, + #khcomplex128_t, + khiter_t, +) + +from pandas._libs.hashtable import ( + # NaN checking + #is_nan_khcomplex128_t, + #is_nan_khcomplex64_t, + is_nan_float64_t, + is_nan_float32_t, + is_nan_int64_t, + is_nan_int32_t, + is_nan_int16_t, + is_nan_int8_t, + is_nan_uint64_t, + is_nan_uint32_t, + is_nan_uint16_t, + is_nan_uint8_t, + # Casting + #to_complex64, + #to_complex128, + #to_khcomplex128_t, + #to_khcomplex64_t, +) + +{{py: +# TODO: add complex64 and complex128 (requires comparisons between complex numbers) +# dtype, ttype, c_type, to_c_type, to_dtype +dtypes = [#('complex128', 'complex128', 'khcomplex128_t', + # 'to_khcomplex128_t', 'to_complex128'), + #('complex64', 'complex64', 'khcomplex64_t', + # 'to_khcomplex64_t', 'to_complex64'), + ('float64', 'float64', 'float64_t', '', ''), + ('float32', 'float32', 'float32_t', '', ''), + ('uint64', 'uint64', 'uint64_t', '', ''), + ('uint32', 'uint32', 'uint32_t', '', ''), + ('uint16', 'uint16', 'uint16_t', '', ''), + ('uint8', 'uint8', 'uint8_t', '', ''), + ('object', 'pymap', 'object', '', ''), + ('int64', 'int64', 'int64_t', '', ''), + ('int32', 'int32', 'int32_t', '', ''), + ('int16', 'int16', 'int16_t', '', ''), + ('int8', 'int8', 'int8_t', '', '')] + +}} + +{{for dtype, ttype, c_type, to_c_type, to_dtype in dtypes}} + + +@cython.wraparound(False) +@cython.boundscheck(False) +cdef {{c_type}} calc_mode_{{dtype}}(kh_{{ttype}}_t *table): + cdef: + {{c_type}} mode = 0 # fix annoying uninitialized warning + {{c_type}} val + int count, max_count = 0 + khiter_t k + + for k in range(table.n_buckets): + if kh_exist_{{ttype}}(table, k): + count = table.vals[k] + {{if dtype != 'object'}} + val = table.keys[k] + if count == max_count and val < mode: + {{else}} + val = <object>table.keys[k] + if count == max_count: + {{endif}} + mode = val + elif count > max_count: + mode = val + max_count = count + return mode + + +@cython.wraparound(False) +@cython.boundscheck(False) +def group_mode_{{dtype}}(ndarray[{{c_type}}, ndim=1] out, + ndarray[{{c_type}}, ndim=1] values, + ndarray[int64_t, ndim=1] labels, + bint dropna = True): + """ + Calculates the mode of each group. + If multimodal returns the smallest mode in each group if numeric. + For all other datatypes, returns a mode. + """ + cdef: + Py_ssize_t i, N = len(values) + int64_t lab, curr_label = -1 + kh_{{ttype}}_t *table + khiter_t k + int ret = 0 + + table = kh_init_{{ttype}}() + {{if dtype != 'object'}} + #TODO: Fix NOGIL later + #with nogil: + for i in range(N): + lab = labels[i] + if lab < 0: # NaN case + continue + if lab != curr_label and curr_label != -1: + out[curr_label] = calc_mode_{{dtype}}(table) + # Reset variables + max_count = 0 + table = kh_init_{{ttype}}() + + val = {{to_c_type}}(values[i]) + + if not is_nan_{{c_type}}(val) or not dropna: + k = kh_get_{{ttype}}(table, val) + if k != table.n_buckets: + table.vals[k] += 1 + else: + k = kh_put_{{ttype}}(table, val, &ret) + table.vals[k] = 1 + curr_label = lab + # Calc mode for the last group + out[curr_label] = calc_mode_{{dtype}}(table) + {{else}} + for i in range(N): + lab = labels[i] + if lab < 0: # NaN case + continue + if lab != curr_label and curr_label != -1: + out[curr_label] = calc_mode_{{dtype}}(table) + # Reset variables + table = kh_init_{{ttype}}() + + val = values[i] + if not checknull(val) or not dropna: + k = kh_get_{{ttype}}(table, <PyObject*>val) + if k != table.n_buckets: + table.vals[k] += 1 + else: + k = kh_put_{{ttype}}(table, <PyObject*>val, &ret) + table.vals[k] = 1 + curr_label = lab + out[curr_label] = calc_mode_{{dtype}}(table) + {{endif}} + kh_destroy_{{ttype}}(table) +{{endfor}} diff --git a/pandas/_libs/hashtable_class_helper.pxi.in b/pandas/_libs/hashtable_class_helper.pxi.in index 0b6bb170cc531..21a7550a80496 100644 --- a/pandas/_libs/hashtable_class_helper.pxi.in +++ b/pandas/_libs/hashtable_class_helper.pxi.in @@ -42,7 +42,8 @@ c_types = ['khcomplex128_t', {{for c_type in c_types}} -cdef bint is_nan_{{c_type}}({{c_type}} val) nogil: +cpdef bint is_nan_{{c_type}}({{c_type}} val) nogil: + # TODO: create missing.pxi.in and move there as cdef? {{if c_type in {'khcomplex128_t', 'khcomplex64_t'} }} return val.real != val.real or val.imag != val.imag {{elif c_type in {'float64_t', 'float32_t'} }} diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index c169e29b74dbb..f92decce6c6be 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -141,6 +141,7 @@ def _gotitem(self, key, ndim, subset=None): "mad", "max", "mean", + "mode", "median", "min", "ngroup", diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index bc277bf67614d..072b53ba65381 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1578,6 +1578,35 @@ def median(self, numeric_only=True): numeric_only=numeric_only, ) + @final + @Substitution(name="groupby") + @Appender(_common_see_also) + def mode(self, dropna=True, numeric_only=False): + """ + Compute mode of groups, excluding missing values. If a group has + multiple modes, the smallest mode will be used. + + Parameters + ---------- + dropna : bool, default True + Do not use NaNs in mode calculation + numeric_only: bool, default False + Include only float, int, boolean columns. If None, will attempt to use + everything, then use only numeric data. + Returns + ------- + Series or DataFrame + Mode of values within each group. + """ + # Note: get_cythonized_result iterates in python, slow for many columns? + return self._get_cythonized_result( + "group_mode", + aggregate=True, + numeric_only=numeric_only, + needs_values=True, + dropna=dropna, + ) + @final @Substitution(name="groupby") @Appender(_common_see_also) @@ -2585,7 +2614,7 @@ def cummax(self, axis=0, **kwargs): def _get_cythonized_result( self, how: str, - cython_dtype: np.dtype, + cython_dtype: np.dtype = None, aggregate: bool = False, numeric_only: bool = True, needs_counts: bool = False, @@ -2666,12 +2695,18 @@ def _get_cythonized_result( labels, _, ngroups = grouper.group_info output: Dict[base.OutputKey, np.ndarray] = {} - base_func = getattr(libgroupby, how) + if cython_dtype is not None: + base_func = getattr(libgroupby, how) error_msg = "" for idx, obj in enumerate(self._iterate_slices()): name = obj.name values = obj._values + if cython_dtype is None: + cython_dtype = values.dtype + # We also need to get the specific function for that dtype + how += f"_{cython_dtype}" + base_func = getattr(libgroupby, how) if numeric_only and not is_numeric_dtype(values): continue diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index f9b45f4d9f4cf..d0085a408785b 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -388,3 +388,25 @@ def test_cython_agg_EA_known_dtypes(data, op_name, action, with_na): result = grouped["col"].aggregate(op_name) assert result.dtype == expected_dtype + + +def test_mode_numeric(): + data = { + "A": [0, 0, 0, 0, 1, 1, 1, 1, 1, 1.0, np.nan, np.nan], + "B": ["A", "B"] * 6, + "C": [2, 4, 3, 1, 2, 3, 4, 5, 2, 7, 9, 9], + } + df = DataFrame(data) + df.drop(columns="B", inplace=True) + # Group by 1 column + result = df.groupby("A").mode() + exp = DataFrame({"C": [1, 2]}, index=Series([0.0, 1.0], name="A")) + tm.assert_frame_equal(result, exp) + # Group by 2 column + df = DataFrame(data) + result = df.groupby(by=["A", "B"]).mode() + exp = DataFrame( + {"C": [3, 1, 2, 7]}, + index=pd.MultiIndex.from_product([[0.0, 1.0], ["A", "B"]], names=["A", "B"]), + ) + tm.assert_frame_equal(result, exp) diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index de8335738791d..3a5e0fb0231d2 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -285,6 +285,7 @@ def test_tab_completion(mframe): "mean", "median", "min", + "mode", "ngroups", "nth", "ohlc", diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 4049ef46f3006..f518997c7e7db 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -52,6 +52,7 @@ def f(a): "max": np.NaN, "mean": np.NaN, "median": np.NaN, + "mode": np.NaN, "min": np.NaN, "nth": np.NaN, "nunique": 0, diff --git a/setup.py b/setup.py index 45548fed68322..47a7b18d20d32 100755 --- a/setup.py +++ b/setup.py @@ -56,6 +56,10 @@ def is_platform_mac(): _pxi_dep_template = { "algos": ["_libs/algos_common_helper.pxi.in", "_libs/algos_take_helper.pxi.in"], + "groupby": [ + "_libs/groupby_mode_helper.pxi.in", + "_libs/khash_for_primitive_helper.pxi.in", + ], "hashtable": [ "_libs/hashtable_class_helper.pxi.in", "_libs/hashtable_func_helper.pxi.in", @@ -440,7 +444,14 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "include": klib_include, "depends": _pxi_dep["algos"], }, - "_libs.groupby": {"pyxfile": "_libs/groupby"}, + "_libs.groupby": { + "pyxfile": "_libs/groupby", + "include": klib_include, + "depends": ( + ["pandas/_libs/src/klib/khash_python.h", "pandas/_libs/src/klib/khash.h"] + + _pxi_dep["groupby"] + ), + }, "_libs.hashing": {"pyxfile": "_libs/hashing", "depends": []}, "_libs.hashtable": { "pyxfile": "_libs/hashtable",
- [x] closes #19254 - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry Proof of concept for #19254 Is relatively fast compared to @rhshadrach method ``` In [4]: %timeit df.groupby("a").mode() 2.52 ms ± 415 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [5]: %timeit df.groupby("a").mode() 1.99 ms ± 60.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [6]: %timeit gb_mode(df, ['a'], 'b') 3.9 ms ± 310 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [7]: %timeit gb_mode(df, ['a'], 'b') 3.8 ms ± 270 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [8]: %timeit gb_mode(df, ['a'], 'b') 3.89 ms ± 433 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` API for what to do when multimodal needs discussion though.
https://api.github.com/repos/pandas-dev/pandas/pulls/39867
2021-02-17T17:57:51Z
2021-04-14T18:59:47Z
null
2021-04-14T18:59:47Z
TYP: @final for Block methods
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ae019c2f853a1..206b7f02fd449 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -32,6 +32,7 @@ Dtype, DtypeObj, Shape, + final, ) from pandas.util._validators import validate_bool_kwarg @@ -231,6 +232,7 @@ def _holder(self): """ return None + @final @property def _consolidate_key(self): return self._can_consolidate, self.dtype.name @@ -242,6 +244,7 @@ def is_view(self) -> bool: values = cast(np.ndarray, values) return values.base is not None + @final @property def is_categorical(self) -> bool: return self._holder is Categorical @@ -278,6 +281,7 @@ def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: return self.values.astype(object) return self.values + @final def get_block_values_for_json(self) -> np.ndarray: """ This is used in the JSON C code. @@ -300,6 +304,7 @@ def mgr_locs(self, new_mgr_locs): self._mgr_locs = new_mgr_locs + @final def make_block(self, values, placement=None) -> Block: """ Create a new block, with type inference propagate any values that are @@ -312,14 +317,14 @@ def make_block(self, values, placement=None) -> Block: return make_block(values, placement=placement, ndim=self.ndim) - def make_block_same_class(self, values, placement=None, ndim=None) -> Block: + @final + def make_block_same_class(self, values, placement=None) -> Block: """ Wrap given values in a block of same type as self. """ if placement is None: placement = self.mgr_locs - if ndim is None: - ndim = self.ndim - return type(self)(values, placement=placement, ndim=ndim) + return type(self)(values, placement=placement, ndim=self.ndim) + @final def __repr__(self) -> str: # don't want to print out all of the items here name = type(self).__name__ @@ -332,12 +337,15 @@ def __repr__(self) -> str: return result + @final def __len__(self) -> int: return len(self.values) + @final def __getstate__(self): return self.mgr_locs.indexer, self.values + @final def __setstate__(self, state): self.mgr_locs = libinternals.BlockPlacement(state[0]) self.values = state[1] @@ -348,6 +356,7 @@ def _slice(self, slicer): return self.values[slicer] + @final def getitem_block(self, slicer, new_mgr_locs=None) -> Block: """ Perform __getitem__-like, return result as block. @@ -371,6 +380,7 @@ def getitem_block(self, slicer, new_mgr_locs=None) -> Block: def shape(self) -> Shape: return self.values.shape + @final @property def dtype(self) -> DtypeObj: return self.values.dtype @@ -389,6 +399,7 @@ def set_inplace(self, locs, values): """ self.values[locs] = values + @final def delete(self, loc) -> None: """ Delete given loc(-s) from block in-place. @@ -396,6 +407,7 @@ def delete(self, loc) -> None: self.values = np.delete(self.values, loc, 0) self.mgr_locs = self.mgr_locs.delete(loc) + @final def apply(self, func, **kwargs) -> List[Block]: """ apply the function to my values; return a block if we are not @@ -427,6 +439,7 @@ def reduce(self, func, ignore_failures: bool = False) -> List[Block]: nb = self.make_block(res_values) return [nb] + @final def _split_op_result(self, result) -> List[Block]: # See also: split_and_operate if is_extension_array_dtype(result) and result.ndim > 1: @@ -487,6 +500,7 @@ def f(mask, val, idx): return self.split_and_operate(None, f, inplace) + @final def _split(self) -> List[Block]: """ Split a block into a list of single-column blocks. @@ -501,6 +515,7 @@ def _split(self) -> List[Block]: new_blocks.append(nb) return new_blocks + @final def split_and_operate( self, mask, f, inplace: bool, ignore_failures: bool = False ) -> List[Block]: @@ -617,6 +632,7 @@ def f(mask, val, idx): return self.split_and_operate(None, f, False) + @final def astype(self, dtype, copy: bool = False, errors: str = "raise"): """ Coerce to the new dtype. @@ -708,6 +724,7 @@ def _can_hold_element(self, element: Any) -> bool: """ require the same dtype as ourselves """ raise NotImplementedError("Implemented on subclasses") + @final def should_store(self, value: ArrayLike) -> bool: """ Should we set self.values[indexer] = value inplace or do we need to cast? @@ -741,12 +758,13 @@ def to_native_types(self, na_rep="nan", quoting=None, **kwargs): return self.make_block(values) # block actions # + @final def copy(self, deep: bool = True): """ copy constructor """ values = self.values if deep: values = values.copy() - return self.make_block_same_class(values, ndim=self.ndim) + return self.make_block_same_class(values) # --------------------------------------------------------------------- # Replace @@ -795,6 +813,7 @@ def replace( blocks = blk.convert(numeric=False, copy=not inplace) return blocks + @final def _replace_regex( self, to_replace, @@ -840,6 +859,7 @@ def _replace_regex( nbs = [block] return nbs + @final def _replace_list( self, src_list: List[Any], @@ -901,6 +921,7 @@ def _replace_list( rb = new_rb return rb + @final def _replace_coerce( self, to_replace, @@ -1135,6 +1156,7 @@ def f(mask, val, idx): new_blocks = self.split_and_operate(mask, f, True) return new_blocks + @final def coerce_to_target_dtype(self, other) -> Block: """ coerce the current block to a dtype compat for other @@ -1150,6 +1172,7 @@ def coerce_to_target_dtype(self, other) -> Block: return self.astype(new_dtype, copy=False) + @final def interpolate( self, method: str = "pad", @@ -1208,6 +1231,7 @@ def interpolate( **kwargs, ) + @final def _interpolate_with_fill( self, method: str = "pad", @@ -1232,9 +1256,10 @@ def _interpolate_with_fill( limit_area=limit_area, ) - blocks = [self.make_block_same_class(values, ndim=self.ndim)] + blocks = [self.make_block_same_class(values)] return self._maybe_downcast(blocks, downcast) + @final def _interpolate( self, method: str, @@ -1447,7 +1472,7 @@ def _unstack(self, unstacker, fill_value, new_placement): new_values = new_values.T[mask] new_placement = new_placement[mask] - blocks = [make_block(new_values, placement=new_placement)] + blocks = [make_block(new_values, placement=new_placement, ndim=2)] return blocks, mask def quantile( @@ -1747,21 +1772,15 @@ def fillna( ) -> List[Block]: values = self.values if inplace else self.values.copy() values = values.fillna(value=value, limit=limit) - return [ - self.make_block_same_class( - values=values, placement=self.mgr_locs, ndim=self.ndim - ) - ] + return [self.make_block_same_class(values=values)] def interpolate( self, method="pad", axis=0, inplace=False, limit=None, fill_value=None, **kwargs ): values = self.values if inplace else self.values.copy() - return self.make_block_same_class( - values=values.fillna(value=fill_value, method=method, limit=limit), - placement=self.mgr_locs, - ) + new_values = values.fillna(value=fill_value, method=method, limit=limit) + return self.make_block_same_class(new_values) def diff(self, n: int, axis: int = 1) -> List[Block]: if axis == 0 and n != 0: @@ -1783,13 +1802,8 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Blo Dispatches to underlying ExtensionArray and re-boxes in an ExtensionBlock. """ - return [ - self.make_block_same_class( - self.values.shift(periods=periods, fill_value=fill_value), - placement=self.mgr_locs, - ndim=self.ndim, - ) - ] + new_values = self.values.shift(periods=periods, fill_value=fill_value) + return [self.make_block_same_class(new_values)] def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: @@ -1836,7 +1850,7 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: np.where(cond, self.values, other), dtype=dtype ) - return [self.make_block_same_class(result, placement=self.mgr_locs)] + return [self.make_block_same_class(result)] def _unstack(self, unstacker, fill_value, new_placement): # ExtensionArray-safe unstack. diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index aa3545b83dfe3..16440f7a4c2bf 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -118,11 +118,8 @@ def concatenate_block_managers( else: b = make_block(values, placement=placement, ndim=blk.ndim) else: - b = make_block( - _concatenate_join_units(join_units, concat_axis, copy=copy), - placement=placement, - ndim=len(axes), - ) + new_values = _concatenate_join_units(join_units, concat_axis, copy=copy) + b = make_block(new_values, placement=placement, ndim=len(axes)) blocks.append(b) return BlockManager(blocks, axes) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b3f0466f236b6..1c6c327dea5e0 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -215,7 +215,7 @@ def make_empty(self: T, axes=None) -> T: assert isinstance(self, SingleBlockManager) # for mypy blk = self.blocks[0] arr = blk.values[:0] - nb = blk.make_block_same_class(arr, placement=slice(0, 0), ndim=1) + nb = blk.make_block_same_class(arr, placement=slice(0, 0)) blocks = [nb] else: blocks = [] @@ -967,12 +967,8 @@ def iget(self, i: int) -> SingleBlockManager: values = block.iget(self.blklocs[i]) # shortcut for select a single-dim from a 2-dim BM - return SingleBlockManager( - block.make_block_same_class( - values, placement=slice(0, len(values)), ndim=1 - ), - self.axes[1], - ) + nb = type(block)(values, placement=slice(0, len(values)), ndim=1) + return SingleBlockManager(nb, self.axes[1]) def iget_values(self, i: int) -> ArrayLike: """
small optimization removing ndim kwarg from make_block_same_class
https://api.github.com/repos/pandas-dev/pandas/pulls/39865
2021-02-17T17:39:09Z
2021-02-21T17:21:14Z
2021-02-21T17:21:14Z
2021-02-21T17:23:00Z
Update offsets.pyx
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 2d4704ad3bda6..14dac644442a1 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1838,12 +1838,11 @@ cdef class YearOffset(SingleConstructorOffset): """ DateOffset that just needs a month. """ + _attributes = tuple(["n", "normalize", "month"]) - # _default_month: int # FIXME: python annotation here breaks things - cdef readonly: - int month + int month, _default_month, _period_dtype_code def __init__(self, n=1, normalize=False, month=None): BaseOffset.__init__(self, n, normalize) @@ -1853,6 +1852,8 @@ cdef class YearOffset(SingleConstructorOffset): if month < 1 or month > 12: raise ValueError("Month must go from 1 to 12") + + self._period_dtype_code = PeriodDtypeCode.A + self.month % 12 cpdef __setstate__(self, state): self.month = state.pop("month") @@ -1865,8 +1866,11 @@ cdef class YearOffset(SingleConstructorOffset): kwargs = {} if suffix: kwargs["month"] = MONTH_TO_CAL_NUM[suffix] + else: + if cls._default_month is not None: + kwargs["month"] = cls._default_month return cls(**kwargs) - + @property def rule_code(self) -> str: month = MONTH_ALIASES[self.month] @@ -1902,40 +1906,58 @@ cdef class YearOffset(SingleConstructorOffset): ) return shifted - -cdef class BYearEnd(YearOffset): + +cdef class YearBegin(YearOffset): + """ + DateOffset increments between calendar year begin dates. + + Examples + -------- + >>> from pandas.tseries.offsets import YearBegin + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + YearBegin() + Timestamp('2021-01-01 05:01:15') + >>> ts + YearBegin(normalize = True) + Timestamp('2021-01-01 00:00:00') + >>> ts + YearBegin()._from_name('APR') + Timestamp('2021-04-01 05:01:15') """ - DateOffset increments between the last business day of the year. + _outputName = "YearBegin" + _default_month = 1 + _prefix = "AS" + _day_opt = "start" + + +cdef class YearEnd(YearOffset): + """ + DateOffset increments between calendar year ends. + Examples -------- - >>> from pandas.tseries.offset import BYearEnd + >>> from pandas.tseries.offsets import YearEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') - >>> ts - BYearEnd() - Timestamp('2019-12-31 05:01:15') - >>> ts + BYearEnd() + >>> ts + YearEnd() Timestamp('2020-12-31 05:01:15') - >>> ts + BYearEnd(3) - Timestamp('2022-12-30 05:01:15') - >>> ts + BYearEnd(-3) - Timestamp('2017-12-29 05:01:15') - >>> ts + BYearEnd(month=11) - Timestamp('2020-11-30 05:01:15') + >>> ts + YearEnd(normalize = True) + Timestamp('2020-12-31 00:00:00') + >>> ts + YearEnd()._from_name('AUG') + Timestamp('2020-08-31 05:01:15') """ - _outputName = "BusinessYearEnd" + _outputName = "YearEnd" _default_month = 12 - _prefix = "BA" - _day_opt = "business_end" - - + _prefix = "A" + _day_opt = "end" + + cdef class BYearBegin(YearOffset): """ DateOffset increments between the first business day of the year. Examples -------- - >>> from pandas.tseries.offset import BYearBegin + >>> from pandas.tseries.offsets import BYearBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BYearBegin() Timestamp('2021-01-01 05:01:15') @@ -1951,36 +1973,47 @@ cdef class BYearBegin(YearOffset): _default_month = 1 _prefix = "BAS" _day_opt = "business_start" + - -cdef class YearEnd(YearOffset): - """ - DateOffset increments between calendar year ends. +cdef class BYearEnd(YearOffset): """ + DateOffset increments between the last business days of offset years. + Here, the year is a period of 12 consecutive calendar months + (January - December by default). The "month" parameter allows custom setting + of the final month in a year (and correspondingly - the year start month). + + Parameters + ---------- + n : int, default 1 + Number of years to offset. + normalize: bool, default False + If true, the time component of the resulting date-time is converted to + 00:00:00, i.e. midnight (the start, not the end of date-time). + month: int, default 12 + The calendar month number (12 for December) of the ending month + in a custom-defined year to be used as offset. - _default_month = 12 - _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): - """ - DateOffset increments between calendar year begin dates. + Examples + -------- + >>> from pandas.tseries.offsets import BYearEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts - BYearEnd() + Timestamp('2019-12-31 05:01:15') + >>> ts + BYearEnd() + Timestamp('2020-12-31 05:01:15') + >>> ts + BYearEnd(3) + Timestamp('2022-12-30 05:01:15') + >>> ts + BYearEnd(-3) + Timestamp('2017-12-29 05:01:15') + >>> ts + BYearEnd(month=11) + Timestamp('2020-11-30 05:01:15') """ - _default_month = 1 - _prefix = "AS" - _day_opt = "start" - + _outputName = "BusinessYearEnd" + _default_month = 12 + _prefix = "BA" + _day_opt = "business_end" + # ---------------------------------------------------------------------- # Quarter-Based Offset Classes @@ -1991,19 +2024,21 @@ cdef class QuarterOffset(SingleConstructorOffset): # point. Also apply_index, is_on_offset, rule_code if # startingMonth vs month attr names are resolved - # FIXME: python annotations here breaks things - # _default_starting_month: int - # _from_name_starting_month: int cdef readonly: - int startingMonth + int startingMonth, _default_month, _period_dtype_code def __init__(self, n=1, normalize=False, startingMonth=None): BaseOffset.__init__(self, n, normalize) - - if startingMonth is None: - startingMonth = self._default_starting_month - self.startingMonth = startingMonth + + if startingMonth is not None: + if startingMonth < 1 or startingMonth > 12: + raise ValueError("Month must go from 1 to 12") + self.startingMonth = startingMonth + else: + self.startingMonth = self._default_month + + self._period_dtype_code = PeriodDtypeCode.Q_DEC + self.startingMonth % 12 cpdef __setstate__(self, state): self.startingMonth = state.pop("startingMonth") @@ -2016,8 +2051,8 @@ cdef class QuarterOffset(SingleConstructorOffset): if suffix: kwargs["startingMonth"] = MONTH_TO_CAL_NUM[suffix] else: - if cls._from_name_starting_month is not None: - kwargs["startingMonth"] = cls._from_name_starting_month + if cls._default_month is not None: + kwargs["startingMonth"] = cls._default_month return cls(**kwargs) @property @@ -2070,7 +2105,7 @@ cdef class BQuarterEnd(QuarterOffset): Examples -------- - >>> from pandas.tseries.offset import BQuarterEnd + >>> from pandas.tseries.offsets import BQuarterEnd >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BQuarterEnd() Timestamp('2020-06-30 05:01:15') @@ -2081,9 +2116,9 @@ cdef class BQuarterEnd(QuarterOffset): >>> ts + BQuarterEnd(startingMonth=2) Timestamp('2020-05-29 05:01:15') """ + _output_name = "BusinessQuarterEnd" - _default_starting_month = 3 - _from_name_starting_month = 12 + _default_month = 3 _prefix = "BQ" _day_opt = "business_end" @@ -2098,20 +2133,20 @@ cdef class BQuarterBegin(QuarterOffset): Examples -------- - >>> from pandas.tseries.offset import BQuarterBegin + >>> from pandas.tseries.offsets import BQuarterBegin >>> ts = pd.Timestamp('2020-05-24 05:01:15') >>> ts + BQuarterBegin() - Timestamp('2020-06-01 05:01:15') + Timestamp('2020-07-01 05:01:15') >>> ts + BQuarterBegin(2) - Timestamp('2020-09-01 05:01:15') + Timestamp('2020-10-01 05:01:15') >>> ts + BQuarterBegin(startingMonth=2) Timestamp('2020-08-03 05:01:15') >>> ts + BQuarterBegin(-1) - Timestamp('2020-03-02 05:01:15') + Timestamp('2020-04-01 05:01:15') """ + _output_name = "BusinessQuarterBegin" - _default_starting_month = 3 - _from_name_starting_month = 1 + _default_month = 1 _prefix = "BQS" _day_opt = "business_start" @@ -2123,20 +2158,26 @@ cdef class QuarterEnd(QuarterOffset): startingMonth = 1 corresponds to dates like 1/31/2007, 4/30/2007, ... startingMonth = 2 corresponds to dates like 2/28/2007, 5/31/2007, ... startingMonth = 3 corresponds to dates like 3/31/2007, 6/30/2007, ... + + Examples + -------- + >>> from pandas.tseries.offsets import QuarterEnd + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + QuarterEnd(2) + Timestamp('2020-09-30 05:01:15') + >>> ts + QuarterEnd()._from_name('JUN') + Timestamp('2020-06-30 05:01:15') + >>> ts + QuarterEnd(1, normalize = True) + Timestamp('2020-06-30 00:00:00') + >>> ts + QuarterEnd(-2, startingMonth = 2) + Timestamp('2019-11-30 05:01:15') """ - _default_starting_month = 3 + + _output_name = "QuarterEnd" + _default_month = 3 _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): """ @@ -2145,9 +2186,23 @@ cdef class QuarterBegin(QuarterOffset): startingMonth = 1 corresponds to dates like 1/01/2007, 4/01/2007, ... startingMonth = 2 corresponds to dates like 2/01/2007, 5/01/2007, ... startingMonth = 3 corresponds to dates like 3/01/2007, 6/01/2007, ... + + Examples + -------- + >>> from pandas.tseries.offsets import QuarterBegin + >>> ts = pd.Timestamp('2020-05-24 05:01:15') + >>> ts + QuarterBegin()._from_name('MAR') + Timestamp('2020-06-01 05:01:15') + >>> ts + QuarterBegin() + Timestamp('2020-07-01 05:01:15') + >>> ts + QuarterBegin(2) + Timestamp('2020-10-01 05:01:15') + >>> ts + QuarterBegin(2, startingMonth = 2) + Timestamp('2020-11-01 05:01:15') """ - _default_starting_month = 3 - _from_name_starting_month = 1 + + _output_name = "QuarterBegin" + _default_month = 1 _prefix = "QS" _day_opt = "start" @@ -2156,6 +2211,11 @@ cdef class QuarterBegin(QuarterOffset): # Month-Based Offset Classes cdef class MonthOffset(SingleConstructorOffset): + cdef readonly: + int _period_dtype_code + + _period_dtype_code = PeriodDtypeCode.M + def is_on_offset(self, dt: datetime) -> bool: if self.normalize and not _is_normalized(dt): return False @@ -2184,22 +2244,43 @@ cdef class MonthOffset(SingleConstructorOffset): BaseOffset.__setstate__(self, state) + +cdef class MonthBegin(MonthOffset): + """ + DateOffset of one month at beginning. + """ + _prefix = "MS" + _day_opt = "start" + + cdef class MonthEnd(MonthOffset): """ DateOffset of one month end. """ - _period_dtype_code = PeriodDtypeCode.M + _prefix = "M" _day_opt = "end" -cdef class MonthBegin(MonthOffset): +cdef class BusinessMonthBegin(MonthOffset): """ - DateOffset of one month at beginning. + DateOffset of one month at the first business day. + + Examples + -------- + >>> from pandas.tseries.offset import BMonthBegin + >>> ts=pd.Timestamp('2020-05-24 05:01:15') + >>> ts + BMonthBegin() + Timestamp('2020-06-01 05:01:15') + >>> ts + BMonthBegin(2) + Timestamp('2020-07-01 05:01:15') + >>> ts + BMonthBegin(-3) + Timestamp('2020-03-02 05:01:15') """ - _prefix = "MS" - _day_opt = "start" + + _prefix = "BMS" + _day_opt = "business_start" cdef class BusinessMonthEnd(MonthOffset): @@ -2217,29 +2298,11 @@ cdef class BusinessMonthEnd(MonthOffset): >>> ts + BMonthEnd(-2) Timestamp('2020-03-31 05:01:15') """ + _prefix = "BM" _day_opt = "business_end" -cdef class BusinessMonthBegin(MonthOffset): - """ - DateOffset of one month at the first business day. - - Examples - -------- - >>> from pandas.tseries.offset import BMonthBegin - >>> ts=pd.Timestamp('2020-05-24 05:01:15') - >>> ts + BMonthBegin() - Timestamp('2020-06-01 05:01:15') - >>> ts + BMonthBegin(2) - Timestamp('2020-07-01 05:01:15') - >>> ts + BMonthBegin(-3) - Timestamp('2020-03-02 05:01:15') - """ - _prefix = "BMS" - _day_opt = "business_start" - - # --------------------------------------------------------------------- # Semi-Month Based Offsets
Fixes to year, quarter and month offsets. - [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39864
2021-02-17T17:00:10Z
2021-02-17T17:13:07Z
null
2021-02-17T17:13:07Z
[POC] PERF: 1d version of the cython grouped aggregation algorithms
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 43bf6d9dd1fee..03848a7c4af43 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -700,6 +700,225 @@ group_mean_float32 = _group_mean['float'] group_mean_float64 = _group_mean['double'] +@cython.wraparound(False) +@cython.boundscheck(False) +def _group_mean_Corder(floating[:, ::1] out, + int64_t[::1] counts, + ndarray[floating, ndim=2] values, + const int64_t[::1] labels, + Py_ssize_t min_count=-1): + cdef: + Py_ssize_t i, j, N, K, lab, ncounts = len(counts) + floating val, count, y, t + floating[:, ::1] sumx, compensation + int64_t[:, ::1] 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 len_values != len_labels: + raise ValueError("len(index) != len(labels)") + + nobs = np.zeros((<object>out).shape, dtype=np.int64) + sumx = np.zeros_like(out) + compensation = np.zeros_like(out) + + N, K = (<object>values).shape + + with nogil: + for i in range(N): + lab = labels[i] + if lab < 0: + continue + + counts[lab] += 1 + for j in range(K): + val = values[i, j] + # not nan + if val == val: + nobs[lab, j] += 1 + y = val - compensation[lab, j] + t = sumx[lab, j] + y + compensation[lab, j] = t - sumx[lab, j] - y + sumx[lab, j] = t + + for i in range(ncounts): + for j in range(K): + count = nobs[i, j] + if nobs[i, j] == 0: + out[i, j] = NAN + else: + out[i, j] = sumx[i, j] / count + + +group_mean_Corder_float32 = _group_mean_Corder['float'] +group_mean_Corder_float64 = _group_mean_Corder['double'] + + +@cython.wraparound(False) +@cython.boundscheck(False) +def _group_mean_transposed(floating[:, :] out, + int64_t[:] counts, + ndarray[floating, ndim=2] values, + const int64_t[:] labels, + Py_ssize_t min_count=-1): + cdef: + Py_ssize_t i, j, N, K, lab, ncounts = len(counts) + floating val, count, y, t + floating[:, :] sumx, compensation + 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 len_values != len_labels: + # raise ValueError("len(index) != len(labels)") + + nobs = np.zeros((<object>out).shape, dtype=np.int64) + sumx = np.zeros_like(out) + compensation = np.zeros_like(out) + + K, N = (<object>values).shape + + if N != len_labels: + raise ValueError("len(index) != len(labels)") + + with nogil: + for i in range(N): + lab = labels[i] + if lab < 0: + continue + + counts[lab] += 1 + for j in range(K): + val = values[j, i] + # not nan + if val == val: + nobs[j, lab] += 1 + y = val - compensation[j, lab] + t = sumx[j, lab] + y + compensation[j, lab] = t - sumx[j, lab] - y + sumx[j, lab] = t + + for i in range(ncounts): + for j in range(K): + count = nobs[j, i] + if nobs[j, i] == 0: + out[j, i] = NAN + else: + out[j, i] = sumx[j, i] / count + + +group_mean_transposed_float32 = _group_mean_transposed['float'] +group_mean_transposed_float64 = _group_mean_transposed['double'] + + +@cython.wraparound(False) +@cython.boundscheck(False) +def _group_mean_1d(floating[:] out, + int64_t[:] counts, + ndarray[floating, ndim=1] values, + const int64_t[:] labels, + Py_ssize_t min_count=-1): + cdef: + Py_ssize_t i, j, N, K, lab, ncounts = len(counts) + floating val, count, y, t + floating[:] sumx, compensation + 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 len_values != len_labels: + raise ValueError("len(index) != len(labels)") + + nobs = np.zeros((<object>out).shape, dtype=np.int64) + sumx = np.zeros_like(out) + compensation = np.zeros_like(out) + + N, = (<object>values).shape + + with nogil: + for i in range(N): + lab = labels[i] + if lab < 0: + continue + + counts[lab] += 1 + val = values[i] + # not nan + if val == val: + nobs[lab] += 1 + y = val - compensation[lab] + t = sumx[lab] + y + compensation[lab] = t - sumx[lab] - y + sumx[lab] = t + + for i in range(ncounts): + count = nobs[i] + if nobs[i] == 0: + out[i] = NAN + else: + out[i] = sumx[i] / count + + +group_mean_1d_float32 = _group_mean_1d['float'] +group_mean_1d_float64 = _group_mean_1d['double'] + + +@cython.wraparound(False) +@cython.boundscheck(False) +def _group_mean_1d_Corder(floating[::1] out, + int64_t[::1] counts, + floating[::1] values, + const int64_t[:] labels, + Py_ssize_t min_count=-1): + cdef: + Py_ssize_t i, j, N, K, lab, ncounts = len(counts) + floating val, count, y, t + floating[::1] sumx, compensation + int64_t[::1] 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 len_values != len_labels: + raise ValueError("len(index) != len(labels)") + + nobs = np.zeros((<object>out).shape, dtype=np.int64) + sumx = np.zeros_like(out) + compensation = np.zeros_like(out) + + N, = (<object>values).shape + + with nogil: + for i in range(N): + lab = labels[i] + if lab < 0: + continue + + counts[lab] += 1 + val = values[i] + # not nan + if val == val: + nobs[lab] += 1 + y = val - compensation[lab] + t = sumx[lab] + y + compensation[lab] = t - sumx[lab] - y + sumx[lab] = t + + for i in range(ncounts): + count = nobs[i] + if nobs[i] == 0: + out[i] = NAN + else: + out[i] = sumx[i] / count + + +group_mean_1d_Corder_float32 = _group_mean_1d_Corder['float'] +group_mean_1d_Corder_float64 = _group_mean_1d_Corder['double'] + + @cython.wraparound(False) @cython.boundscheck(False) def _group_ohlc(floating[:, :] out,
For now, this is just a small example to open discussion about how to tackle this topic (not meant for merging). Context: for a columnar dataframe (with ArrayManager), we would also perform the groupby operations column by column (instead of on the 2D blocks). Most of our custom cython aggregation algorithms are currently written for 2D arrays (eg `group_add`, `group_mean`, etc. I think only the fill/shift/any/all are 1D). But by being 2D, that means they have some performance penalty when using it for a single column. Experiment: I copied the implementation for "mean" and made a 1D version of it (exactly the same code, but removing one `for` loop over the columns, and simplifying the indices to index into 1D arrays instead of 2D arrays). And with that did some timings to see the impact: ```python N = 1_000_000 df = pd.DataFrame(np.random.randn(N, 10), columns=list("abcdefghij")) df["key"] = np.random.randint(0, 100, size=N) # below I am manually doing the aggregation part for one column of the following groupby operation expected = df.groupby("key").mean() ``` Using the existing 2D algorithm on a single column: ```python codes, uniques = pd.factorize(df["key"], sort=True) out_shape = (len(uniques), 1) out_dtype = "float64" values = df[['a']]._mgr.blocks[0].values.T result = np.empty(out_shape, out_dtype) result.fill(np.nan) counts = np.zeros(len(uniques), dtype=np.int64) pd._libs.groupby.group_mean_float64(result, counts, values, codes, min_count=-1) ``` Using the new 1D version: ```python out_shape1d = (len(uniques),) out_dtype = "float64" values1d = df['a']._mgr.blocks[0].values.copy() result1d = np.empty(out_shape1d, out_dtype) result1d.fill(np.nan) counts = np.zeros(len(uniques), dtype=np.int64) pd._libs.groupby.group_mean_1d_float64(result1d, counts, values1d, codes, min_count=-1) ``` Ensure that both give the same result: ``` In [4]: np.allclose(result.squeeze(), expected['a'].values) Out[4]: True In [5]: np.allclose(result1d, expected['a'].values) Out[5]: True ``` And timings for both: ``` In [8]: %%timeit ...: result = np.empty(out_shape, out_dtype) ...: result.fill(np.nan) ...: counts = np.zeros(len(uniques), dtype=np.int64) ...: pd._libs.groupby.group_mean_float64(result, counts, values, codes, min_count=-1) 4.15 ms ± 54.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [9]: %%timeit ...: result1d = np.empty(out_shape1d, out_dtype) ...: result1d.fill(np.nan) ...: counts = np.zeros(len(uniques), dtype=np.int64) ...: pd._libs.groupby.group_mean_1d_float64(result1d, counts, values1d, codes, min_count=-1) 2.62 ms ± 38.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` So for a single column, the 1D version is ca 30-40% faster (increasing the size of the array with 10x, I also get 40% faster). Some notes: - The actual aggregation is only a part of the full groupby operation. But for sufficiently large data, it becomes the most significant portion. E.g. for the `df.groupby("key").mean()` example above, the `group_mean` takes ca 1.5x the time of the factorization step (that's for multiple columns, though, when profiling it for grouping a single column, the ratio becomes the other way around: ca 38% in group_mean and ca 62% in factorization) - If we want to have an optimized groupby for the ArrayManager-backed dataframe, I think we will need those 1D versions of the cython algos. Of course, what I currently did here would give a huge duplication in code (and also not easily templateable or so) on the short term. xref https://github.com/pandas-dev/pandas/issues/39146
https://api.github.com/repos/pandas-dev/pandas/pulls/39861
2021-02-17T09:10:05Z
2021-04-26T08:19:54Z
null
2021-04-26T08:19:54Z
DOC: Update matplotlib canonical
diff --git a/doc/source/conf.py b/doc/source/conf.py index 7cd9743e463d0..66f5e631fa656 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -423,7 +423,7 @@ if include_api: intersphinx_mapping = { "dateutil": ("https://dateutil.readthedocs.io/en/latest/", None), - "matplotlib": ("https://matplotlib.org/", None), + "matplotlib": ("https://matplotlib.org/stable/", None), "numpy": ("https://numpy.org/doc/stable/", None), "pandas-gbq": ("https://pandas-gbq.readthedocs.io/en/latest/", None), "py": ("https://pylib.readthedocs.io/en/latest/", None),
Please see https://discourse.matplotlib.org/t/canonical-documentation-have-moved/21863
https://api.github.com/repos/pandas-dev/pandas/pulls/39858
2021-02-17T05:41:48Z
2021-02-17T20:09:31Z
2021-02-17T20:09:31Z
2021-02-17T20:10:54Z
CLN: assorted cleanups
diff --git a/Makefile b/Makefile index 2c968234749f5..f47c50032f83c 100644 --- a/Makefile +++ b/Makefile @@ -25,16 +25,3 @@ doc: cd doc; \ python make.py clean; \ python make.py html - -check: - python3 scripts/validate_unwanted_patterns.py \ - --validation-type="private_function_across_module" \ - --included-file-extensions="py" \ - --excluded-file-paths=pandas/tests,asv_bench/ \ - pandas/ - - python3 scripts/validate_unwanted_patterns.py \ - --validation-type="private_import_across_module" \ - --included-file-extensions="py" \ - --excluded-file-paths=pandas/tests,asv_bench/,doc/ - pandas/ diff --git a/pandas/core/common.py b/pandas/core/common.py index 50aed70bf275d..c3ec78324cf8d 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -49,11 +49,7 @@ ABCSeries, ) from pandas.core.dtypes.inference import iterable_not_string -from pandas.core.dtypes.missing import ( # noqa - isna, - isnull, - notnull, -) +from pandas.core.dtypes.missing import isna class SettingWithCopyError(ValueError): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index f1328b0eeee5e..52a48b6b165f2 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -752,10 +752,11 @@ def _can_fast_transpose(self) -> bool: """ if isinstance(self._mgr, ArrayManager): return False - if self._mgr.any_extension_types: - # TODO(EA2D) special case would be unnecessary with 2D EAs + blocks = self._mgr.blocks + if len(blocks) != 1: return False - return len(self._mgr.blocks) == 1 + + return not self._mgr.any_extension_types # ---------------------------------------------------------------------- # Rendering Methods diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index c2fabfc332b23..812cffdeb58f6 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -822,9 +822,7 @@ def _convert_list_indexer(self, keyarr): def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: if not isinstance(dtype, IntervalDtype): return False - if self.closed != dtype.closed: - return False - common_subtype = find_common_type([self.dtype.subtype, dtype.subtype]) + common_subtype = find_common_type([self.dtype, dtype]) return not is_object_dtype(common_subtype) # -------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ae019c2f853a1..abc59f818978c 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1001,7 +1001,7 @@ def setitem(self, indexer, value): arr_value = value else: is_ea_value = False - arr_value = np.array(value) + arr_value = np.asarray(value) if transpose: values = values.T @@ -1640,8 +1640,8 @@ def setitem(self, indexer, value): be a compatible shape. """ if not self._can_hold_element(value): - # This is only relevant for DatetimeTZBlock, which has a - # non-trivial `_can_hold_element`. + # This is only relevant for DatetimeTZBlock, ObjectValuesExtensionBlock, + # which has a non-trivial `_can_hold_element`. # https://github.com/pandas-dev/pandas/issues/24020 # Need a dedicated setitem until GH#24020 (type promotion in setitem # for extension arrays) is designed and implemented. @@ -2052,6 +2052,8 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Blo class DatetimeLikeBlockMixin(NDArrayBackedExtensionBlock): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" + is_numeric = False + _can_hold_na = True _dtype: np.dtype _holder: Type[Union[DatetimeArray, TimedeltaArray]] @@ -2104,10 +2106,6 @@ class DatetimeBlock(DatetimeLikeBlockMixin): _dtype = fill_value.dtype _holder = DatetimeArray - @property - def _can_hold_na(self): - return True - def set_inplace(self, locs, values): """ See Block.set.__doc__ @@ -2124,6 +2122,8 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): __slots__ = () is_extension = True + _can_hold_na = True + is_numeric = False _holder = DatetimeArray @@ -2188,8 +2188,6 @@ def fillna( class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () - _can_hold_na = True - is_numeric = False _holder = TimedeltaArray fill_value = np.timedelta64("NaT", "ns") _dtype = fill_value.dtype diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index aa3545b83dfe3..16440f7a4c2bf 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -118,11 +118,8 @@ def concatenate_block_managers( else: b = make_block(values, placement=placement, ndim=blk.ndim) else: - b = make_block( - _concatenate_join_units(join_units, concat_axis, copy=copy), - placement=placement, - ndim=len(axes), - ) + new_values = _concatenate_join_units(join_units, concat_axis, copy=copy) + b = make_block(new_values, placement=placement, ndim=len(axes)) blocks.append(b) return BlockManager(blocks, axes) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 4ccdbc089a058..543bf44e61216 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -429,7 +429,7 @@ def unstack(obj, level, fill_value=None): return obj.T.stack(dropna=False) elif not isinstance(obj.index, MultiIndex): # GH 36113 - # Give nicer error messages when unstack a Series whose + # Give nicer error messages when unstack a Series whose # Index is not a MultiIndex. raise ValueError( f"index must be a MultiIndex to unstack, {type(obj.index)} was passed" @@ -451,9 +451,10 @@ def _unstack_frame(obj, level, fill_value=None): mgr = obj._mgr.unstack(unstacker, fill_value=fill_value) return obj._constructor(mgr) else: - return _Unstacker( - obj.index, level=level, constructor=obj._constructor - ).get_result(obj._values, value_columns=obj.columns, fill_value=fill_value) + unstacker = _Unstacker(obj.index, level=level, constructor=obj._constructor) + return unstacker.get_result( + obj._values, value_columns=obj.columns, fill_value=fill_value + ) def _unstack_extension_series(series, level, fill_value): diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 3df54f769a6e4..b08442321f502 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -2090,6 +2090,7 @@ def test_td64arr_div_numeric_array( expected = [tdser[n] / vector[n] for n in range(len(tdser))] expected = pd.Index(expected) # do dtype inference expected = tm.box_expected(expected, xbox) + assert tm.get_dtype(expected) == "m8[ns]" if using_array_manager and box_with_array is pd.DataFrame: # TODO the behaviour is buggy here (third column with all-NaT diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 881e47f4f5fe2..d5e5cabc93b66 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -921,7 +921,7 @@ def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self): with pytest.raises(ValueError, match=msg): obj.iloc[nd3] = 0 - @pytest.mark.parametrize("indexer", [lambda x: x.loc, lambda x: x.iloc]) + @pytest.mark.parametrize("indexer", [tm.loc, tm.iloc]) def test_iloc_getitem_read_only_values(self, indexer): # GH#10043 this is fundamentally a test for iloc, but test loc while # we're here diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 35f6647b631aa..d5f3af12ef5a5 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -242,6 +242,88 @@ def test_setitem_callable_other(self): tm.assert_series_equal(ser, expected) +class TestSetitemWithExpansion: + def test_setitem_empty_series(self): + # GH#10193 + key = Timestamp("2012-01-01") + series = Series(dtype=object) + series[key] = 47 + expected = Series(47, [key]) + tm.assert_series_equal(series, expected) + + def test_setitem_empty_series_datetimeindex_preserves_freq(self): + # GH#33573 our index should retain its freq + series = Series([], DatetimeIndex([], freq="D"), dtype=object) + key = Timestamp("2012-01-01") + series[key] = 47 + expected = Series(47, DatetimeIndex([key], freq="D")) + tm.assert_series_equal(series, expected) + assert series.index.freq == expected.index.freq + + def test_setitem_empty_series_timestamp_preserves_dtype(self): + # GH 21881 + timestamp = Timestamp(1412526600000000000) + series = Series([timestamp], index=["timestamp"], dtype=object) + expected = series["timestamp"] + + series = Series([], dtype=object) + series["anything"] = 300.0 + series["timestamp"] = timestamp + result = series["timestamp"] + assert result == expected + + @pytest.mark.parametrize( + "td", + [ + Timedelta("9 days"), + Timedelta("9 days").to_timedelta64(), + Timedelta("9 days").to_pytimedelta(), + ], + ) + def test_append_timedelta_does_not_cast(self, td): + # GH#22717 inserting a Timedelta should _not_ cast to int64 + expected = Series(["x", td], index=[0, "td"], dtype=object) + + ser = Series(["x"]) + ser["td"] = td + tm.assert_series_equal(ser, expected) + assert isinstance(ser["td"], Timedelta) + + ser = Series(["x"]) + ser.loc["td"] = Timedelta("9 days") + tm.assert_series_equal(ser, expected) + assert isinstance(ser["td"], Timedelta) + + +def test_setitem_scalar_into_readonly_backing_data(): + # GH#14359: test that you cannot mutate a read only buffer + + array = np.zeros(5) + array.flags.writeable = False # make the array immutable + series = Series(array) + + for n in range(len(series)): + msg = "assignment destination is read-only" + with pytest.raises(ValueError, match=msg): + series[n] = 1 + + assert array[n] == 0 + + +def test_setitem_slice_into_readonly_backing_data(): + # GH#14359: test that you cannot mutate a read only buffer + + array = np.zeros(5) + array.flags.writeable = False # make the array immutable + series = Series(array) + + msg = "assignment destination is read-only" + with pytest.raises(ValueError, match=msg): + series[1:3] = 1 + + assert not array.any() + + class TestSetitemCasting: @pytest.mark.parametrize("unique", [True, False]) @pytest.mark.parametrize("val", [3, 3.0, "3"], ids=type) @@ -445,88 +527,6 @@ def val(self, request): return request.param -class TestSetitemWithExpansion: - def test_setitem_empty_series(self): - # GH#10193 - key = Timestamp("2012-01-01") - series = Series(dtype=object) - series[key] = 47 - expected = Series(47, [key]) - tm.assert_series_equal(series, expected) - - def test_setitem_empty_series_datetimeindex_preserves_freq(self): - # GH#33573 our index should retain its freq - series = Series([], DatetimeIndex([], freq="D"), dtype=object) - key = Timestamp("2012-01-01") - series[key] = 47 - expected = Series(47, DatetimeIndex([key], freq="D")) - tm.assert_series_equal(series, expected) - assert series.index.freq == expected.index.freq - - def test_setitem_empty_series_timestamp_preserves_dtype(self): - # GH 21881 - timestamp = Timestamp(1412526600000000000) - series = Series([timestamp], index=["timestamp"], dtype=object) - expected = series["timestamp"] - - series = Series([], dtype=object) - series["anything"] = 300.0 - series["timestamp"] = timestamp - result = series["timestamp"] - assert result == expected - - @pytest.mark.parametrize( - "td", - [ - Timedelta("9 days"), - Timedelta("9 days").to_timedelta64(), - Timedelta("9 days").to_pytimedelta(), - ], - ) - def test_append_timedelta_does_not_cast(self, td): - # GH#22717 inserting a Timedelta should _not_ cast to int64 - expected = Series(["x", td], index=[0, "td"], dtype=object) - - ser = Series(["x"]) - ser["td"] = td - tm.assert_series_equal(ser, expected) - assert isinstance(ser["td"], Timedelta) - - ser = Series(["x"]) - ser.loc["td"] = Timedelta("9 days") - tm.assert_series_equal(ser, expected) - assert isinstance(ser["td"], Timedelta) - - -def test_setitem_scalar_into_readonly_backing_data(): - # GH#14359: test that you cannot mutate a read only buffer - - array = np.zeros(5) - array.flags.writeable = False # make the array immutable - series = Series(array) - - for n in range(len(series)): - msg = "assignment destination is read-only" - with pytest.raises(ValueError, match=msg): - series[n] = 1 - - assert array[n] == 0 - - -def test_setitem_slice_into_readonly_backing_data(): - # GH#14359: test that you cannot mutate a read only buffer - - array = np.zeros(5) - array.flags.writeable = False # make the array immutable - series = Series(array) - - msg = "assignment destination is read-only" - with pytest.raises(ValueError, match=msg): - series[1:3] = 1 - - assert not array.any() - - class TestSetitemTimedelta64IntoNumeric(SetitemCastingEquivalents): # timedelta64 should not be treated as integers when setting into # numeric Series
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39856
2021-02-17T03:51:45Z
2021-02-21T17:16:21Z
2021-02-21T17:16:21Z
2021-02-21T17:23:36Z
REF/POC: DTBlock/TDBlock backed directly by DTA/TDA
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 40533cdd554b3..792b4a91754bc 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -63,6 +63,7 @@ is_period_dtype, is_scalar, is_signed_integer_dtype, + is_strict_ea, is_timedelta64_dtype, is_unsigned_integer_dtype, needs_i8_conversion, @@ -1779,6 +1780,11 @@ def take_nd( if isinstance(arr, ABCExtensionArray): # Check for EA to catch DatetimeArray, TimedeltaArray + if not is_strict_ea(arr): + # i.e. DatetimeArray, TimedeltaArray + return arr.take( + indexer, axis=axis, fill_value=fill_value, allow_fill=allow_fill + ) return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) arr = extract_array(arr) diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 825757ddffee4..6c1f8049f6d20 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -171,6 +171,10 @@ def T(self: NDArrayBackedExtensionArrayT) -> NDArrayBackedExtensionArrayT: new_data = self._ndarray.T return self._from_backing_data(new_data) + def swapaxes(self, axis1, axis2): + res_values = self._ndarray.swapaxes(axis1, axis2) + return self._from_backing_data(res_values) + # ------------------------------------------------------------------------ def equals(self, other) -> bool: @@ -287,7 +291,7 @@ def fillna( if mask.any(): if method is not None: - func = missing.get_fill_func(method) + func = missing.get_fill_func(method, ndim=self.ndim) new_values = func(self._ndarray.copy(), limit=limit, mask=mask) # TODO: PandasArray didn't used to copy, need tests for this new_values = self._from_backing_data(new_values) @@ -378,8 +382,10 @@ def where( res_values = np.where(mask, self._ndarray, value) return self._from_backing_data(res_values) - def delete(self: NDArrayBackedExtensionArrayT, loc) -> NDArrayBackedExtensionArrayT: - res_values = np.delete(self._ndarray, loc) + def delete( + self: NDArrayBackedExtensionArrayT, loc, axis: int = 0 + ) -> NDArrayBackedExtensionArrayT: + res_values = np.delete(self._ndarray, loc, axis=axis) return self._from_backing_data(res_values) # ------------------------------------------------------------------------ diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index edc8fa14ca142..36ec6b61de9ac 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -618,7 +618,7 @@ def argsort( mask=np.asarray(self.isna()), ) - def argmin(self, skipna: bool = True) -> int: + def argmin(self, axis: int = 0, skipna: bool = True): """ Return the index of minimum value. @@ -640,9 +640,9 @@ def argmin(self, skipna: bool = True) -> int: validate_bool_kwarg(skipna, "skipna") if not skipna and self.isna().any(): raise NotImplementedError - return nargminmax(self, "argmin") + return nargminmax(self, "argmin", axis=axis) - def argmax(self, skipna: bool = True) -> int: + def argmax(self, axis: int = 0, skipna: bool = True): """ Return the index of maximum value. @@ -664,7 +664,7 @@ def argmax(self, skipna: bool = True) -> int: validate_bool_kwarg(skipna, "skipna") if not skipna and self.isna().any(): raise NotImplementedError - return nargminmax(self, "argmax") + return nargminmax(self, "argmax", axis=axis) def fillna(self, value=None, method=None, limit=None): """ diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 05184ea02e7a2..99e1f3f50b3d1 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -616,6 +616,10 @@ def astype(self, dtype, copy=True): elif is_datetime64_ns_dtype(dtype): return astype_dt64_to_dt64tz(self, dtype, copy, via_utc=False) + elif self.tz is None and is_datetime64_dtype(dtype) and dtype != self.dtype: + # unit conversion + return self._data.astype(dtype) + elif is_period_dtype(dtype): return self.to_period(freq=dtype.freq) return dtl.DatetimeLikeArrayMixin.astype(self, dtype, copy) diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 0966d0b93cc25..48a3d382e6039 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -1495,6 +1495,31 @@ def is_extension_type(arr) -> bool: return False +def is_strict_ea(obj): + """ + ExtensionArray that does not support 2D, or more specifically that does + not use HybridBlock. + """ + from pandas.core.arrays import ( + DatetimeArray, + ExtensionArray, + TimedeltaArray, + ) + + return isinstance(obj, ExtensionArray) and not isinstance( + obj, (DatetimeArray, TimedeltaArray) + ) + + +def is_ea_dtype(dtype) -> bool: + """ + Analogue to is_extension_array_dtype but excluding DatetimeTZDtype. + """ + # Note: if other EA dtypes are ever held in HybridBlock, exclude those + # here too. + return is_extension_array_dtype(dtype) and not is_datetime64tz_dtype(dtype) + + def is_extension_array_dtype(arr_or_dtype) -> bool: """ Check if an object is a pandas extension array type. diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 42ac786ff315e..1e8f7f06ed24c 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -108,6 +108,7 @@ def is_nonempty(x) -> bool: to_concat = non_empties kinds = {obj.dtype.kind for obj in to_concat} + _contains_datetime = any(kind in ["m", "M"] for kind in kinds) all_empty = not len(non_empties) single_dtype = len({x.dtype for x in to_concat}) == 1 @@ -122,11 +123,13 @@ def is_nonempty(x) -> bool: if isinstance(to_concat[0], ExtensionArray): cls = type(to_concat[0]) + if _contains_datetime: + return _concat_datetime(to_concat, axis=axis) return cls._concat_same_type(to_concat) else: - return np.concatenate(to_concat) + return np.concatenate(to_concat, axis=axis) - elif any(kind in ["m", "M"] for kind in kinds): + elif _contains_datetime: return _concat_datetime(to_concat, axis=axis) elif all_empty: @@ -344,14 +347,5 @@ def _concat_datetime(to_concat, axis=0): # in Timestamp/Timedelta return _concatenate_2d([x.astype(object) for x in to_concat], axis=axis) - if axis == 1: - # TODO(EA2D): kludge not necessary with 2D EAs - to_concat = [x.reshape(1, -1) if x.ndim == 1 else x for x in to_concat] - result = type(to_concat[0])._concat_same_type(to_concat, axis=axis) - - if result.ndim == 2 and is_extension_array_dtype(result.dtype): - # TODO(EA2D): kludge not necessary with 2D EAs - assert result.shape[0] == 1 - result = result[0] return result diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 060652c9f94ae..492e308710793 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -110,6 +110,7 @@ is_datetime64_any_dtype, is_dict_like, is_dtype_equal, + is_ea_dtype, is_extension_array_dtype, is_float, is_float_dtype, @@ -121,6 +122,7 @@ is_object_dtype, is_scalar, is_sequence, + is_strict_ea, pandas_dtype, ) from pandas.core.dtypes.missing import ( @@ -752,10 +754,13 @@ def _can_fast_transpose(self) -> bool: """ if isinstance(self._mgr, ArrayManager): return False - if self._mgr.any_extension_types: - # TODO(EA2D) special case would be unnecessary with 2D EAs + blocks = self._mgr.blocks + if len(blocks) != 1: return False - return len(self._mgr.blocks) == 1 + + dtype = blocks[0].dtype + # TODO(EA2D) special case would be unnecessary with 2D EAs + return not is_ea_dtype(dtype) # ---------------------------------------------------------------------- # Rendering Methods @@ -2981,9 +2986,23 @@ def transpose(self, *args, copy: bool = False) -> DataFrame: # construct the args dtypes = list(self.dtypes) - if self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]): + if self._mgr.nblocks == 1 and not is_strict_ea(self._mgr.blocks[0].values): + # Note: tests pass without this, but this improves perf quite a bit. + # TODO: something like frame.values but that _may_ give an EA + blk = self._mgr.blocks[0] + new_values = blk.values + if copy: + new_values = new_values.copy() + result = self._constructor( + new_values, index=self.columns, columns=self.index + ) + + elif ( + self._is_homogeneous_type and dtypes and is_extension_array_dtype(dtypes[0]) + ): # We have EAs with the same dtype. We can preserve that dtype in transpose. dtype = dtypes[0] + arr_type = dtype.construct_array_type() values = self.values @@ -2991,6 +3010,7 @@ def transpose(self, *args, copy: bool = False) -> DataFrame: result = self._constructor( dict(zip(self.index, new_values)), index=self.columns ) + # TODO: what if index is non-unique? (not specific to EA2D) else: new_values = self.values.T @@ -9021,6 +9041,8 @@ def func(values: np.ndarray): def blk_func(values, axis=1): if isinstance(values, ExtensionArray): + if not is_strict_ea(values): + return values._reduce(name, axis=1, skipna=skipna, **kwds) return values._reduce(name, skipna=skipna, **kwds) else: return op(values, axis=axis, skipna=skipna, **kwds) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index c1a277925de2a..1df3e48cedd77 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -65,6 +65,7 @@ is_interval_dtype, is_numeric_dtype, is_scalar, + is_strict_ea, needs_i8_conversion, ) from pandas.core.dtypes.missing import ( @@ -82,10 +83,7 @@ validate_func_kwargs, ) from pandas.core.apply import GroupByApply -from pandas.core.arrays import ( - Categorical, - ExtensionArray, -) +from pandas.core.arrays import Categorical from pandas.core.base import ( DataError, SpecificationError, @@ -1115,7 +1113,7 @@ def py_fallback(bvalues: ArrayLike) -> ArrayLike: obj: FrameOrSeriesUnion # call our grouper again with only this block - if isinstance(bvalues, ExtensionArray): + if is_strict_ea(bvalues): # TODO(EA2D): special case not needed with 2D EAs obj = Series(bvalues) else: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 00cb65fff3803..06667a3ea9c57 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -71,6 +71,7 @@ ) import pandas.core.algorithms as algorithms +from pandas.core.arrays import ExtensionArray from pandas.core.base import SelectionMixin import pandas.core.common as com from pandas.core.frame import DataFrame @@ -208,7 +209,9 @@ def apply(self, f: F, data: FrameOrSeries, axis: int = 0): result_values = None sdata: FrameOrSeries = splitter._get_sorted_data() - if sdata.ndim == 2 and np.any(sdata.dtypes.apply(is_extension_array_dtype)): + if sdata.ndim == 2 and any( + isinstance(x, ExtensionArray) for x in sdata._iter_column_arrays() + ): # calling splitter.fast_apply will raise TypeError via apply_frame_axis0 # if we pass EA instead of ndarray # TODO: can we have a workaround for EAs backed by ndarray? diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 4150ec745bd2e..0097959245686 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -309,6 +309,10 @@ def astype(self, dtype, copy=True): return self return self.copy() + if isinstance(dtype, np.dtype) and dtype.kind == "M" and dtype != "M8[ns]": + # For now Datetime supports this by unwrapping ndarray, but DTI doesn't + raise TypeError(f"Cannot cast {type(self._data).__name__} to dtype") + new_values = self._data.astype(dtype, copy=copy) # pass copy=False because any copying will be done in the diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ae019c2f853a1..2185180e07abc 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -26,7 +26,6 @@ writers, ) from pandas._libs.internals import BlockPlacement -from pandas._libs.tslibs import conversion from pandas._typing import ( ArrayLike, Dtype, @@ -51,10 +50,12 @@ is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, + is_ea_dtype, is_extension_array_dtype, is_list_like, is_object_dtype, is_sparse, + is_strict_ea, pandas_dtype, ) from pandas.core.dtypes.dtypes import ( @@ -112,7 +113,6 @@ Float64Index, Index, ) - from pandas.core.arrays._mixins import NDArrayBackedExtensionArray class Block(PandasObject): @@ -276,7 +276,7 @@ def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: """ if is_object_dtype(dtype): return self.values.astype(object) - return self.values + return np.asarray(self.values) def get_block_values_for_json(self) -> np.ndarray: """ @@ -308,7 +308,7 @@ def make_block(self, values, placement=None) -> Block: if placement is None: placement = self.mgr_locs if self.is_extension: - values = _block_shape(values, ndim=self.ndim) + values = block_shape(values, ndim=self.ndim) return make_block(values, placement=placement, ndim=self.ndim) @@ -434,7 +434,10 @@ def _split_op_result(self, result) -> List[Block]: # if we get a 2D ExtensionArray, we need to split it into 1D pieces nbs = [] for i, loc in enumerate(self.mgr_locs): - vals = result[i] + if not is_strict_ea(result): + vals = result[i : i + 1] + else: + vals = result[i] block = self.make_block(values=vals, placement=[loc]) nbs.append(block) return nbs @@ -533,7 +536,7 @@ def make_a_block(nv, ref_loc): else: # Put back the dimension that was taken from it and make # a block out of the result. - nv = _block_shape(nv, ndim=self.ndim) + nv = block_shape(nv, ndim=self.ndim) block = self.make_block(values=nv, placement=ref_loc) return block @@ -674,6 +677,15 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike: values = self.values + if ( + values.dtype.kind in ["m", "M"] + and dtype.kind in ["i", "u"] + and dtype.itemsize != 8 + ): + # TODO(2.0) remove special case once deprecation on DTA/TDA is enforced + msg = rf"cannot astype a datetimelike from [{values.dtype}] to [{dtype}]" + raise TypeError(msg) + if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype): return astype_dt64_to_dt64tz(values, dtype, copy, via_utc=True) @@ -988,11 +1000,6 @@ def setitem(self, indexer, value): # current dtype cannot store value, coerce to common dtype return self.coerce_to_target_dtype(value).setitem(indexer, value) - if self.dtype.kind in ["m", "M"]: - arr = self.array_values().T - arr[indexer] = value - return self - # value must be storable at this moment if is_extension_array_dtype(getattr(value, "dtype", None)): # We need to be careful not to allow through strings that @@ -1524,9 +1531,8 @@ def __init__(self, values, placement, ndim: int): ndim = 2 super().__init__(values, placement, ndim=ndim) - if self.ndim == 2 and len(self.mgr_locs) != 1: - # TODO(EA2D): check unnecessary with 2D EAs - raise AssertionError("block.size != values.size") + if self.ndim == 2 and len(self.mgr_locs) > 1: + raise ValueError("need to split... for now") @property def shape(self) -> Shape: @@ -1640,8 +1646,8 @@ def setitem(self, indexer, value): be a compatible shape. """ if not self._can_hold_element(value): - # This is only relevant for DatetimeTZBlock, which has a - # non-trivial `_can_hold_element`. + # This is only relevant for DatetimeTZBlock, ObjectValuesExtensionBlock, + # which has a non-trivial `_can_hold_element`. # https://github.com/pandas-dev/pandas/issues/24020 # Need a dedicated setitem until GH#24020 (type promotion in setitem # for extension arrays) is designed and implemented. @@ -1873,9 +1879,13 @@ def quantile(self, qs, interpolation="linear", axis: int = 0) -> Block: result = quantile_with_mask(values, mask, fill_value, qs, interpolation, axis) if not is_sparse(self.dtype): - # shape[0] should be 1 as long as EAs are 1D - assert result.shape == (1, len(qs)), result.shape - result = type(self.values)._from_factorized(result[0], self.values) + if self.values.ndim == 1: + # shape[0] should be 1 as long as EAs are 1D + assert result.shape == (1, len(qs)), result.shape + result = type(self.values)._from_factorized(result[0], self.values) + else: + # NDArrayBackedExtensionBlock, e.g. DatetimeTZBlock + result = type(self.values)._from_factorized(result, self.values) return make_block(result, placement=self.mgr_locs, ndim=2) @@ -1965,28 +1975,11 @@ def to_native_types( class NDArrayBackedExtensionBlock(HybridMixin, Block): """ - Block backed by an NDArrayBackedExtensionArray + Block backed by an NDarrayBackedExtensionArray, supporting 2D values. """ - def internal_values(self): - # Override to return DatetimeArray and TimedeltaArray - return self.array_values() - - def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: - """ - return object dtype as boxed values, such as Timestamps/Timedelta - """ - values = self.array_values() - if is_object_dtype(dtype): - # DTA/TDA constructor and astype can handle 2D - values = values.astype(object) - # TODO(EA2D): reshape not needed with 2D EAs - return np.asarray(values).reshape(self.shape) - - def iget(self, key): - # GH#31649 we need to wrap scalars in Timestamp/Timedelta - # TODO(EA2D): this can be removed if we ever have 2D EA - return self.array_values().reshape(self.shape)[key] + def array_values(self): + return self.values def putmask(self, mask, new) -> List[Block]: mask = extract_bool_array(mask) @@ -1994,28 +1987,47 @@ def putmask(self, mask, new) -> List[Block]: if not self._can_hold_element(new): return self.astype(object).putmask(mask, new) - # TODO(EA2D): reshape unnecessary with 2D EAs - arr = self.array_values().reshape(self.shape) - arr = cast("NDArrayBackedExtensionArray", arr) + arr = self.values arr.T.putmask(mask, new) return [self] def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: - # TODO(EA2D): reshape unnecessary with 2D EAs - arr = self.array_values().reshape(self.shape) - - cond = extract_bool_array(cond) + arr = self.values try: res_values = arr.T.where(cond, other).T except (ValueError, TypeError): - return super().where(other, cond, errors=errors, axis=axis) + return Block.where(self, other, cond, errors=errors, axis=axis) - # TODO(EA2D): reshape not needed with 2D EAs - res_values = res_values.reshape(self.values.shape) nb = self.make_block_same_class(res_values) return [nb] + @property + def is_view(self) -> bool: + """ return a boolean if I am possibly a view """ + # check the ndarray values of the DatetimeIndex values + return self.values._data.base is not None + + def setitem(self, indexer, value): + if not self._can_hold_element(value): + # TODO: general case needs casting logic. + return self.astype(object).setitem(indexer, value) + + transpose = self.ndim == 2 + + values = self.values + if transpose: + values = values.T + values[indexer] = value + return self + + def delete(self, loc) -> None: + """ + Delete given loc(-s) from block in-place. + """ + self.values = self.values.delete(loc, 0) + self.mgr_locs = self.mgr_locs.delete(loc) + def diff(self, n: int, axis: int = 0) -> List[Block]: """ 1st discrete difference. @@ -2036,22 +2048,37 @@ def diff(self, n: int, axis: int = 0) -> List[Block]: The arguments here are mimicking shift so they are called correctly by apply. """ - # TODO(EA2D): reshape not necessary with 2D EAs - values = self.array_values().reshape(self.shape) + values = self.values new_values = values - values.shift(n, axis=axis) return [self.make_block(new_values)] def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Block]: - # TODO(EA2D) this is unnecessary if these blocks are backed by 2D EAs - values = self.array_values().reshape(self.shape) + values = self.values new_values = values.shift(periods, fill_value=fill_value, axis=axis) return [self.make_block_same_class(new_values)] + def fillna( + self, value, limit=None, inplace: bool = False, downcast=None + ) -> List[Block]: + + if not self._can_hold_element(value) and self.dtype.kind != "m": + # We support filling a DatetimeTZ with a `value` whose timezone + # is different by coercing to object. + # TODO: don't special-case td64 + return self.astype(object).fillna(value, limit, inplace, downcast) + + values = self.values + values = values if inplace else values.copy() + new_values = values.fillna(value=value, limit=limit) + return [self.make_block_same_class(values=new_values)] + class DatetimeLikeBlockMixin(NDArrayBackedExtensionBlock): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" + is_numeric = False + _can_hold_na = True _dtype: np.dtype _holder: Type[Union[DatetimeArray, TimedeltaArray]] @@ -2072,30 +2099,30 @@ def _maybe_coerce_values(cls, values): Overridden by DatetimeTZBlock. """ - if values.dtype != cls._dtype: + if cls.fill_value is not NaT and values.dtype != cls._dtype: # non-nano we will convert to nano if values.dtype.kind != cls._dtype.kind: # caller is responsible for ensuring td64/dt64 dtype raise TypeError(values.dtype) # pragma: no cover - values = cls._holder._from_sequence(values)._data + values = cls._holder._from_sequence(values) - if isinstance(values, cls._holder): - values = values._data + if not isinstance(values, cls._holder): + values = cls._holder(values) - assert isinstance(values, np.ndarray), type(values) return values - def array_values(self): - return self._holder._simple_new(self.values) - def to_native_types(self, na_rep="NaT", **kwargs): """ convert to our native types format """ - arr = self.array_values() - + arr = self.values result = arr._format_native_types(na_rep=na_rep, **kwargs) return self.make_block(result) + def external_values(self): + # NB: for dt64tz this is different from np.asarray(self.values), + # since that return an object-dtype ndarray of Timestamps. + return self.values._data + class DatetimeBlock(DatetimeLikeBlockMixin): __slots__ = () @@ -2104,104 +2131,42 @@ class DatetimeBlock(DatetimeLikeBlockMixin): _dtype = fill_value.dtype _holder = DatetimeArray - @property - def _can_hold_na(self): - return True - - def set_inplace(self, locs, values): - """ - See Block.set.__doc__ - """ - values = conversion.ensure_datetime64ns(values, copy=False) - - self.values[locs] = values - -class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): +class DatetimeTZBlock(DatetimeBlock, ExtensionBlock): """ implement a datetime64 block with a tz attribute """ values: DatetimeArray __slots__ = () is_extension = True + _validate_ndim = True + _can_consolidate = True _holder = DatetimeArray - - internal_values = Block.internal_values - _can_hold_element = DatetimeBlock._can_hold_element - to_native_types = DatetimeBlock.to_native_types - diff = DatetimeBlock.diff fill_value = NaT - where = DatetimeBlock.where - putmask = DatetimeLikeBlockMixin.putmask - - array_values = ExtensionBlock.array_values - @classmethod - def _maybe_coerce_values(cls, values): - """ - Input validation for values passed to __init__. Ensure that - we have datetime64TZ, coercing if necessary. + get_values = Block.get_values + set_inplace = Block.set_inplace + iget = Block.iget + _slice = Block._slice + shape = Block.shape + __init__ = Block.__init__ + take_nd = Block.take_nd + _unstack = Block._unstack - Parameters - ---------- - values : array-like - Must be convertible to datetime64 - - Returns - ------- - values : DatetimeArray - """ - if not isinstance(values, cls._holder): - values = cls._holder(values) - - if values.tz is None: - raise ValueError("cannot create a DatetimeTZBlock without a tz") - - return values - - @property - def is_view(self) -> bool: - """ return a boolean if I am possibly a view """ - # check the ndarray values of the DatetimeIndex values - return self.values._data.base is not None - - def external_values(self): - # NB: this is different from np.asarray(self.values), since that - # return an object-dtype ndarray of Timestamps. - # Avoid FutureWarning in .astype in casting from dt64tz to dt64 - return self.values._data - - def fillna( - self, value, limit=None, inplace: bool = False, downcast=None - ) -> List[Block]: - # We support filling a DatetimeTZ with a `value` whose timezone - # is different by coercing to object. - if self._can_hold_element(value): - return super().fillna(value, limit, inplace, downcast) - - # different timezones, or a non-tz - return self.astype(object).fillna( - value, limit=limit, inplace=inplace, downcast=downcast - ) + # TODO: we still share these with ExtensionBlock (and not DatetimeBlock) + # ['interpolate', 'quantile'] + # [x for x in dir(DatetimeTZBlock) if hasattr(ExtensionBlock, x) + # and getattr(DatetimeTZBlock, x) is getattr(ExtensionBlock, x) + # and getattr(ExtensionBlock, x) is not getattr(Block, x)] class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () - _can_hold_na = True - is_numeric = False _holder = TimedeltaArray fill_value = np.timedelta64("NaT", "ns") _dtype = fill_value.dtype - def fillna( - self, value, limit=None, inplace: bool = False, downcast=None - ) -> List[Block]: - values = self.array_values() - values = values if inplace else values.copy() - new_values = values.fillna(value=value, limit=limit) - return [self.make_block_same_class(values=new_values)] - class ObjectBlock(Block): __slots__ = () @@ -2277,7 +2242,8 @@ def f(mask, val, idx): if isinstance(values, np.ndarray): # TODO(EA2D): allow EA once reshape is supported values = values.reshape(shape) - + if isinstance(values, ABCIndex): + values = values._data return values if self.ndim == 2: @@ -2408,6 +2374,10 @@ def make_block( # TODO: This is no longer hit internally; does it need to be retained # for e.g. pyarrow? values = DatetimeArray._simple_new(values, dtype=dtype) + placement = BlockPlacement(placement) + if len(placement) == 1 and values.ndim == 1 and (ndim is None or ndim == 2): + # TODO: unnecessary after https://github.com/apache/arrow/pull/8957 + values = values.reshape(1, -1) return klass(values, ndim=ndim, placement=placement) @@ -2431,11 +2401,11 @@ def extend_blocks(result, blocks=None) -> List[Block]: return blocks -def _block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: +def block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: """ guarantee the shape of the values to be at least 1 d """ if values.ndim < ndim: shape = values.shape - if not is_extension_array_dtype(values.dtype): + if not is_strict_ea(values): # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. @@ -2459,8 +2429,10 @@ def safe_reshape(arr: ArrayLike, new_shape: Shape) -> ArrayLike: ------- np.ndarray or ExtensionArray """ - if not is_extension_array_dtype(arr.dtype): + if not is_ea_dtype(arr.dtype): # Note: this will include TimedeltaArray and tz-naive DatetimeArray # TODO(EA2D): special case will be unnecessary with 2D EAs - arr = np.asarray(arr).reshape(new_shape) + arr = extract_array(arr, extract_numpy=True).reshape(new_shape) + if type(arr).__name__ == "PandasArray": + arr = arr.to_numpy() return arr diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index aa3545b83dfe3..a28436a9a82b8 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -27,8 +27,10 @@ from pandas.core.dtypes.common import ( is_datetime64tz_dtype, is_dtype_equal, + is_ea_dtype, is_extension_array_dtype, is_sparse, + is_strict_ea, ) from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.missing import ( @@ -108,9 +110,14 @@ def concatenate_block_managers( values = np.concatenate(vals, axis=blk.ndim - 1) else: # TODO(EA2D): special-casing not needed with 2D EAs - values = concat_compat(vals) - if not isinstance(values, ExtensionArray): - values = values.reshape(1, len(values)) + if all(x.ndim == blk.ndim for x in vals): + # i.e. DTA/TDA + values = concat_compat(vals, axis=blk.ndim - 1) + else: + values = concat_compat(vals) + + if not is_strict_ea(values) and blk.ndim == 2 and values.ndim == 1: + values = values.reshape(1, -1) if blk.values.dtype == values.dtype: # Fast-path @@ -118,11 +125,8 @@ def concatenate_block_managers( else: b = make_block(values, placement=placement, ndim=blk.ndim) else: - b = make_block( - _concatenate_join_units(join_units, concat_axis, copy=copy), - placement=placement, - ndim=len(axes), - ) + new_values = _concatenate_join_units(join_units, concat_axis, copy=copy) + b = make_block(new_values, placement=placement, ndim=len(axes)) blocks.append(b) return BlockManager(blocks, axes) @@ -310,12 +314,11 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: fill_value = None if is_datetime64tz_dtype(empty_dtype): - # TODO(EA2D): special case unneeded with 2D EAs - i8values = np.full(self.shape[1], fill_value.value) + i8values = np.full(self.shape, fill_value.value) return DatetimeArray(i8values, dtype=empty_dtype) elif is_extension_array_dtype(blk_dtype): pass - elif is_extension_array_dtype(empty_dtype): + elif is_ea_dtype(empty_dtype): cls = empty_dtype.construct_array_type() missing_arr = cls._from_sequence([], dtype=empty_dtype) ncols, nrows = self.shape @@ -378,6 +381,7 @@ def _concatenate_join_units( ju.get_reindexed_values(empty_dtype=empty_dtype, upcasted_na=upcasted_na) for ju in join_units ] + ndim = max(x.ndim for x in to_concat) if len(to_concat) == 1: # Only one block, nothing to concatenate. @@ -390,17 +394,24 @@ def _concatenate_join_units( concat_values = concat_values.copy() else: concat_values = concat_values.copy() + elif any(isinstance(t, ExtensionArray) for t in to_concat): + # TODO(EA2D): special case not needed if all EAs used HybridBlocks + # NB: we are still assuming here that Hybrid blocks have shape (1, N) # concatting with at least one EA means we are concatting a single column # the non-EA values are 2D arrays with shape (1, n) - to_concat = [t if isinstance(t, ExtensionArray) else t[0, :] for t in to_concat] + to_concat = [t if is_strict_ea(t) else t[0, :] for t in to_concat] concat_values = concat_compat(to_concat, axis=0, ea_compat_axis=True) - if not is_extension_array_dtype(concat_values.dtype): + # TODO: what if we have dt64tz blocks with more than 1 column? + + if concat_values.ndim < ndim and not is_strict_ea(concat_values): # if the result of concat is not an EA but an ndarray, reshape to # 2D to put it a non-EA Block - # special case DatetimeArray/TimedeltaArray, which *is* an EA, but - # is put in a consolidated 2D block - concat_values = np.atleast_2d(concat_values) + # special case DatetimeArray, which *is* an EA, but is put in a + # consolidated 2D block + # TODO(EA2D): we could just get this right within concat_compat + concat_values = concat_values.reshape(1, -1) + else: concat_values = concat_compat(to_concat, axis=concat_axis) diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 2cfe613b7072b..7a41fd277293d 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -40,6 +40,7 @@ from pandas.core.dtypes.common import ( is_datetime64tz_dtype, is_dtype_equal, + is_ea_dtype, is_extension_array_dtype, is_integer_dtype, is_list_like, @@ -58,7 +59,10 @@ algorithms, common as com, ) -from pandas.core.arrays import Categorical +from pandas.core.arrays import ( + Categorical, + ExtensionArray, +) from pandas.core.construction import ( extract_array, sanitize_array, @@ -70,6 +74,7 @@ get_objs_combined_axis, union_indexes, ) +from pandas.core.internals.blocks import block_shape from pandas.core.internals.managers import ( create_block_manager_from_arrays, create_block_manager_from_blocks, @@ -210,7 +215,7 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool): if not len(values) and columns is not None and len(columns): values = np.empty((0, 1), dtype=object) - if is_extension_array_dtype(values) or is_extension_array_dtype(dtype): + if is_ea_dtype(values) or is_extension_array_dtype(dtype): # GH#19157 if isinstance(values, np.ndarray) and values.ndim > 1: @@ -225,9 +230,18 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool): return arrays_to_mgr(values, columns, index, columns, dtype=dtype) - # by definition an array here - # the dtypes will be coerced to a single dtype - values = _prep_ndarray(values, copy=copy) + if is_datetime64tz_dtype(values): + # TODO: combine into _prep_ndarray? + values = extract_array(values, extract_numpy=True) + if copy: + values = values.copy() + if values.ndim == 1: + values = values.reshape(-1, 1) + + else: + # by definition an array here + # the dtypes will be coerced to a single dtype + values = _prep_ndarray(values, copy=copy) if dtype is not None and not is_dtype_equal(values.dtype, dtype): try: @@ -254,10 +268,12 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool): if values.ndim == 2 and values.shape[0] != 1: # transpose and separate blocks + # TODO: do this in one go dvals_list = [maybe_infer_to_datetimelike(row) for row in values] + dvals_list = [extract_array(x, extract_numpy=True) for x in dvals_list] + # TODO: unpack DatetimeIndex directly in maybe_infer_to_datetimelike for n in range(len(dvals_list)): - if isinstance(dvals_list[n], np.ndarray): - dvals_list[n] = dvals_list[n].reshape(1, -1) + dvals_list[n] = dvals_list[n].reshape(1, -1) from pandas.core.internals.blocks import make_block @@ -270,6 +286,10 @@ def init_ndarray(values, index, columns, dtype: Optional[DtypeObj], copy: bool): else: datelike_vals = maybe_infer_to_datetimelike(values) block_values = [datelike_vals] + block_values = [extract_array(x, extract_numpy=True) for x in block_values] + if values.ndim == 2: + block_values = [block_shape(x, 2) for x in block_values] + else: block_values = [values] @@ -288,7 +308,6 @@ def init_dict(data: Dict, index, columns, dtype: Optional[DtypeObj] = None): arrays = Series(data, index=columns, dtype=object) data_names = arrays.index - missing = arrays.isna() if index is None: # GH10856 @@ -356,7 +375,12 @@ def treat_as_nested(data) -> bool: """ Check if we should use nested_data_to_arrays. """ - return len(data) > 0 and is_list_like(data[0]) and getattr(data[0], "ndim", 1) == 1 + return ( + len(data) > 0 + and is_list_like(data[0]) + and getattr(data[0], "ndim", 1) == 1 + and not (isinstance(data, ExtensionArray) and data.ndim == 2) + ) # --------------------------------------------------------------------- diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b3f0466f236b6..51e6a7ecb7e0b 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -38,7 +38,9 @@ ) from pandas.core.dtypes.common import ( DT64NS_DTYPE, + is_datetime64tz_dtype, is_dtype_equal, + is_ea_dtype, is_extension_array_dtype, is_list_like, ) @@ -69,6 +71,7 @@ DatetimeTZBlock, ExtensionBlock, ObjectValuesExtensionBlock, + block_shape, extend_blocks, get_block_type, make_block, @@ -310,6 +313,16 @@ def unpickle_block(values, mgr_locs, ndim: int): state = state[3]["0.14.1"] self.axes = [ensure_index(ax) for ax in state["axes"]] ndim = len(self.axes) + + for blk in state["blocks"]: + vals = blk["values"] + if is_datetime64tz_dtype(vals.dtype): + # older versions will hold in DatetimeIndex instead of DTA + vals = extract_array(vals, extract_numpy=True) + if vals.ndim == 1 and ndim == 2: + vals = vals.reshape(1, -1) + blk["values"] = vals + self.blocks = tuple( unpickle_block(b["values"], b["mgr_locs"], ndim=ndim) for b in state["blocks"] @@ -1029,7 +1042,7 @@ def iset(self, loc: Union[int, slice, np.ndarray], value): if self._blklocs is None and self.ndim > 1: self._rebuild_blknos_and_blklocs() - value_is_extension_type = is_extension_array_dtype(value) + value_is_extension_type = is_ea_dtype(value) # categorical/sparse/datetimetz if value_is_extension_type: @@ -1165,7 +1178,7 @@ def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False if value.ndim == 2: value = value.T - elif value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype): + elif value.ndim == self.ndim - 1: # TODO(EA2D): special case not needed with 2D EAs value = safe_reshape(value, (1,) + value.shape) @@ -1715,7 +1728,12 @@ def _form_blocks(arrays, names: Index, axes: List[Index]) -> List[Block]: if len(items_dict["DatetimeTZBlock"]): dttz_blocks = [ - make_block(array, klass=DatetimeTZBlock, placement=i, ndim=2) + make_block( + block_shape(extract_array(array), 2), + klass=DatetimeTZBlock, + placement=i, + ndim=2, + ) for i, array in items_dict["DatetimeTZBlock"] ] blocks.extend(dttz_blocks) @@ -1864,7 +1882,13 @@ def _merge_blocks( # TODO: optimization potential in case all mgrs contain slices and # combination of those slices is a slice, too. new_mgr_locs = np.concatenate([b.mgr_locs.as_array for b in blocks]) - new_values = np.vstack([b.values for b in blocks]) + + if isinstance(blocks[0].dtype, np.dtype): + new_values = np.vstack([b.values for b in blocks]) + else: + new_values = blocks[0].values._concat_same_type( + [b.values for b in blocks], axis=0 + ) argsort = np.argsort(new_mgr_locs) new_values = new_values[argsort] diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py index 70d4f3b91c245..3f018d5e802f7 100644 --- a/pandas/core/internals/ops.py +++ b/pandas/core/internals/ops.py @@ -8,8 +8,6 @@ Tuple, ) -import numpy as np - from pandas._typing import ArrayLike if TYPE_CHECKING: @@ -32,7 +30,7 @@ def _iter_block_pairs( locs = blk.mgr_locs blk_vals = blk.values - left_ea = not isinstance(blk_vals, np.ndarray) + left_ea = blk_vals.ndim == 1 rblks = right._slice_take_blocks_ax0(locs.indexer, only_slice=True) @@ -43,7 +41,7 @@ def _iter_block_pairs( # assert rblks[0].shape[0] == 1, rblks[0].shape for k, rblk in enumerate(rblks): - right_ea = not isinstance(rblk.values, np.ndarray) + right_ea = rblk.values.ndim == 1 lvals, rvals = _get_same_shape_values(blk, rblk, left_ea, right_ea) info = BlockPairInfo(lvals, rvals, locs, left_ea, right_ea, rblk) diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 9ae5f7d1b7497..98ab01c46ce23 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -729,9 +729,11 @@ def _backfill_2d(values, limit=None, mask=None): _fill_methods = {"pad": _pad_1d, "backfill": _backfill_1d} -def get_fill_func(method): +def get_fill_func(method, ndim: int = 1): method = clean_fill_method(method) - return _fill_methods[method] + if ndim == 1: + return _fill_methods[method] + return {"pad": _pad_2d, "backfill": _backfill_2d}[method] def clean_reindex_fill_method(method): diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 67863036929b3..aa7e9b400f475 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -396,7 +396,7 @@ def nargsort( return indexer -def nargminmax(values, method: str): +def nargminmax(values, method: str, axis: int = 0): """ Implementation of np.argmin/argmax but for ExtensionArray and which handles missing values. @@ -405,6 +405,7 @@ def nargminmax(values, method: str): ---------- values : ExtensionArray method : {"argmax", "argmin"} + axis : int, default 0 Returns ------- @@ -416,11 +417,17 @@ def nargminmax(values, method: str): mask = np.asarray(isna(values)) values = values._values_for_argsort() - idx = np.arange(len(values)) + idx = np.arange(values.shape[axis]) + if values.ndim > 1 and values.size > 0: + # values.size check is a kludge bc JSONArray can come back with size-0 2D + if mask.any(): + assert False # just checking + return func(values, axis=axis) + non_nans = values[~mask] non_nan_idx = idx[~mask] - return non_nan_idx[func(non_nans)] + return non_nan_idx[func(non_nans, axis=axis)] def _ensure_key_mapped_multiindex( diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 88b444acfea62..42646f0e7c8a1 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -4554,9 +4554,13 @@ def read( # if we have a DataIndexableCol, its shape will only be 1 dim if values.ndim == 1 and isinstance(values, np.ndarray): + # TODO(EA2D): special case not needed with 2D EAs values = values.reshape((1, values.shape[0])) + if isinstance(values, DatetimeIndex) and len(cols_) != 1: + # FIXME: kludge + values = values._data.reshape(len(cols_), -1, order="F") - if isinstance(values, np.ndarray): + if isinstance(values, (np.ndarray, DatetimeArray)): df = DataFrame(values.T, columns=cols_, index=index_) elif isinstance(values, Index): df = DataFrame(values, columns=cols_, index=index_) diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 423d20c46bdb1..92ef97654dd8d 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1020,10 +1020,7 @@ def test_dt64arr_sub_dt64object_array(self, box_with_array, tz_naive_fixture): obj = tm.box_expected(dti, box_with_array) expected = tm.box_expected(expected, box_with_array) - warn = None - if box_with_array is not pd.DataFrame or tz_naive_fixture is None: - warn = PerformanceWarning - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(PerformanceWarning): result = obj - obj.astype(object) tm.assert_equal(result, expected) @@ -1525,10 +1522,7 @@ def test_dt64arr_add_sub_offset_array( if box_other: other = tm.box_expected(other, box_with_array) - warn = PerformanceWarning - if box_with_array is pd.DataFrame and tz is not None: - warn = None - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(PerformanceWarning): res = op(dtarr, other) tm.assert_equal(res, expected) @@ -2469,18 +2463,14 @@ def test_dti_addsub_object_arraylike( expected = DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture) expected = tm.box_expected(expected, xbox) - warn = PerformanceWarning - if box_with_array is pd.DataFrame and tz is not None: - warn = None - - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(PerformanceWarning): result = dtarr + other tm.assert_equal(result, expected) expected = DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture) expected = tm.box_expected(expected, xbox) - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(PerformanceWarning): result = dtarr - other tm.assert_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index 46f5a20f38941..35e958ff3a2b1 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -432,19 +432,11 @@ def test_astype_to_incorrect_datetimelike(self, unit): other = f"m8[{unit}]" df = DataFrame(np.array([[1, 2, 3]], dtype=dtype)) - msg = ( - fr"cannot astype a datetimelike from \[datetime64\[ns\]\] to " - fr"\[timedelta64\[{unit}\]\]" - fr"|(Cannot cast DatetimeArray to dtype timedelta64\[{unit}\])" - ) + msg = fr"Cannot cast DatetimeArray to dtype timedelta64\[{unit}\]" with pytest.raises(TypeError, match=msg): df.astype(other) - msg = ( - fr"cannot astype a timedelta from \[timedelta64\[ns\]\] to " - fr"\[datetime64\[{unit}\]\]" - fr"|(Cannot cast TimedeltaArray to dtype datetime64\[{unit}\])" - ) + msg = 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) diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py index 430abd9700a23..08ffb9dea36e0 100644 --- a/pandas/tests/frame/methods/test_set_index.py +++ b/pandas/tests/frame/methods/test_set_index.py @@ -103,7 +103,8 @@ def test_set_index_dst(self): # single level res = df.set_index("index") exp = DataFrame( - data={"a": [0, 1, 2], "b": [3, 4, 5]}, index=Index(di, name="index") + data={"a": [0, 1, 2], "b": [3, 4, 5]}, + index=Index(di, name="index")._with_freq(None), ) tm.assert_frame_equal(res, exp) diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 193f1617fbb55..c28a2cd9374bc 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -39,7 +39,7 @@ def test_setitem_invalidates_datetime_index_freq(self): ts = dti[1] df = DataFrame({"B": dti}) - assert df["B"]._values.freq == "D" + assert df["B"]._values.freq is None df.iloc[1, 0] = pd.NaT assert df["B"]._values.freq is None diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 4bbdba9fedbff..f9bc03d4745da 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -1003,7 +1003,6 @@ def test_apply_function_with_indexing_return_column(): tm.assert_frame_equal(result, expected) -@pytest.mark.xfail(reason="GH-34998") def test_apply_with_timezones_aware(): # GH: 27212 diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 4dce7e8553be4..e0fe1b5bef288 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -838,7 +838,7 @@ def test_omit_nuisance(df): # won't work with axis = 1 grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) - msg = "reduction operation 'sum' not allowed for this dtype" + msg = "'DatetimeArray' does not implement reduction 'sum'" with pytest.raises(TypeError, match=msg): grouped.agg(lambda x: x.sum(0, numeric_only=False)) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index a24c711df7b55..e7b79d920af0e 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -124,6 +124,8 @@ def create_block(typestr, placement, item_shape=None, num_offset=0): tz = m.groups()[0] assert num_items == 1, "must have only 1 num items for a tz-aware" values = DatetimeIndex(np.arange(N) * 1e9, tz=tz) + if len(shape) == 2: + values = values._data.reshape(1, -1) elif typestr in ("timedelta", "td", "m8[ns]"): values = (mat * 1).astype("m8[ns]") elif typestr in ("category",): @@ -425,7 +427,11 @@ def test_copy(self, mgr): # copy assertion we either have a None for a base or in case of # some blocks it is an array (e.g. datetimetz), but was copied tm.assert_equal(cp_blk.values, blk.values) - if not isinstance(cp_blk.values, np.ndarray): + if isinstance(cp_blk.values, DatetimeArray): + assert ( + cp_blk.values._data.base is None and blk.values._data.base is None + ) or (cp_blk.values._data.base is not blk.values._data.base) + elif not isinstance(cp_blk.values, np.ndarray): assert cp_blk.values._data.base is not blk.values._data.base else: assert cp_blk.values.base is None and blk.values.base is None @@ -490,7 +496,7 @@ def test_astype(self, t): mgr = create_mgr("a,b: object; c: bool; d: datetime; e: f4; f: f2; g: f8") t = np.dtype(t) - with tm.assert_produces_warning(warn): + with tm.assert_produces_warning(warn, check_stacklevel=False): tmgr = mgr.astype(t, errors="ignore") assert tmgr.iget(2).dtype.type == t assert tmgr.iget(4).dtype.type == t @@ -563,10 +569,10 @@ def _compare(old_mgr, new_mgr): assert new_mgr.iget(8).dtype == np.float16 def test_invalid_ea_block(self): - with pytest.raises(AssertionError, match="block.size != values.size"): + with pytest.raises(ValueError, match="need to split"): create_mgr("a: category; b: category") - with pytest.raises(AssertionError, match="block.size != values.size"): + with pytest.raises(ValueError, match="need to split"): create_mgr("a: category2; b: category2") def test_interleave(self): diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 489352380b186..66aa1afb65a00 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -97,6 +97,7 @@ def test_append_with_timezones_dateutil(setup_path): r"existing_value \[dateutil/.*US/Eastern\] " r"conflicts with new value \[dateutil/.*EET\]" ) + msg = r"cannot match existing table structure for \[A,B\] on appending data" with pytest.raises(ValueError, match=msg): store.append("df_tz", df) @@ -195,6 +196,7 @@ def test_append_with_timezones_pytz(setup_path): r"invalid info for \[values_block_1\] for \[tz\], " r"existing_value \[US/Eastern\] conflicts with new value \[EET\]" ) + msg = r"cannot match existing table structure for \[A,B\] on appending data" with pytest.raises(ValueError, match=msg): store.append("df_tz", df) @@ -214,6 +216,7 @@ def test_append_with_timezones_pytz(setup_path): index=range(5), ) + # TODO: can we share this with other similar tests? msg = ( r"invalid info for \[B\] for \[tz\], " r"existing_value \[EET\] conflicts with new value \[CET\]" diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py index 320179c0a8b0a..37af46cdb1f51 100644 --- a/pandas/tests/series/methods/test_isin.py +++ b/pandas/tests/series/methods/test_isin.py @@ -59,7 +59,7 @@ def test_isin_with_i8(self): tm.assert_series_equal(result, expected) # fails on dtype conversion in the first place - result = s.isin(s[0:2].values.astype("datetime64[D]")) + result = s.isin(np.asarray(s[0:2]).astype("datetime64[D]")) tm.assert_series_equal(result, expected) result = s.isin([s[1]]) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 1daeee8645f2e..bdf76d7c5b0a4 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1313,12 +1313,12 @@ def test_constructor_dtype_timedelta64(self): # td.astype('m8[%s]' % t) # valid astype - with tm.assert_produces_warning(FutureWarning): + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): # astype(int64) deprecated td.astype("int64") # invalid casting - msg = r"cannot astype a timedelta from \[timedelta64\[ns\]\] to \[int32\]" + msg = r"cannot astype a datetimelike from \[timedelta64\[ns\]\] to \[int32\]" with pytest.raises(TypeError, match=msg): td.astype("int32")
Remaining kludges in pytables and nanargminmax
https://api.github.com/repos/pandas-dev/pandas/pulls/39855
2021-02-17T02:34:51Z
2021-02-17T03:04:59Z
null
2021-02-17T03:04:59Z
PERF: is_list_like
diff --git a/asv_bench/benchmarks/libs.py b/asv_bench/benchmarks/libs.py new file mode 100644 index 0000000000000..f5c2397945cea --- /dev/null +++ b/asv_bench/benchmarks/libs.py @@ -0,0 +1,42 @@ +""" +Benchmarks for code in pandas/_libs, excluding pandas/_libs/tslibs, +which has its own directory +""" +import numpy as np + +from pandas._libs.lib import ( + is_list_like, + is_scalar, +) + +from pandas import ( + NA, + NaT, +) + +# TODO: share with something in pd._testing? +scalars = [ + 0, + 1.0, + 1 + 2j, + True, + "foo", + b"bar", + None, + np.datetime64(123, "ns"), + np.timedelta64(123, "ns"), + NaT, + NA, +] +zero_dims = [np.array("123")] +listlikes = [np.array([1, 2, 3]), {0: 1}, {1, 2, 3}, [1, 2, 3], (1, 2, 3)] + + +class ScalarListLike: + params = scalars + zero_dims + listlikes + + def time_is_list_like(self, param): + is_list_like(param) + + def time_is_scalar(self, param): + is_scalar(param) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 3a64ecb7a8a18..9f2c82d760785 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1059,11 +1059,12 @@ def is_list_like(obj: object, allow_sets: bool = True) -> bool: cdef inline bint c_is_list_like(object obj, bint allow_sets) except -1: return ( - isinstance(obj, abc.Iterable) + # equiv: `isinstance(obj, abc.Iterable)` + hasattr(obj, "__iter__") and not isinstance(obj, type) # we do not count strings/unicode/bytes as list-like and not isinstance(obj, (str, bytes)) # exclude zero-dimensional numpy arrays, effectively scalars - and not (util.is_array(obj) and obj.ndim == 0) + and not cnp.PyArray_IsZeroDim(obj) # exclude sets if allow_sets is False and not (allow_sets is False and isinstance(obj, abc.Set)) )
``` In [3]: arr = np.array(0) In [4]: arr2 = np.array([0]) In [5]: %timeit is_list_like([]) 118 ns ± 2.21 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR 328 ns ± 3.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master In [6]: %timeit is_list_like(0) 271 ns ± 5.65 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- PR 348 ns ± 4.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master In [7]: %timeit is_list_like(arr) 111 ns ± 1.71 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR 369 ns ± 24.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master In [8]: %timeit is_list_like(arr2) 109 ns ± 3.39 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) # <-- PR 340 ns ± 1.91 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) # <-- master ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39852
2021-02-16T22:38:04Z
2021-02-17T20:11:52Z
2021-02-17T20:11:52Z
2021-02-17T21:01:57Z
DOC: Add list of UDF methods to mutation gotcha
diff --git a/doc/source/user_guide/gotchas.rst b/doc/source/user_guide/gotchas.rst index 4089f9523724f..180f833a2753d 100644 --- a/doc/source/user_guide/gotchas.rst +++ b/doc/source/user_guide/gotchas.rst @@ -183,6 +183,9 @@ testing for membership in the list of column names. Mutating with User Defined Function (UDF) methods ------------------------------------------------- +This section applies to pandas methods that take a UDF. In particular, the methods +``.apply``, ``.aggregate``, ``.transform``, and ``.filter``. + It is a general rule in programming that one should not mutate a container while it is being iterated over. Mutation will invalidate the iterator, causing unexpected behavior. Consider the example: @@ -246,7 +249,6 @@ not apply to the container being iterated over. df = pd.DataFrame({"a": [1, 2, 3], 'b': [4, 5, 6]}) df.apply(f, axis="columns") - ``NaN``, Integer ``NA`` values and ``NA`` type promotions ---------------------------------------------------------
- [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them Ref: https://github.com/pandas-dev/pandas/pull/39762#discussion_r575832330
https://api.github.com/repos/pandas-dev/pandas/pulls/39851
2021-02-16T22:16:34Z
2021-02-16T23:35:09Z
2021-02-16T23:35:09Z
2021-02-17T22:16:26Z
solved raise an error on redundant definition (#39823)
diff --git a/doc/source/_static/spreadsheets/group-by.png b/doc/source/_static/spreadsheets/group-by.png new file mode 100644 index 0000000000000..984d4e55df33d Binary files /dev/null and b/doc/source/_static/spreadsheets/group-by.png differ diff --git a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst index 55f999c099e23..32b793374286f 100644 --- a/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst +++ b/doc/source/getting_started/comparison/comparison_with_spreadsheets.rst @@ -365,6 +365,48 @@ In Excel, there are `merging of tables can be done through a VLOOKUP * It will include all columns from the lookup table, instead of just a single specified column * It supports :ref:`more complex join operations <merging.join>` +GroupBy +-------------------- + +In Excel, this can be done by using the Query Editor. +You can group the values in various rows into a single value by grouping the rows according to the values in one or more columns +Then using the Query Editor ribbon, Right-click the column header that you want to group on, +and click `Group By <https://support.microsoft.com/en-us/office/group-rows-in-a-table-power-query-e1b9e916-6fcc-40bf-a6e8-ef928240adf1>`_. + +Power Query has two types of Group By operations: + +* Aggregate a column with an aggregate function +* Perform a row operation + +To aggregate a column, select the column to perform the Aggregate Operation on from the Column drop-down. +A Row Operation does not require a Column, since data is grouped based on table rows. + +.. image:: ../../_static/spreadsheets/group-by.png + +The equivalent in pandas: +We can use the `Group By <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html>`_ operation. +For example - + +.. ipython:: python + + df = pd.DataFrame( + [ + ("bird", "Falconiformes", 389.0), + ("bird", "Psittaciformes", 24.0), + ("mammal", "Carnivora", 80.2), + ("mammal", "Primates", np.nan), + ("mammal", "Carnivora", 58), + ], + index=["falcon", "parrot", "lion", "monkey", "leopard"], + columns=("class", "order", "max_speed"), + ) + df + + # default is axis=0 + grouped = df.groupby("class") + grouped = df.groupby("order", axis="columns") + grouped = df.groupby(["class", "order"]) + Other considerations -------------------- diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index edfc7ee0b6258..6d3b268da5348 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -1218,10 +1218,15 @@ def _refine_defaults_read( # Alias sep -> delimiter. if delimiter is None: delimiter = sep + elif sep and (delimiter is not lib.no_default): + raise ValueError( + "Specified both delimiter and " + "sep; you can only specify one." + ) if delim_whitespace and (delimiter is not lib.no_default): raise ValueError( - "Specified a delimiter with both sep and " + "Specified a delimiter with both delimiter and " "delim_whitespace=True; you can only specify one." )
- [ ] closes #39823 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39849
2021-02-16T21:19:22Z
2021-02-22T06:09:35Z
null
2021-02-22T06:09:35Z
ASV: add frame ops benchmarks for varying n_rows/n_columns ratios
diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index 7478efbf22609..ff049e61d02cf 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -110,16 +110,26 @@ class FrameWithFrameWide: operator.add, operator.floordiv, operator.gt, - ] + ], + [ + # (n_rows, n_columns) + (1_000_000, 10), + (100_000, 100), + (10_000, 1000), + (1000, 10_000), + ], ] - param_names = ["op"] + param_names = ["op", "shape"] - def setup(self, op): + def setup(self, op, shape): # we choose dtypes so as to make the blocks # a) not perfectly match between right and left # b) appreciably bigger than single columns - n_cols = 2000 - n_rows = 500 + n_rows, n_cols = shape + + if op is operator.floordiv: + # floordiv is much slower than the other operations -> use less data + n_rows = n_rows // 10 # construct dataframe with 2 blocks arr1 = np.random.randn(n_rows, n_cols // 2).astype("f8") @@ -131,7 +141,7 @@ def setup(self, op): df._consolidate_inplace() # TODO: GH#33198 the setting here shoudlnt need two steps - arr1 = np.random.randn(n_rows, n_cols // 4).astype("f8") + arr1 = np.random.randn(n_rows, max(n_cols // 4, 3)).astype("f8") arr2 = np.random.randn(n_rows, n_cols // 2).astype("i8") arr3 = np.random.randn(n_rows, n_cols // 4).astype("f8") df2 = pd.concat( @@ -145,11 +155,11 @@ def setup(self, op): self.left = df self.right = df2 - def time_op_different_blocks(self, op): + def time_op_different_blocks(self, op, shape): # blocks (and dtypes) are not aligned op(self.left, self.right) - def time_op_same_blocks(self, op): + def time_op_same_blocks(self, op, shape): # blocks (and dtypes) are aligned op(self.left, self.left)
Currently, we have a benchmark for frame/frame ops with a wide dataframe (originating from previous (long) PR / discussion about this, xref https://github.com/pandas-dev/pandas/pull/32779) To get a better idea of the trade-offs for future changes to the ops code (eg ArrayManager related), I think it is useful to have this benchmark for a varying rows/columns ratio (it is mostly this ratio that determines how much overhead we have when performing ops column-wise). So I changed the benchmark to be parametrized over 4 different ratios, from a long to a wide dataframe, and with each case having the same number of total elements in the dataframe. The shape in the original benchmark was `(500, 2000)`, which is somewhere in between two new cases of `(10_000, 1000)` and `(1000, 10_000)`, so that should preserve the original intent of the benchmark (the last case of `(1000, 10_000)` even has a lower row/column ratio, so should even be a "worse" case for the column-wise ops perspective). cc @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/39848
2021-02-16T19:54:43Z
2021-02-17T21:34:38Z
2021-02-17T21:34:38Z
2021-02-17T21:34:38Z
ASV: add benchmarks for groupby cython aggregations
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 806cf38ad90b6..fb08c6fdeaedf 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -461,6 +461,29 @@ def time_dtype_as_field(self, dtype, method, application): self.as_field_method() +class GroupByCythonAgg: + """ + Benchmarks specifically targetting our cython aggregation algorithms + (using a big enough dataframe with simple key, so a large part of the + time is actually spent in the grouped aggregation). + """ + + param_names = ["dtype", "method"] + params = [ + ["float64"], + ["sum", "prod", "min", "max", "mean", "median", "var", "first", "last"], + ] + + def setup(self, dtype, method): + N = 1_000_000 + df = DataFrame(np.random.randn(N, 10), columns=list("abcdefghij")) + df["key"] = np.random.randint(0, 100, size=N) + self.df = df + + def time_frame_agg(self, dtype, method): + self.df.groupby("key").agg(method) + + class RankWithTies: # GH 21237 param_names = ["dtype", "tie_method"]
I noticed that we currently don't really have a groupby benchmark that specifically targets the cython aggregations. We have of course benchmarks that call those, but eg `GroupByMethods` is setup in such a way that it's mostly benchmarking the factorization and post-processing (also useful of course), while eg for sum only 7% is spent in the actual `groupby_add` algorithm. So therefore this PR is adding an additional benchmark more targetted at the cython aggregation (where 30-50% of the time is spent in the actual aggregation function, so we will more easily catch regressions/improvements there) For now I only added "float64". I could also add "float32", but not sure how useful that is (since they are all using fused types, it's the same implementation for both dtypes.
https://api.github.com/repos/pandas-dev/pandas/pulls/39846
2021-02-16T16:48:43Z
2021-02-16T23:58:27Z
2021-02-16T23:58:27Z
2021-02-17T10:16:26Z
Backport PR #39795 on branch 1.2.x (fix benchmark failure with numpy 1.20+)
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 9f3689779d056..2a239204e4c01 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -2,6 +2,8 @@ import numpy as np +from pandas.compat.numpy import np_version_under1p20 + from pandas import Categorical, NaT, Series, date_range from .pandas_vb_common import tm @@ -122,6 +124,10 @@ class IsInLongSeriesLookUpDominates: def setup(self, dtype, MaxNumber, series_type): N = 10 ** 7 + + if not np_version_under1p20 and dtype in ("Int64", "Float64"): + raise NotImplementedError + if series_type == "random_hits": np.random.seed(42) array = np.random.randint(0, MaxNumber, N)
Backport PR #39795: fix benchmark failure with numpy 1.20+
https://api.github.com/repos/pandas-dev/pandas/pulls/39842
2021-02-16T13:53:12Z
2021-02-16T15:34:26Z
null
2021-02-16T15:34:26Z
[ArrayManager] Implement concat with axis=1 (merge/join)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a07149fe8171..461363d295f6a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -154,6 +154,7 @@ jobs: source activate pandas-dev pytest pandas/tests/frame/methods --array-manager pytest pandas/tests/arithmetic/ --array-manager + pytest pandas/tests/reshape/merge --array-manager # indexing subset (temporary since other tests don't pass yet) pytest pandas/tests/frame/indexing/test_indexing.py::TestDataFrameIndexing::test_setitem_boolean --array-manager diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index 132598e03d6c0..054ce8a40288b 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -12,7 +12,7 @@ TimeDeltaBlock, make_block, ) -from pandas.core.internals.concat import concatenate_block_managers +from pandas.core.internals.concat import concatenate_managers from pandas.core.internals.managers import ( BlockManager, SingleBlockManager, @@ -35,7 +35,7 @@ "ArrayManager", "BlockManager", "SingleBlockManager", - "concatenate_block_managers", + "concatenate_managers", # those two are preserved here for downstream compatibility (GH-33892) "create_block_manager_from_arrays", "create_block_manager_from_blocks", diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index e09a434170780..d38d278e89a67 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -831,7 +831,7 @@ def _reindex_indexer( new_axes = list(self._axes) new_axes[axis] = new_axis - return type(self)(new_arrays, new_axes) + return type(self)(new_arrays, new_axes, do_integrity_check=False) def take(self, indexer, axis: int = 1, verify: bool = True, convert: bool = True): """ diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 16440f7a4c2bf..362f2fde47e0b 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -49,7 +49,46 @@ from pandas import Index -def concatenate_block_managers( +def concatenate_array_managers( + mgrs_indexers, axes: List[Index], concat_axis: int, copy: bool +) -> Manager: + """ + Concatenate array managers into one. + + Parameters + ---------- + mgrs_indexers : list of (ArrayManager, {axis: indexer,...}) tuples + axes : list of Index + concat_axis : int + copy : bool + + Returns + ------- + ArrayManager + """ + # reindex all arrays + mgrs = [] + for mgr, indexers in mgrs_indexers: + for ax, indexer in indexers.items(): + mgr = mgr.reindex_indexer(axes[ax], indexer, axis=ax, allow_dups=True) + mgrs.append(mgr) + + if concat_axis == 1: + # concatting along the rows -> concat the reindexed arrays + # TODO(ArrayManager) doesn't yet preserve the correct dtype + arrays = [ + concat_compat([mgrs[i].arrays[j] for i in range(len(mgrs))]) + for j in range(len(mgrs[0].arrays)) + ] + return ArrayManager(arrays, [axes[1], axes[0]], do_integrity_check=False) + else: + # concatting along the columns -> combine reindexed arrays in a single manager + assert concat_axis == 0 + arrays = list(itertools.chain.from_iterable([mgr.arrays for mgr in mgrs])) + return ArrayManager(arrays, [axes[1], axes[0]], do_integrity_check=False) + + +def concatenate_managers( mgrs_indexers, axes: List[Index], concat_axis: int, copy: bool ) -> Manager: """ @@ -66,20 +105,9 @@ def concatenate_block_managers( ------- BlockManager """ + # TODO(ArrayManager) this assumes that all managers are of the same type 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]]) + return concatenate_array_managers(mgrs_indexers, axes, concat_axis, copy) concat_plans = [ _get_mgr_concatenation_plan(mgr, indexers) for mgr, indexers in mgrs_indexers diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 9c536abbc7559..86df773147e21 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -282,6 +282,18 @@ def get_dtypes(self): dtypes = np.array([blk.dtype for blk in self.blocks]) return algos.take_nd(dtypes, self.blknos, allow_fill=False) + @property + def arrays(self): + """ + Quick access to the backing arrays of the Blocks. + + Only for compatibility with ArrayManager for testing convenience. + Not to be used in actual code, and return value is not the same as the + ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs). + """ + for blk in self.blocks: + yield blk.values + def __getstate__(self): block_values = [b.values for b in self.blocks] block_items = [self.items[b.mgr_locs.indexer] for b in self.blocks] diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 92fc4a2e85163..a8c6913cd5d6c 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -43,7 +43,7 @@ get_unanimous_names, ) import pandas.core.indexes.base as ibase -from pandas.core.internals import concatenate_block_managers +from pandas.core.internals import concatenate_managers if TYPE_CHECKING: from pandas import ( @@ -524,7 +524,7 @@ def get_result(self): mgrs_indexers.append((obj._mgr, indexers)) - new_data = concatenate_block_managers( + new_data = concatenate_managers( mgrs_indexers, self.new_axes, concat_axis=self.bm_axis, copy=self.copy ) if not self.copy: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 79d018427aa33..217d9915f834c 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -76,7 +76,7 @@ import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.frame import _merge_doc -from pandas.core.internals import concatenate_block_managers +from pandas.core.internals import concatenate_managers from pandas.core.sorting import is_int64_overflow_possible if TYPE_CHECKING: @@ -720,7 +720,7 @@ def get_result(self): lindexers = {1: left_indexer} if left_indexer is not None else {} rindexers = {1: right_indexer} if right_indexer is not None else {} - result_data = concatenate_block_managers( + result_data = concatenate_managers( [(self.left._mgr, lindexers), (self.right._mgr, rindexers)], axes=[llabels.append(rlabels), join_index], concat_axis=0, @@ -1616,7 +1616,7 @@ def get_result(self): lindexers = {1: left_join_indexer} if left_join_indexer is not None else {} rindexers = {1: right_join_indexer} if right_join_indexer is not None else {} - result_data = concatenate_block_managers( + result_data = concatenate_managers( [(self.left._mgr, lindexers), (self.right._mgr, rindexers)], axes=[llabels.append(rlabels), join_index], concat_axis=0, diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index dc9a1565aad1e..0f51c4aef79db 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -161,7 +161,7 @@ def test_drop(self): assert return_value is None tm.assert_frame_equal(df, expected) - @td.skip_array_manager_not_yet_implemented + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_drop_multiindex_not_lexsorted(self): # GH#11640 diff --git a/pandas/tests/frame/methods/test_explode.py b/pandas/tests/frame/methods/test_explode.py index be80dd49ff1fb..bd0901387eeed 100644 --- a/pandas/tests/frame/methods/test_explode.py +++ b/pandas/tests/frame/methods/test_explode.py @@ -1,14 +1,9 @@ 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_join.py b/pandas/tests/frame/methods/test_join.py index 90456ad949f59..1c7f7e3ff674a 100644 --- a/pandas/tests/frame/methods/test_join.py +++ b/pandas/tests/frame/methods/test_join.py @@ -3,8 +3,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import ( DataFrame, @@ -15,9 +13,6 @@ ) 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(): @@ -240,8 +235,9 @@ def test_join(self, multiindex_dataframe_random_data): b = frame.loc[frame.index[2:], ["B", "C"]] joined = a.join(b, how="outer").reindex(frame.index) - expected = frame.copy() - expected.values[np.isnan(joined.values)] = np.nan + expected = frame.copy().values + expected[np.isnan(joined.values)] = np.nan + expected = DataFrame(expected, index=frame.index, columns=frame.columns) assert not np.isnan(joined.values).all() diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index 2339e21288bb5..24d1973eeda6d 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -121,7 +121,7 @@ def test_ambiguous_width(self): assert adjoined == expected -@td.skip_array_manager_not_yet_implemented +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) JSON class TestTableSchemaRepr: @classmethod def setup_class(cls): diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index d9575a6ad81e5..3131131682ccd 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -247,7 +247,7 @@ def test_pickle_options(fsspectest): tm.assert_frame_equal(df, out) -@td.skip_array_manager_not_yet_implemented +@td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) JSON def test_json_options(fsspectest): df = DataFrame({"a": [0]}) df.to_json("testmem://afile", storage_options={"test": "json_write"}) diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index e5499c44be7d7..2ec94d4cebf5a 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.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 ( Categorical, @@ -551,6 +553,7 @@ def test_join_non_unique_period_index(self): ) tm.assert_frame_equal(result, expected) + @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) groupby def test_mixed_type_join_with_suffix(self): # GH #916 df = DataFrame(np.random.randn(20, 6), columns=["a", "b", "c", "d", "e", "f"]) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index d9af59382ae79..e1b1e80a29a43 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -287,17 +287,27 @@ def test_merge_copy(self): merged["d"] = "peekaboo" assert (right["d"] == "bar").all() - def test_merge_nocopy(self): + def test_merge_nocopy(self, using_array_manager): left = DataFrame({"a": 0, "b": 1}, index=range(10)) right = DataFrame({"c": "foo", "d": "bar"}, index=range(10)) merged = merge(left, right, left_index=True, right_index=True, copy=False) - merged["a"] = 6 - assert (left["a"] == 6).all() + if using_array_manager: + # With ArrayManager, setting a column doesn't change the values inplace + # and thus does not propagate the changes to the original left/right + # dataframes -> need to check that no copy was made in a different way + # TODO(ArrayManager) we should be able to simplify this with a .loc + # setitem test: merged.loc[0, "a"] = 10; assert left.loc[0, "a"] == 10 + # but this currently replaces the array (_setitem_with_indexer_split_path) + assert merged._mgr.arrays[0] is left._mgr.arrays[0] + assert merged._mgr.arrays[2] is right._mgr.arrays[0] + else: + merged["a"] = 6 + assert (left["a"] == 6).all() - merged["d"] = "peekaboo" - assert (right["d"] == "peekaboo").all() + merged["d"] = "peekaboo" + assert (right["d"] == "peekaboo").all() def test_intelligently_handle_join_key(self): # #733, be a bit more 1337 about not returning unconsolidated DataFrame @@ -1381,7 +1391,10 @@ def test_merge_readonly(self): np.arange(20).reshape((5, 4)) + 1, columns=["a", "b", "x", "y"] ) - data1._mgr.blocks[0].values.flags.writeable = False + # make each underlying block array / column array read-only + for arr in data1._mgr.arrays: + arr.flags.writeable = False + data1.merge(data2) # no error
The (hopefully) "easy" part of https://github.com/pandas-dev/pandas/pull/39612 for which there seems less discussion: this separates the pieces from https://github.com/pandas-dev/pandas/pull/39612 that are needed to get `concat` with `axis=1` working (`concat_axis=0`), which at least enables the join / merge usecases.
https://api.github.com/repos/pandas-dev/pandas/pulls/39841
2021-02-16T12:10:09Z
2021-02-23T10:13:44Z
2021-02-23T10:13:44Z
2021-02-23T21:21:51Z
TST: JSON with tz roundtrip
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index e25964f556e4e..94931f9635075 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -759,8 +759,7 @@ def test_comprehensive(self): "E": pd.Series(pd.Categorical(["a", "b", "c", "c"])), "F": pd.Series(pd.Categorical(["a", "b", "c", "c"], ordered=True)), "G": [1.1, 2.2, 3.3, 4.4], - # 'H': pd.date_range('2016-01-01', freq='d', periods=4, - # tz='US/Central'), + "H": pd.date_range("2016-01-01", freq="d", periods=4, tz="US/Central"), "I": [True, False, False, True], }, index=pd.Index(range(4), name="idx"),
test was ignored previously cause `tz` not supported. was fixed by PR #35973 might as well include the test now.
https://api.github.com/repos/pandas-dev/pandas/pulls/39840
2021-02-16T10:55:40Z
2021-02-16T13:51:36Z
2021-02-16T13:51:36Z
2021-02-16T18:03:40Z
CI: remove stale assignments
diff --git a/.github/workflows/assign.yml b/.github/workflows/assign.yml index a6d3f1f383751..98748ab3f2357 100644 --- a/.github/workflows/assign.yml +++ b/.github/workflows/assign.yml @@ -1,3 +1,4 @@ +# deprecated in favor of /assign name: Assign on: issue_comment: diff --git a/.github/workflows/slash_assign.yml b/.github/workflows/slash_assign.yml new file mode 100644 index 0000000000000..b08d6ebc63e70 --- /dev/null +++ b/.github/workflows/slash_assign.yml @@ -0,0 +1,32 @@ +# https://github.com/JasonEtco/slash-assign-action#usage +name: Slash assign + +on: + schedule: + - cron: 0 0 * * * + issue_comment: + types: [created] + +jobs: + slash_assign: + if: > + (github.event_name == 'issue_comment' && startsWith(github.event.comment.body, '/assign')) || + github.event_name == 'schedule' + runs-on: ubuntu-latest + steps: + # not yet published + # https://github.com/JasonEtco/slash-assign-action/issues/1 + - name: Check out GitHub Action + uses: actions/checkout@v2 + with: + repository: JasonEtco/slash-assign-action + ref: 842404647dfd10109c8c4feb3e776807eb5e2071 + path: .github/actions/slash-assign-action + - name: Compile the Action + run: | + npm install + npm run build + working-directory: .github/actions/slash-assign-action + + - name: Assign the user or unassign stale assignments + uses: ./.github/actions/slash-assign-action diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index f3630a44d29cd..7d7ffffdf2045 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -31,13 +31,13 @@ comment letting others know they are working on an issue. While this is ok, you check each issue individually, and it's not possible to find the unassigned ones. For this reason, we implemented a workaround consisting of adding a comment with the exact -text ``take``. When you do it, a GitHub action will automatically assign you the issue +text ``/assign``. When you do it, a GitHub action will automatically assign you the issue (this will take seconds, and may require refreshing the page to see it). By doing this, it's possible to filter the list of issues and find only the unassigned ones. So, a good way to find an issue to start contributing to pandas is to check the list of `unassigned good first issues <https://github.com/pandas-dev/pandas/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22+no%3Aassignee>`_ -and assign yourself one you like by writing a comment with the exact text ``take``. +and assign yourself one you like by writing a comment with the exact text ``/assign``. If for whatever reason you are not able to continue working with the issue, please try to unassign it, so other people know it's available again. You can check the list of
Use a third-party GitHub Action to handle the claiming of issues. [See it in action.](https://github.com/afeld/pandas/issues/2#issuecomment-779635007) It also handles automatically unassigning them after a period of inactivity, which is the more interesting part. The motivation here is that I bet there are a lot of issues where someone has used `take`, but the issue remains open without movement. [By default](https://github.com/JasonEtco/slash-assign-action#options), this Action will remove the assignment after 21 days. Open to suggestions about whether that should be longer or shorter. - [ ] ~~closes #xxxx~~ - [ ] ~~tests added / passed~~ - [ ] ~~Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them~~ - [ ] ~~whatsnew entry~~
https://api.github.com/repos/pandas-dev/pandas/pulls/39836
2021-02-16T07:19:15Z
2021-06-18T01:36:13Z
null
2021-06-18T01:36:13Z
TST/REF: collect tests by method
diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index fc4809d333e57..4da9ed76844af 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1146,7 +1146,8 @@ def test_setitem_frame_mixed(self, float_string_frame): f.loc[key] = piece tm.assert_almost_equal(f.loc[f.index[0:2], ["A", "B"]].values, piece.values) - # rows unaligned + def test_setitem_frame_mixed_rows_unaligned(self, float_string_frame): + # GH#3216 rows unaligned f = float_string_frame.copy() piece = DataFrame( [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]], @@ -1159,7 +1160,8 @@ def test_setitem_frame_mixed(self, float_string_frame): f.loc[f.index[0:2:], ["A", "B"]].values, piece.values[0:2] ) - # key is unaligned with values + def test_setitem_frame_mixed_key_unaligned(self, float_string_frame): + # GH#3216 key is unaligned with values f = float_string_frame.copy() piece = f.loc[f.index[:2], ["A"]] piece.index = f.index[-2:] @@ -1168,7 +1170,8 @@ def test_setitem_frame_mixed(self, float_string_frame): piece["B"] = np.nan tm.assert_almost_equal(f.loc[f.index[-2:], ["A", "B"]].values, piece.values) - # ndarray + def test_setitem_frame_mixed_ndarray(self, float_string_frame): + # GH#3216 ndarray f = float_string_frame.copy() piece = float_string_frame.loc[f.index[:2], ["A", "B"]] key = (f.index[slice(-2, None)], ["A", "B"]) @@ -1471,7 +1474,7 @@ def test_loc_setitem_datetimeindex_tz(self, idxer, tz_naive_fixture): result.loc[:, idxer] = expected tm.assert_frame_equal(result, expected) - def test_at_time_between_time_datetimeindex(self): + def test_loc_setitem_time_key(self): index = date_range("2012-01-01", "2012-01-05", freq="30min") df = DataFrame(np.random.randn(len(index), 5), index=index) akey = time(12, 0, 0) @@ -1479,20 +1482,6 @@ def test_at_time_between_time_datetimeindex(self): ainds = [24, 72, 120, 168] binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172] - result = df.at_time(akey) - expected = df.loc[akey] - expected2 = df.iloc[ainds] - tm.assert_frame_equal(result, expected) - tm.assert_frame_equal(result, expected2) - assert len(result) == 4 - - result = df.between_time(bkey.start, bkey.stop) - expected = df.loc[bkey] - expected2 = df.iloc[binds] - tm.assert_frame_equal(result, expected) - tm.assert_frame_equal(result, expected2) - assert len(result) == 12 - result = df.copy() result.loc[akey] = 0 result = result.loc[akey] @@ -1529,26 +1518,11 @@ def test_loc_getitem_index_namedtuple(self): result = df.loc[IndexType("foo", "bar")]["A"] assert result == 1 - @pytest.mark.parametrize( - "tpl", - [ - (1,), - ( - 1, - 2, - ), - ], - ) + @pytest.mark.parametrize("tpl", [(1,), (1, 2)]) def test_loc_getitem_index_single_double_tuples(self, tpl): # GH 20991 idx = Index( - [ - (1,), - ( - 1, - 2, - ), - ], + [(1,), (1, 2)], name="A", tupleize_cols=False, ) diff --git a/pandas/tests/frame/methods/test_at_time.py b/pandas/tests/frame/methods/test_at_time.py index e9ac4336701a3..2d05176d20f5f 100644 --- a/pandas/tests/frame/methods/test_at_time.py +++ b/pandas/tests/frame/methods/test_at_time.py @@ -113,3 +113,16 @@ def test_at_time_axis(self, axis): result.index = result.index._with_freq(None) expected.index = expected.index._with_freq(None) tm.assert_frame_equal(result, expected) + + def test_at_time_datetimeindex(self): + index = date_range("2012-01-01", "2012-01-05", freq="30min") + df = DataFrame(np.random.randn(len(index), 5), index=index) + akey = time(12, 0, 0) + ainds = [24, 72, 120, 168] + + result = df.at_time(akey) + expected = df.loc[akey] + expected2 = df.iloc[ainds] + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected2) + assert len(result) == 4 diff --git a/pandas/tests/frame/methods/test_between_time.py b/pandas/tests/frame/methods/test_between_time.py index 073368019e0f5..0daa267767269 100644 --- a/pandas/tests/frame/methods/test_between_time.py +++ b/pandas/tests/frame/methods/test_between_time.py @@ -194,3 +194,16 @@ def test_between_time_axis_raises(self, axis): ts.columns = mask with pytest.raises(TypeError, match=msg): ts.between_time(stime, etime, axis=1) + + def test_between_time_datetimeindex(self): + index = date_range("2012-01-01", "2012-01-05", freq="30min") + df = DataFrame(np.random.randn(len(index), 5), index=index) + bkey = slice(time(13, 0, 0), time(14, 0, 0)) + binds = [26, 27, 28, 74, 75, 76, 122, 123, 124, 170, 171, 172] + + result = df.between_time(bkey.start, bkey.stop) + expected = df.loc[bkey] + expected2 = df.iloc[binds] + tm.assert_frame_equal(result, expected) + tm.assert_frame_equal(result, expected2) + assert len(result) == 12 diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index 4bc45e3abca32..113e870c8879b 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -391,3 +391,14 @@ def test_describe_when_include_all_exclude_not_allowed(self, exclude): msg = "exclude must be None when include is 'all'" with pytest.raises(ValueError, match=msg): df.describe(include="all", exclude=exclude) + + def test_describe_with_duplicate_columns(self): + df = DataFrame( + [[1, 1, 1], [2, 2, 2], [3, 3, 3]], + columns=["bar", "a", "a"], + dtype="float64", + ) + result = df.describe() + ser = df.iloc[:, 0].describe() + expected = pd.concat([ser, ser, ser], keys=df.columns, axis=1) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 6749865367399..f92899740f95f 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -457,3 +457,13 @@ def test_drop_with_non_unique_multiindex(self): result = df.drop(index="x") expected = DataFrame([2], index=MultiIndex.from_arrays([["y"], ["j"]])) tm.assert_frame_equal(result, expected) + + def test_drop_with_duplicate_columns(self): + df = DataFrame( + [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] + ) + result = df.drop(["a"], axis=1) + expected = DataFrame([[1], [1], [1]], columns=["bar"]) + tm.assert_frame_equal(result, expected) + result = df.drop("a", axis=1) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index 128942cd64926..8a3ac265db154 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -644,6 +644,18 @@ def test_reindex_dups(self): with pytest.raises(ValueError, match=msg): df.reindex(index=list(range(len(df)))) + def test_reindex_with_duplicate_columns(self): + + # reindex is invalid! + df = DataFrame( + [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] + ) + msg = "cannot reindex from a duplicate axis" + with pytest.raises(ValueError, match=msg): + df.reindex(columns=["bar"]) + with pytest.raises(ValueError, match=msg): + df.reindex(columns=["bar", "foo"]) + def test_reindex_axis_style(self): # https://github.com/pandas-dev/pandas/issues/12392 df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) diff --git a/pandas/tests/frame/methods/test_rename.py b/pandas/tests/frame/methods/test_rename.py index 10ed862225c01..677d862dfe077 100644 --- a/pandas/tests/frame/methods/test_rename.py +++ b/pandas/tests/frame/methods/test_rename.py @@ -4,11 +4,14 @@ import numpy as np import pytest +import pandas.util._test_decorators as td + from pandas import ( DataFrame, Index, MultiIndex, Series, + merge, ) import pandas._testing as tm @@ -357,3 +360,45 @@ def test_rename_mapper_and_positional_arguments_raises(self): with pytest.raises(TypeError, match=msg): df.rename({}, columns={}, index={}) + + @td.skip_array_manager_not_yet_implemented + def test_rename_with_duplicate_columns(self): + # GH#4403 + df4 = DataFrame( + {"RT": [0.0454], "TClose": [22.02], "TExg": [0.0422]}, + index=MultiIndex.from_tuples( + [(600809, 20130331)], names=["STK_ID", "RPT_Date"] + ), + ) + + df5 = DataFrame( + { + "RPT_Date": [20120930, 20121231, 20130331], + "STK_ID": [600809] * 3, + "STK_Name": ["饡驦", "饡驦", "饡驦"], + "TClose": [38.05, 41.66, 30.01], + }, + index=MultiIndex.from_tuples( + [(600809, 20120930), (600809, 20121231), (600809, 20130331)], + names=["STK_ID", "RPT_Date"], + ), + ) + # TODO: can we construct this without merge? + k = merge(df4, df5, how="inner", left_index=True, right_index=True) + result = k.rename(columns={"TClose_x": "TClose", "TClose_y": "QT_Close"}) + str(result) + result.dtypes + + expected = DataFrame( + [[0.0454, 22.02, 0.0422, 20130331, 600809, "饡驦", 30.01]], + columns=[ + "RT", + "TClose", + "TExg", + "RPT_Date", + "STK_ID", + "STK_Name", + "QT_Close", + ], + ).set_index(["STK_ID", "RPT_Date"], drop=False) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py index 94ea369d26b97..38e58860959b8 100644 --- a/pandas/tests/frame/methods/test_values.py +++ b/pandas/tests/frame/methods/test_values.py @@ -55,6 +55,12 @@ def test_values_duplicates(self): tm.assert_numpy_array_equal(result, expected) + def test_values_with_duplicate_columns(self): + df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"]) + result = df.values + expected = np.array([[1, 2.5], [3, 4.5]]) + assert (result == expected).all().all() + @pytest.mark.parametrize("constructor", [date_range, period_range]) def test_values_casts_datetimelike_to_object(self, constructor): series = Series(constructor("2000-01-01", periods=10, freq="D")) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 26710b1f9ed73..44b6d44ee6275 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -57,6 +57,21 @@ def any(self, axis=None): class TestFrameComparisons: # Specifically _not_ flex-comparisons + def test_comparison_with_categorical_dtype(self): + # GH#12564 + + df = DataFrame({"A": ["foo", "bar", "baz"]}) + exp = DataFrame({"A": [True, False, False]}) + + res = df == "foo" + tm.assert_frame_equal(res, exp) + + # casting to categorical shouldn't affect the result + df["A"] = df["A"].astype("category") + + res = df == "foo" + tm.assert_frame_equal(res, exp) + def test_frame_in_list(self): # GH#12689 this should raise at the DataFrame level, not blocks df = DataFrame(np.random.randn(6, 4), columns=list("ABCD")) @@ -597,6 +612,26 @@ def test_flex_add_scalar_fill_value(self): res = df.add(2, fill_value=0) tm.assert_frame_equal(res, exp) + def test_sub_alignment_with_duplicate_index(self): + # GH#5185 dup aligning operations should work + df1 = DataFrame([1, 2, 3, 4, 5], index=[1, 2, 1, 2, 3]) + df2 = DataFrame([1, 2, 3], index=[1, 2, 3]) + expected = DataFrame([0, 2, 0, 2, 2], index=[1, 1, 2, 2, 3]) + result = df1.sub(df2) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("op", ["__add__", "__mul__", "__sub__", "__truediv__"]) + def test_arithmetic_with_duplicate_columns(self, op): + # operations + df = DataFrame({"A": np.arange(10), "B": np.random.rand(10)}) + expected = getattr(df, op)(df) + expected.columns = ["A", "A"] + df.columns = ["A", "A"] + result = getattr(df, op)(df) + tm.assert_frame_equal(result, expected) + str(result) + result.dtypes + class TestFrameArithmetic: def test_td64_op_nat_casting(self): diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 3e48883232243..c3812e109b938 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -4,7 +4,6 @@ import pandas as pd from pandas import ( DataFrame, - MultiIndex, Series, date_range, ) @@ -19,7 +18,7 @@ def check(result, expected=None): class TestDataFrameNonuniqueIndexes: - def test_column_dups_operations(self): + def test_setattr_columns_vs_construct_with_columns(self): # assignment # GH 3687 @@ -30,6 +29,7 @@ def test_column_dups_operations(self): expected = DataFrame(arr, columns=idx) check(df, expected) + def test_setattr_columns_vs_construct_with_columns_datetimeindx(self): idx = date_range("20130101", periods=4, freq="Q-NOV") df = DataFrame( [[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=["a", "a", "a", "a"] @@ -162,90 +162,6 @@ def test_dup_across_dtypes(self): ) check(df, expected) - def test_values_with_duplicate_columns(self): - # values - df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"]) - result = df.values - expected = np.array([[1, 2.5], [3, 4.5]]) - assert (result == expected).all().all() - - def test_rename_with_duplicate_columns(self): - # rename, GH 4403 - df4 = DataFrame( - {"RT": [0.0454], "TClose": [22.02], "TExg": [0.0422]}, - index=MultiIndex.from_tuples( - [(600809, 20130331)], names=["STK_ID", "RPT_Date"] - ), - ) - - df5 = DataFrame( - { - "RPT_Date": [20120930, 20121231, 20130331], - "STK_ID": [600809] * 3, - "STK_Name": ["饡驦", "饡驦", "饡驦"], - "TClose": [38.05, 41.66, 30.01], - }, - index=MultiIndex.from_tuples( - [(600809, 20120930), (600809, 20121231), (600809, 20130331)], - names=["STK_ID", "RPT_Date"], - ), - ) - - k = pd.merge(df4, df5, how="inner", left_index=True, right_index=True) - result = k.rename(columns={"TClose_x": "TClose", "TClose_y": "QT_Close"}) - str(result) - result.dtypes - - expected = DataFrame( - [[0.0454, 22.02, 0.0422, 20130331, 600809, "饡驦", 30.01]], - columns=[ - "RT", - "TClose", - "TExg", - "RPT_Date", - "STK_ID", - "STK_Name", - "QT_Close", - ], - ).set_index(["STK_ID", "RPT_Date"], drop=False) - tm.assert_frame_equal(result, expected) - - def test_reindex_with_duplicate_columns(self): - - # reindex is invalid! - df = DataFrame( - [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] - ) - msg = "cannot reindex from a duplicate axis" - with pytest.raises(ValueError, match=msg): - df.reindex(columns=["bar"]) - with pytest.raises(ValueError, match=msg): - df.reindex(columns=["bar", "foo"]) - - def test_drop_with_duplicate_columns(self): - - # drop - df = DataFrame( - [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] - ) - result = df.drop(["a"], axis=1) - expected = DataFrame([[1], [1], [1]], columns=["bar"]) - check(result, expected) - result = df.drop("a", axis=1) - check(result, expected) - - def test_describe_with_duplicate_columns(self): - # describe - df = DataFrame( - [[1, 1, 1], [2, 2, 2], [3, 3, 3]], - columns=["bar", "a", "a"], - dtype="float64", - ) - result = df.describe() - s = df.iloc[:, 0].describe() - expected = pd.concat([s, s, s], keys=df.columns, axis=1) - check(result, expected) - def test_column_dups_indexes(self): # check column dups with index equal and not equal to df's index df = DataFrame( @@ -263,17 +179,6 @@ def test_column_dups_indexes(self): this_df["A"] = index check(this_df, expected_df) - def test_arithmetic_with_dups(self): - - # operations - for op in ["__add__", "__mul__", "__sub__", "__truediv__"]: - df = DataFrame({"A": np.arange(10), "B": np.random.rand(10)}) - expected = getattr(df, op)(df) - expected.columns = ["A", "A"] - df.columns = ["A", "A"] - result = getattr(df, op)(df) - check(result, expected) - def test_changing_dtypes_with_duplicate_columns(self): # multiple assignments that change dtypes # the location indexer is a slice @@ -329,16 +234,6 @@ def test_column_dups_dropna(self): result = df.dropna(subset=["A", "C"], how="all") tm.assert_frame_equal(result, expected) - def test_column_dups_indexing(self): - - # dup aligning operations should work - # GH 5185 - df1 = DataFrame([1, 2, 3, 4, 5], index=[1, 2, 1, 2, 3]) - df2 = DataFrame([1, 2, 3], index=[1, 2, 3]) - expected = DataFrame([0, 2, 0, 2, 2], index=[1, 1, 2, 2, 3]) - result = df1.sub(df2) - tm.assert_frame_equal(result, expected) - def test_dup_columns_comparisons(self): # equality df1 = DataFrame([[1, 2], [2, np.nan], [3, 4], [4, 4]], columns=["A", "B"]) diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py index 627306143788e..eaf597e6bf978 100644 --- a/pandas/tests/indexing/interval/test_interval.py +++ b/pandas/tests/indexing/interval/test_interval.py @@ -35,7 +35,7 @@ def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl): tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) @pytest.mark.parametrize("direction", ["increasing", "decreasing"]) - def test_nonoverlapping_monotonic(self, direction, closed, indexer_sl): + def test_getitem_nonoverlapping_monotonic(self, direction, closed, indexer_sl): tpls = [(0, 1), (2, 3), (4, 5)] if direction == "decreasing": tpls = tpls[::-1] @@ -60,7 +60,7 @@ def test_nonoverlapping_monotonic(self, direction, closed, indexer_sl): for key, expected in zip(idx.mid, ser): assert indexer_sl(ser)[key] == expected - def test_non_matching(self, series_with_interval_index, indexer_sl): + def test_getitem_non_matching(self, series_with_interval_index, indexer_sl): ser = series_with_interval_index.copy() # this is a departure from our current @@ -72,7 +72,7 @@ def test_non_matching(self, series_with_interval_index, indexer_sl): indexer_sl(ser)[[-1, 3]] @pytest.mark.arm_slow - def test_large_series(self): + def test_loc_getitem_large_series(self): ser = Series( np.arange(1000000), index=IntervalIndex.from_breaks(np.arange(1000001)) ) diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 3b6bc42544c51..68ae1a0dd6f3d 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -450,30 +450,16 @@ def test_loc_slice(self): def test_loc_and_at_with_categorical_index(self): # GH 20629 - s = Series([1, 2, 3], index=CategoricalIndex(["A", "B", "C"])) - assert s.loc["A"] == 1 - assert s.at["A"] == 1 df = DataFrame( [[1, 2], [3, 4], [5, 6]], index=CategoricalIndex(["A", "B", "C"]) ) - assert df.loc["B", 1] == 4 - assert df.at["B", 1] == 4 - - def test_indexing_with_category(self): - - # https://github.com/pandas-dev/pandas/issues/12564 - # consistent result if comparing as Dataframe - cat = DataFrame({"A": ["foo", "bar", "baz"]}) - exp = DataFrame({"A": [True, False, False]}) - - res = cat[["A"]] == "foo" - tm.assert_frame_equal(res, exp) - - cat["A"] = cat["A"].astype("category") + s = df[0] + assert s.loc["A"] == 1 + assert s.at["A"] == 1 - res = cat[["A"]] == "foo" - tm.assert_frame_equal(res, exp) + assert df.loc["B", 1] == 4 + assert df.at["B", 1] == 4 @pytest.mark.parametrize( "idx_values", @@ -501,7 +487,7 @@ def test_indexing_with_category(self): pd.timedelta_range(start="1d", periods=3).array, ], ) - def test_loc_with_non_string_categories(self, idx_values, ordered): + def test_loc_getitem_with_non_string_categories(self, idx_values, ordered): # GH-17569 cat_idx = CategoricalIndex(idx_values, ordered=ordered) df = DataFrame({"A": ["foo", "bar", "baz"]}, index=cat_idx) diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index 7cad0f92b06a3..28a1098c10d9f 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -25,22 +25,17 @@ def test_indexing_with_datetime_tz(self): df.iloc[1, 1] = pd.NaT df.iloc[1, 2] = pd.NaT - # indexing - result = df.iloc[1] expected = Series( [Timestamp("2013-01-02 00:00:00-0500", tz="US/Eastern"), pd.NaT, pd.NaT], index=list("ABC"), dtype="object", name=1, ) + + # indexing + result = df.iloc[1] tm.assert_series_equal(result, expected) result = df.loc[1] - expected = Series( - [Timestamp("2013-01-02 00:00:00-0500", tz="US/Eastern"), pd.NaT, pd.NaT], - index=list("ABC"), - dtype="object", - name=1, - ) tm.assert_series_equal(result, expected) def test_indexing_fast_xs(self): @@ -224,12 +219,14 @@ def test_nanosecond_getitem_setitem_with_tz(self): expected = DataFrame(-1, index=index, columns=["a"]) tm.assert_frame_equal(result, expected) - def test_loc_setitem_with_existing_dst(self): + def test_loc_setitem_with_expansion_and_existing_dst(self): # GH 18308 start = Timestamp("2017-10-29 00:00:00+0200", tz="Europe/Madrid") end = Timestamp("2017-10-29 03:00:00+0100", tz="Europe/Madrid") ts = Timestamp("2016-10-10 03:00:00", tz="Europe/Madrid") idx = pd.date_range(start, end, closed="left", freq="H") + assert ts not in idx # i.e. result.loc setitem is with-expansion + result = DataFrame(index=idx, columns=["value"]) result.loc[ts, "value"] = 12 expected = DataFrame( diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index a4a7ef0860c15..efd99df9a5e4f 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -59,6 +59,9 @@ def test_setitem_ndarray_1d(self): ) tm.assert_series_equal(result, expected) + def test_setitem_ndarray_1d_2(self): + # GH5508 + # dtype getting changed? df = DataFrame(index=Index(np.arange(1, 11))) df["foo"] = np.zeros(10, dtype=np.float64) @@ -139,7 +142,7 @@ def test_inf_upcast(self): expected = pd.Float64Index([1, 2, np.inf]) tm.assert_index_equal(result, expected) - def test_inf_upcast_empty(self): + def test_loc_setitem_with_expasnion_inf_upcast_empty(self): # Test with np.inf in columns df = DataFrame() df.loc[0, 0] = 1 @@ -293,6 +296,8 @@ def test_dups_fancy_indexing2(self): with pytest.raises(KeyError, match="with any missing labels"): df.loc[:, ["A", "B", "C"]] + def test_dups_fancy_indexing3(self): + # GH 6504, multi-axis indexing df = DataFrame( np.random.randn(9, 2), index=[1, 1, 1, 2, 2, 2, 3, 3, 3], columns=["a", "b"] @@ -506,6 +511,7 @@ def test_setitem_list(self): tm.assert_frame_equal(result, df) + def test_iloc_setitem_custom_object(self): # iloc with an object class TO: def __init__(self, value): @@ -551,6 +557,9 @@ def test_string_slice(self): with pytest.raises(KeyError, match="'2011'"): df.loc["2011", 0] + def test_string_slice_empty(self): + # GH 14424 + df = DataFrame() assert not df.index._is_all_dates with pytest.raises(KeyError, match="'2011'"): @@ -595,6 +604,7 @@ def test_astype_assignment(self): ) tm.assert_frame_equal(df, expected) + def test_astype_assignment_full_replacements(self): # full replacements / no nans df = DataFrame({"A": [1.0, 2.0, 3.0, 4.0]}) df.iloc[:, 0] = df["A"].astype(np.int64) @@ -658,9 +668,9 @@ class TestMisc: def test_float_index_to_mixed(self): df = DataFrame({0.0: np.random.rand(10), 1.0: np.random.rand(10)}) df["a"] = 10 - tm.assert_frame_equal( - DataFrame({0.0: df[0.0], 1.0: df[1.0], "a": [10] * 10}), df - ) + + expected = DataFrame({0.0: df[0.0], 1.0: df[1.0], "a": [10] * 10}) + tm.assert_frame_equal(expected, df) def test_float_index_non_scalar_assignment(self): df = DataFrame({"a": [1, 2, 3], "b": [3, 4, 5]}, index=[1.0, 2.0, 3.0]) @@ -745,12 +755,10 @@ def assert_slices_equivalent(l_slc, i_slc): assert_slices_equivalent(SLC[idx[13] : idx[9] : -1], SLC[13:8:-1]) assert_slices_equivalent(SLC[idx[9] : idx[13] : -1], SLC[:0]) - def test_slice_with_zero_step_raises(self): - s = Series(np.arange(20), index=_mklbl("A", 20)) + def test_slice_with_zero_step_raises(self, indexer_sl): + ser = Series(np.arange(20), index=_mklbl("A", 20)) with pytest.raises(ValueError, match="slice step cannot be zero"): - s[::0] - with pytest.raises(ValueError, match="slice step cannot be zero"): - s.loc[::0] + indexer_sl(ser)[::0] def test_indexing_assignment_dict_already_exists(self): index = Index([-5, 0, 5], name="z") @@ -935,7 +943,7 @@ def test_none_coercion_mixed_dtypes(self): class TestDatetimelikeCoercion: def test_setitem_dt64_string_scalar(self, tz_naive_fixture, indexer_sli): - # dispatching _can_hold_element to underling DatetimeArray + # dispatching _can_hold_element to underlying DatetimeArray tz = tz_naive_fixture dti = date_range("2016-01-01", periods=3, tz=tz) diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 740d029effc94..64d763f410666 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -15,6 +15,8 @@ timezones, ) +from pandas.core.dtypes.common import is_scalar + import pandas as pd from pandas import ( Categorical, @@ -533,3 +535,63 @@ def test_getitem_preserve_name(datetime_series): result = datetime_series[5:10] assert result.name == datetime_series.name + + +def test_getitem_with_integer_labels(): + # integer indexes, be careful + ser = Series(np.random.randn(10), index=list(range(0, 20, 2))) + inds = [0, 2, 5, 7, 8] + arr_inds = np.array([0, 2, 5, 7, 8]) + with pytest.raises(KeyError, match="with any missing labels"): + ser[inds] + + with pytest.raises(KeyError, match="with any missing labels"): + ser[arr_inds] + + +def test_getitem_missing(datetime_series): + # missing + d = datetime_series.index[0] - BDay() + msg = r"Timestamp\('1999-12-31 00:00:00', freq='B'\)" + with pytest.raises(KeyError, match=msg): + datetime_series[d] + + +def test_getitem_fancy(string_series, object_series): + slice1 = string_series[[1, 2, 3]] + slice2 = object_series[[1, 2, 3]] + assert string_series.index[2] == slice1.index[1] + assert object_series.index[2] == slice2.index[1] + assert string_series[2] == slice1[1] + assert object_series[2] == slice2[1] + + +def test_getitem_box_float64(datetime_series): + value = datetime_series[5] + assert isinstance(value, np.float64) + + +def test_getitem_unordered_dup(): + obj = Series(range(5), index=["c", "a", "a", "b", "b"]) + assert is_scalar(obj["c"]) + assert obj["c"] == 0 + + +def test_getitem_dups(): + ser = Series(range(5), index=["A", "A", "B", "C", "C"], dtype=np.int64) + expected = Series([3, 4], index=["C", "C"], dtype=np.int64) + result = ser["C"] + tm.assert_series_equal(result, expected) + + +def test_getitem_categorical_str(): + # GH#31765 + ser = Series(range(5), index=Categorical(["a", "b", "c", "a", "b"])) + result = ser["a"] + expected = ser.iloc[[0, 3]] + tm.assert_series_equal(result, expected) + + # Check the intermediate steps work as expected + with tm.assert_produces_warning(FutureWarning): + result = ser.index.get_value(ser, "a") + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index e047317acd24d..4ac50105f078c 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -5,8 +5,6 @@ import numpy as np import pytest -from pandas.core.dtypes.common import is_scalar - import pandas as pd from pandas import ( Categorical, @@ -22,8 +20,6 @@ ) import pandas._testing as tm -from pandas.tseries.offsets import BDay - def test_basic_indexing(): s = Series(np.random.randn(5), index=["a", "b", "a", "a", "b"]) @@ -58,18 +54,6 @@ def test_basic_getitem_with_labels(datetime_series): tm.assert_series_equal(result, expected) -def test_basic_getitem_with_integer_labels(): - # integer indexes, be careful - ser = Series(np.random.randn(10), index=list(range(0, 20, 2))) - inds = [0, 2, 5, 7, 8] - arr_inds = np.array([0, 2, 5, 7, 8]) - with pytest.raises(KeyError, match="with any missing labels"): - ser[inds] - - with pytest.raises(KeyError, match="with any missing labels"): - ser[arr_inds] - - def test_basic_getitem_dt64tz_values(): # GH12089 @@ -98,24 +82,7 @@ def test_getitem_setitem_ellipsis(): assert (result == 5).all() -def test_getitem_missing(datetime_series): - # missing - d = datetime_series.index[0] - BDay() - msg = r"Timestamp\('1999-12-31 00:00:00', freq='B'\)" - with pytest.raises(KeyError, match=msg): - datetime_series[d] - - -def test_getitem_fancy(string_series, object_series): - slice1 = string_series[[1, 2, 3]] - slice2 = object_series[[1, 2, 3]] - assert string_series.index[2] == slice1.index[1] - assert object_series.index[2] == slice2.index[1] - assert string_series[2] == slice1[1] - assert object_series[2] == slice2[1] - - -def test_type_promotion(): +def test_setitem_with_expansion_type_promotion(): # GH12599 s = Series(dtype=object) s["a"] = Timestamp("2016-01-01") @@ -157,11 +124,6 @@ def test_getitem_setitem_integers(): tm.assert_almost_equal(s["a"], 5) -def test_getitem_box_float64(datetime_series): - value = datetime_series[5] - assert isinstance(value, np.float64) - - def test_series_box_timestamp(): rng = pd.date_range("20090415", "20090519", freq="B") ser = Series(rng) @@ -189,49 +151,26 @@ def test_series_box_timedelta(): assert isinstance(ser.iloc[4], Timedelta) -def test_getitem_ambiguous_keyerror(): - s = Series(range(10), index=list(range(0, 20, 2))) +def test_getitem_ambiguous_keyerror(indexer_sl): + ser = Series(range(10), index=list(range(0, 20, 2))) with pytest.raises(KeyError, match=r"^1$"): - s[1] - with pytest.raises(KeyError, match=r"^1$"): - s.loc[1] - + indexer_sl(ser)[1] -def test_getitem_unordered_dup(): - obj = Series(range(5), index=["c", "a", "a", "b", "b"]) - assert is_scalar(obj["c"]) - assert obj["c"] == 0 - -def test_getitem_dups_with_missing(): +def test_getitem_dups_with_missing(indexer_sl): # breaks reindex, so need to use .loc internally # GH 4246 - s = Series([1, 2, 3, 4], ["foo", "bar", "foo", "bah"]) - with pytest.raises(KeyError, match="with any missing labels"): - s.loc[["foo", "bar", "bah", "bam"]] - + ser = Series([1, 2, 3, 4], ["foo", "bar", "foo", "bah"]) with pytest.raises(KeyError, match="with any missing labels"): - s[["foo", "bar", "bah", "bam"]] + indexer_sl(ser)[["foo", "bar", "bah", "bam"]] -def test_getitem_dups(): - s = Series(range(5), index=["A", "A", "B", "C", "C"], dtype=np.int64) - expected = Series([3, 4], index=["C", "C"], dtype=np.int64) - result = s["C"] - tm.assert_series_equal(result, expected) - - -def test_setitem_ambiguous_keyerror(): +def test_setitem_ambiguous_keyerror(indexer_sl): s = Series(range(10), index=list(range(0, 20, 2))) # equivalent of an append s2 = s.copy() - s2[1] = 5 - expected = s.append(Series([5], index=[1])) - tm.assert_series_equal(s2, expected) - - s2 = s.copy() - s2.loc[1] = 5 + indexer_sl(s2)[1] = 5 expected = s.append(Series([5], index=[1])) tm.assert_series_equal(s2, expected) @@ -314,13 +253,10 @@ def test_basic_getitem_setitem_corner(datetime_series): @pytest.mark.parametrize("tz", ["US/Eastern", "UTC", "Asia/Tokyo"]) -def test_setitem_with_tz(tz): +def test_setitem_with_tz(tz, indexer_sli): orig = Series(pd.date_range("2016-01-01", freq="H", periods=3, tz=tz)) assert orig.dtype == f"datetime64[ns, {tz}]" - # scalar - s = orig.copy() - s[1] = Timestamp("2011-01-01", tz=tz) exp = Series( [ Timestamp("2016-01-01 00:00", tz=tz), @@ -328,15 +264,11 @@ def test_setitem_with_tz(tz): Timestamp("2016-01-01 02:00", tz=tz), ] ) - tm.assert_series_equal(s, exp) - s = orig.copy() - s.loc[1] = Timestamp("2011-01-01", tz=tz) - tm.assert_series_equal(s, exp) - - s = orig.copy() - s.iloc[1] = Timestamp("2011-01-01", tz=tz) - tm.assert_series_equal(s, exp) + # scalar + ser = orig.copy() + indexer_sli(ser)[1] = Timestamp("2011-01-01", tz=tz) + tm.assert_series_equal(ser, exp) # vector vals = Series( @@ -345,7 +277,6 @@ def test_setitem_with_tz(tz): ) assert vals.dtype == f"datetime64[ns, {tz}]" - s[[1, 2]] = vals exp = Series( [ Timestamp("2016-01-01 00:00", tz=tz), @@ -353,26 +284,18 @@ def test_setitem_with_tz(tz): Timestamp("2012-01-01 00:00", tz=tz), ] ) - tm.assert_series_equal(s, exp) - s = orig.copy() - s.loc[[1, 2]] = vals - tm.assert_series_equal(s, exp) - - s = orig.copy() - s.iloc[[1, 2]] = vals - tm.assert_series_equal(s, exp) + ser = orig.copy() + indexer_sli(ser)[[1, 2]] = vals + tm.assert_series_equal(ser, exp) -def test_setitem_with_tz_dst(): +def test_setitem_with_tz_dst(indexer_sli): # GH XXX TODO: fill in GH ref tz = "US/Eastern" orig = Series(pd.date_range("2016-11-06", freq="H", periods=3, tz=tz)) assert orig.dtype == f"datetime64[ns, {tz}]" - # scalar - s = orig.copy() - s[1] = Timestamp("2011-01-01", tz=tz) exp = Series( [ Timestamp("2016-11-06 00:00-04:00", tz=tz), @@ -380,15 +303,11 @@ def test_setitem_with_tz_dst(): Timestamp("2016-11-06 01:00-05:00", tz=tz), ] ) - tm.assert_series_equal(s, exp) - s = orig.copy() - s.loc[1] = Timestamp("2011-01-01", tz=tz) - tm.assert_series_equal(s, exp) - - s = orig.copy() - s.iloc[1] = Timestamp("2011-01-01", tz=tz) - tm.assert_series_equal(s, exp) + # scalar + ser = orig.copy() + indexer_sli(ser)[1] = Timestamp("2011-01-01", tz=tz) + tm.assert_series_equal(ser, exp) # vector vals = Series( @@ -397,7 +316,6 @@ def test_setitem_with_tz_dst(): ) assert vals.dtype == f"datetime64[ns, {tz}]" - s[[1, 2]] = vals exp = Series( [ Timestamp("2016-11-06 00:00", tz=tz), @@ -405,15 +323,10 @@ def test_setitem_with_tz_dst(): Timestamp("2012-01-01 00:00", tz=tz), ] ) - tm.assert_series_equal(s, exp) - s = orig.copy() - s.loc[[1, 2]] = vals - tm.assert_series_equal(s, exp) - - s = orig.copy() - s.iloc[[1, 2]] = vals - tm.assert_series_equal(s, exp) + ser = orig.copy() + indexer_sli(ser)[[1, 2]] = vals + tm.assert_series_equal(ser, exp) def test_categorical_assigning_ops(): @@ -453,19 +366,6 @@ def test_setitem_nan_into_categorical(): tm.assert_series_equal(ser, exp) -def test_getitem_categorical_str(): - # GH#31765 - ser = Series(range(5), index=Categorical(["a", "b", "c", "a", "b"])) - result = ser["a"] - expected = ser.iloc[[0, 3]] - tm.assert_series_equal(result, expected) - - # Check the intermediate steps work as expected - with tm.assert_produces_warning(FutureWarning): - result = ser.index.get_value(ser, "a") - tm.assert_series_equal(result, expected) - - def test_slice(string_series, object_series): numSlice = string_series[10:20] numSliceEnd = string_series[-10:]
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39832
2021-02-16T04:03:36Z
2021-02-16T23:26:34Z
2021-02-16T23:26:33Z
2021-02-16T23:34:50Z
TST/REF: share Series setitem tests
diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index e047317acd24d..7889d46f66c99 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -542,56 +542,6 @@ def test_setitem_td64_non_nano(): tm.assert_series_equal(ser, expected) -@pytest.mark.parametrize( - "nat_val", - [ - pd.NaT, - np.timedelta64("NaT", "ns"), - np.datetime64("NaT", "ns"), - ], -) -@pytest.mark.parametrize("tz", [None, "UTC"]) -def test_dt64_series_assign_nat(nat_val, tz, indexer_sli): - # some nat-like values should be cast to datetime64 when inserting - # into a datetime64 series. Others should coerce to object - # and retain their dtypes. - dti = pd.date_range("2016-01-01", periods=3, tz=tz) - base = Series(dti) - expected = Series([pd.NaT] + list(dti[1:]), dtype=dti.dtype) - - should_cast = nat_val is pd.NaT or base.dtype == nat_val.dtype - if not should_cast: - expected = expected.astype(object) - - ser = base.copy(deep=True) - indexer_sli(ser)[0] = nat_val - tm.assert_series_equal(ser, expected) - - -@pytest.mark.parametrize( - "nat_val", - [ - pd.NaT, - np.timedelta64("NaT", "ns"), - np.datetime64("NaT", "ns"), - ], -) -def test_td64_series_assign_nat(nat_val, indexer_sli): - # some nat-like values should be cast to timedelta64 when inserting - # into a timedelta64 series. Others should coerce to object - # and retain their dtypes. - base = Series([0, 1, 2], dtype="m8[ns]") - expected = Series([pd.NaT, 1, 2], dtype="m8[ns]") - - should_cast = nat_val is pd.NaT or base.dtype == nat_val.dtype - if not should_cast: - expected = expected.astype(object) - - ser = base.copy(deep=True) - indexer_sli(ser)[0] = nat_val - tm.assert_series_equal(ser, expected) - - def test_underlying_data_conversion(): # GH 4080 df = DataFrame({c: [1, 2, 3] for c in ["a", "b", "c"]}) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 36948c3dc05f3..18a870b1b0b9c 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -167,15 +167,6 @@ def test_setitem_boolean_python_list(self, func): expected = Series(["a", "b", "c"]) tm.assert_series_equal(ser, expected) - @pytest.mark.parametrize("value", [None, NaT, np.nan]) - def test_setitem_boolean_td64_values_cast_na(self, value): - # GH#18586 - series = Series([0, 1, 2], dtype="timedelta64[ns]") - mask = series == series[0] - series[mask] = value - expected = Series([NaT, 1, 2], dtype="timedelta64[ns]") - tm.assert_series_equal(series, expected) - def test_setitem_boolean_nullable_int_types(self, any_nullable_numeric_dtype): # GH: 26468 ser = Series([5, 6, 7, 8], dtype=any_nullable_numeric_dtype) @@ -640,62 +631,43 @@ def is_inplace(self): return True -class TestSetitemNATimedelta64Dtype(SetitemCastingEquivalents): - # some nat-like values should be cast to timedelta64 when inserting - # into a timedelta64 series. Others should coerce to object - # and retain their dtypes. - - @pytest.fixture - def obj(self): - return Series([0, 1, 2], dtype="m8[ns]") +class TestSetitemNADatetimeLikeDtype(SetitemCastingEquivalents): + # some nat-like values should be cast to datetime64/timedelta64 when + # inserting into a datetime64/timedelta64 series. Others should coerce + # to object and retain their dtypes. + # GH#18586 for td64 and boolean mask case @pytest.fixture( - params=[NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")] + params=["m8[ns]", "M8[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Central]"] ) - def val(self, request): + def dtype(self, request): return request.param @pytest.fixture - def is_inplace(self, val): - # cast to object iff val is datetime64("NaT") - return val is NaT or val.dtype.kind == "m" - - @pytest.fixture - def expected(self, obj, val, is_inplace): - dtype = obj.dtype if is_inplace else object - expected = Series([val] + list(obj[1:]), dtype=dtype) - return expected - - @pytest.fixture - def key(self): - return 0 - - -class TestSetitemNADatetime64Dtype(SetitemCastingEquivalents): - # some nat-like values should be cast to datetime64 when inserting - # into a datetime64 series. Others should coerce to object - # and retain their dtypes. - - @pytest.fixture(params=[None, "UTC", "US/Central"]) - def obj(self, request): - tz = request.param - dti = date_range("2016-01-01", periods=3, tz=tz) - return Series(dti) + def obj(self, dtype): + i8vals = date_range("2016-01-01", periods=3).asi8 + idx = Index(i8vals, dtype=dtype) + assert idx.dtype == dtype + return Series(idx) @pytest.fixture( - params=[NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")] + params=[ + None, + np.nan, + NaT, + np.timedelta64("NaT", "ns"), + np.datetime64("NaT", "ns"), + ] ) def val(self, request): return request.param @pytest.fixture def is_inplace(self, val, obj): - if obj._values.tz is None: - # cast to object iff val is timedelta64("NaT") - return val is NaT or val.dtype.kind == "M" - - # otherwise we have to exclude tznaive dt64("NaT") - return val is NaT + # td64 -> cast to object iff val is datetime64("NaT") + # dt64 -> cast to object iff val is timedelta64("NaT") + # dt64tz -> cast to object with anything _but_ NaT + return val is NaT or val is None or val is np.nan or obj.dtype == val.dtype @pytest.fixture def expected(self, obj, val, is_inplace):
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39831
2021-02-16T02:34:46Z
2021-02-16T18:49:33Z
2021-02-16T18:49:33Z
2021-02-16T18:51:26Z
ENH: Hand numpy-like arrays with is_list_like
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2d8f6468aca83..aec19e27a33e2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -153,3 +153,9 @@ jobs: run: | source activate pandas-dev pytest pandas/tests/frame/methods --array-manager + + # indexing iset related (temporary since other tests don't pass yet) + pytest pandas/tests/frame/indexing/test_indexing.py::TestDataFrameIndexing::test_setitem_multi_index --array-manager + pytest pandas/tests/frame/indexing/test_setitem.py::TestDataFrameSetItem::test_setitem_listlike_indexer_duplicate_columns --array-manager + pytest pandas/tests/indexing/multiindex/test_setitem.py::TestMultiIndexSetItem::test_astype_assignment_with_dups --array-manager + pytest pandas/tests/indexing/multiindex/test_setitem.py::TestMultiIndexSetItem::test_frame_setitem_multi_column --array-manager diff --git a/.github/workflows/database.yml b/.github/workflows/database.yml index f3ccd78266ba6..b34373b82af1a 100644 --- a/.github/workflows/database.yml +++ b/.github/workflows/database.yml @@ -170,3 +170,11 @@ jobs: - name: Print skipped tests run: python ci/print_skipped.py + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1 + with: + files: /tmp/test_coverage.xml + flags: unittests + name: codecov-pandas + fail_ci_if_error: true diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e0df3434b2906..3a371c8249eba 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -180,6 +180,12 @@ repos: language: pygrep types: [python] files: ^pandas/tests/ + - id: title-capitalization + name: Validate correct capitalization among titles in documentation + entry: python scripts/validate_rst_title_capitalization.py + language: python + types: [rst] + files: ^doc/source/(development|reference)/ - repo: https://github.com/asottile/yesqa rev: v1.2.2 hooks: diff --git a/asv_bench/benchmarks/libs.py b/asv_bench/benchmarks/libs.py new file mode 100644 index 0000000000000..1c8de6d9f8e56 --- /dev/null +++ b/asv_bench/benchmarks/libs.py @@ -0,0 +1,42 @@ +""" +Benchmarks for code in pandas/_libs, excluding pandas/_libs/tslibs, +which has its own directory +""" +import numpy as np + +from pandas._libs.lib import ( + is_list_like, + is_scalar, +) + +from pandas import ( + NA, + NaT, +) + +# TODO: share with something in pd._testing? +scalars = [ + 0, + 1.0, + 1 + 2j, + True, + "foo", + b"bar", + None, + np.datetime64(123, "ns"), + np.timedelta64(123, "ns"), + NaT, + NA, +] +zero_dims = [np.array("123")] +listlikes = [np.array([1, 2, 3]), {0: "foo"}, set(1, 2, 3), [1, 2, 3], (1, 2, 3)] + + +class ScalarListLike: + params = scalars + zero_dims + listlikes + + def time_is_list_like(self, param): + is_list_like(param) + + def time_is_scalar(self, param): + is_scalar(param) diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 597aced96eb18..251f450840ea9 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -233,10 +233,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS02,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA02,SA03 RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Validate correct capitalization among titles in documentation' ; echo $MSG - $BASE_DIR/scripts/validate_rst_title_capitalization.py $BASE_DIR/doc/source/development $BASE_DIR/doc/source/reference - RET=$(($RET + $?)) ; echo $MSG "DONE" - fi ### TYPING ### diff --git a/ci/deps/azure-37-locale_slow.yaml b/ci/deps/azure-37-locale_slow.yaml index 7f658fe62d268..0c47b1a72774f 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.6.0 + - openpyxl=3.0.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 f184ea87c89fe..9cc158b76cd41 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.6.0 + - openpyxl=3.0.0 - pytables=3.5.1 - python-dateutil=2.7.3 - pytz=2017.3 diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index bb89b91954518..4b69d5b0c8c77 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -476,6 +476,14 @@ storing numeric arrays with units. These arrays can be stored inside pandas' Series and DataFrame. Operations between Series and DataFrame columns which use pint's extension array are then units aware. +`Text Extensions for Pandas`_ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``Text Extensions for Pandas <https://ibm.biz/text-extensions-for-pandas>`` +provides extension types to cover common data structures for representing natural language +data, plus library integrations that convert the outputs of popular natural language +processing libraries into Pandas DataFrames. + .. _ecosystem.accessors: Accessors diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index 49039f05b889a..06e1af75053d3 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.6.0 Reading / writing for xlsx files +openpyxl 3.0.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/user_guide/gotchas.rst b/doc/source/user_guide/gotchas.rst index 07c856c96426d..4089f9523724f 100644 --- a/doc/source/user_guide/gotchas.rst +++ b/doc/source/user_guide/gotchas.rst @@ -178,6 +178,75 @@ To test for membership in the values, use the method :meth:`~pandas.Series.isin` For ``DataFrames``, likewise, ``in`` applies to the column axis, testing for membership in the list of column names. +.. _udf-mutation: + +Mutating with User Defined Function (UDF) methods +------------------------------------------------- + +It is a general rule in programming that one should not mutate a container +while it is being iterated over. Mutation will invalidate the iterator, +causing unexpected behavior. Consider the example: + +.. ipython:: python + + values = [0, 1, 2, 3, 4, 5] + n_removed = 0 + for k, value in enumerate(values): + idx = k - n_removed + if value % 2 == 1: + del values[idx] + n_removed += 1 + else: + values[idx] = value + 1 + values + +One probably would have expected that the result would be ``[1, 3, 5]``. +When using a pandas method that takes a UDF, internally pandas is often +iterating over the +``DataFrame`` or other pandas object. Therefore, if the UDF mutates (changes) +the ``DataFrame``, unexpected behavior can arise. + +Here is a similar example with :meth:`DataFrame.apply`: + +.. ipython:: python + + def f(s): + s.pop("a") + return s + + df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + try: + df.apply(f, axis="columns") + except Exception as err: + print(repr(err)) + +To resolve this issue, one can make a copy so that the mutation does +not apply to the container being iterated over. + +.. ipython:: python + + values = [0, 1, 2, 3, 4, 5] + n_removed = 0 + for k, value in enumerate(values.copy()): + idx = k - n_removed + if value % 2 == 1: + del values[idx] + n_removed += 1 + else: + values[idx] = value + 1 + values + +.. ipython:: python + + def f(s): + s = s.copy() + s.pop("a") + return s + + df = pd.DataFrame({"a": [1, 2, 3], 'b': [4, 5, 6]}) + df.apply(f, axis="columns") + + ``NaN``, Integer ``NA`` values and ``NA`` type promotions --------------------------------------------------------- diff --git a/doc/source/whatsnew/v0.8.0.rst b/doc/source/whatsnew/v0.8.0.rst index 781054fc4de7c..490175914cef1 100644 --- a/doc/source/whatsnew/v0.8.0.rst +++ b/doc/source/whatsnew/v0.8.0.rst @@ -176,7 +176,7 @@ New plotting methods Vytautas Jancauskas, the 2012 GSOC participant, has added many new plot types. For example, ``'kde'`` is a new option: -.. ipython:: python +.. code-block:: python s = pd.Series( np.concatenate((np.random.randn(1000), np.random.randn(1000) * 0.5 + 3)) diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index e675b3ea921d1..4231b6d94b1b9 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -15,7 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Fixed regression in :func:`pandas.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) - .. --------------------------------------------------------------------------- diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 799bc88ffff4e..76bd95c1c5d9d 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -186,7 +186,7 @@ Optional libraries below the lowest tested version may still work, but are not c +-----------------+-----------------+---------+ | numba | 0.46.0 | | +-----------------+-----------------+---------+ -| openpyxl | 2.6.0 | | +| openpyxl | 3.0.0 | X | +-----------------+-----------------+---------+ | pyarrow | 0.15.0 | | +-----------------+-----------------+---------+ @@ -239,7 +239,7 @@ Deprecations - Deprecated :attr:`Rolling.is_datetimelike` (:issue:`38963`) - Deprecated :meth:`core.window.ewm.ExponentialMovingWindow.vol` (:issue:`39220`) - Using ``.astype`` to convert between ``datetime64[ns]`` dtype and :class:`DatetimeTZDtype` is deprecated and will raise in a future version, use ``obj.tz_localize`` or ``obj.dt.tz_localize`` instead (:issue:`38622`) -- +- Deprecated casting ``datetime.date`` objects to ``datetime64`` when used as ``fill_value`` in :meth:`DataFrame.unstack`, :meth:`DataFrame.shift`, :meth:`Series.shift`, and :meth:`DataFrame.reindex`, pass ``pd.Timestamp(dateobj)`` instead (:issue:`39767`) .. --------------------------------------------------------------------------- @@ -346,7 +346,9 @@ Indexing - Bug in setting ``timedelta64`` or ``datetime64`` values into numeric :class:`Series` failing to cast to object dtype (:issue:`39086`, issue:`39619`) - Bug in setting :class:`Interval` values into a :class:`Series` or :class:`DataFrame` with mismatched :class:`IntervalDtype` incorrectly casting the new values to the existing dtype (:issue:`39120`) - Bug in setting ``datetime64`` values into a :class:`Series` with integer-dtype incorrect casting the datetime64 values to integers (:issue:`39266`) +- Bug in setting ``np.datetime64("NaT")`` into a :class:`Series` with :class:`Datetime64TZDtype` incorrectly treating the timezone-naive value as timezone-aware (:issue:`39769`) - Bug in :meth:`Index.get_loc` not raising ``KeyError`` when method is specified for ``NaN`` value when ``NaN`` is not in :class:`Index` (:issue:`39382`) +- Bug in :meth:`DatetimeIndex.insert` when inserting ``np.datetime64("NaT")`` into a timezone-aware index incorrectly treating the timezone-naive value as timezone-aware (:issue:`39769`) - Bug in incorrectly raising in :meth:`Index.insert`, when setting a new column that cannot be held in the existing ``frame.columns``, or in :meth:`Series.reset_index` or :meth:`DataFrame.reset_index` instead of casting to a compatible dtype (:issue:`39068`) - Bug in :meth:`RangeIndex.append` where a single object of length 1 was concatenated incorrectly (:issue:`39401`) - Bug in setting ``numpy.timedelta64`` values into an object-dtype :class:`Series` using a boolean indexer (:issue:`39488`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 3a11e7fbbdf33..5da6c0778fb60 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1044,11 +1044,15 @@ def is_list_like(obj: object, allow_sets: bool = True) -> bool: cdef inline bint c_is_list_like(object obj, bint allow_sets) except -1: return ( - isinstance(obj, abc.Iterable) + # equiv: `isinstance(obj, abc.Iterable)` + hasattr(obj, "__iter__") and not isinstance(obj, type) # we do not count strings/unicode/bytes as list-like and not isinstance(obj, (str, bytes)) # exclude zero-dimensional numpy arrays, effectively scalars - and not (util.is_array(obj) and obj.ndim == 0) + and not cnp.PyArray_IsZeroDim(obj) + # extra check for numpy-like objects which aren't captured by + # the above + and not (hasattr(obj, "ndim") and obj.ndim == 0) # exclude sets if allow_sets is False and not (allow_sets is False and isinstance(obj, abc.Set)) ) diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 0b2be53131af6..97a152d9ade1e 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -559,7 +559,7 @@ def makeCustomIndex( "p": makePeriodIndex, }.get(idx_type) if idx_func: - # pandas\_testing.py:2120: error: Cannot call function of unknown type + # error: Cannot call function of unknown type idx = idx_func(nentries) # type: ignore[operator] # but we need to fill in the name if names: diff --git a/pandas/_testing/_io.py b/pandas/_testing/_io.py index 5f27b016b68a2..8d387ff5674f7 100644 --- a/pandas/_testing/_io.py +++ b/pandas/_testing/_io.py @@ -82,9 +82,8 @@ def dec(f): is_decorating = not kwargs and len(args) == 1 and callable(args[0]) if is_decorating: f = args[0] - # pandas\_testing.py:2331: error: Incompatible types in assignment - # (expression has type "List[<nothing>]", variable has type - # "Tuple[Any, ...]") + # error: Incompatible types in assignment (expression has type + # "List[<nothing>]", variable has type "Tuple[Any, ...]") args = [] # type: ignore[assignment] return dec(f) else: @@ -205,8 +204,7 @@ def wrapper(*args, **kwargs): except Exception as err: errno = getattr(err, "errno", None) if not errno and hasattr(errno, "reason"): - # pandas\_testing.py:2521: error: "Exception" has no attribute - # "reason" + # error: "Exception" has no attribute "reason" errno = getattr(err.reason, "errno", None) # type: ignore[attr-defined] if errno in skip_errnos: diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index bcad9f1ddab09..eb2b4caddb7a6 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -17,7 +17,7 @@ "matplotlib": "2.2.3", "numexpr": "2.6.8", "odfpy": "1.3.0", - "openpyxl": "2.6.0", + "openpyxl": "3.0.0", "pandas_gbq": "0.12.0", "pyarrow": "0.15.0", "pytest": "5.0.1", diff --git a/pandas/conftest.py b/pandas/conftest.py index bc455092ebe86..79204c8896854 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -1565,6 +1565,14 @@ def indexer_si(request): return request.param +@pytest.fixture(params=[tm.setitem, tm.loc]) +def indexer_sl(request): + """ + Parametrize over __setitem__, loc.__setitem__ + """ + return request.param + + @pytest.fixture def using_array_manager(request): """ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 6088837550ecd..337c1910102a7 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -2208,7 +2208,7 @@ def _sort_mixed(values): return np.concatenate([nums, np.asarray(strs, dtype=object)]) -def _sort_tuples(values: np.ndarray[tuple]): +def _sort_tuples(values: np.ndarray): """ Convert array of tuples (1d) to array or array (2d). We need to keep the columns separately as they contain different types and diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 828b460f84ec6..6e48d4b699977 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -147,18 +147,14 @@ def index(self) -> Index: def apply(self) -> FrameOrSeriesUnion: pass - def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: + def agg(self) -> Optional[FrameOrSeriesUnion]: """ Provide an implementation for the aggregators. Returns ------- - tuple of result, how. - - Notes - ----- - how can be a string describe the required post-processing, or - None if not required. + Result of aggregation, or None if agg cannot be performed by + this method. """ obj = self.obj arg = self.f @@ -171,23 +167,21 @@ def agg(self) -> Tuple[Optional[FrameOrSeriesUnion], Optional[bool]]: result = self.maybe_apply_str() if result is not None: - return result, None + return result if is_dict_like(arg): - return self.agg_dict_like(_axis), True + return self.agg_dict_like(_axis) elif is_list_like(arg): # we require a list, but not a 'str' - return self.agg_list_like(_axis=_axis), None - else: - result = None + return self.agg_list_like(_axis=_axis) if callable(arg): f = obj._get_cython_func(arg) if f and not args and not kwargs: - return getattr(obj, f)(), None + return getattr(obj, f)() # caller can react - return result, True + return None def agg_list_like(self, _axis: int) -> FrameOrSeriesUnion: """ diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index cb185dcf78f63..e17ba45f30d6c 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -228,7 +228,7 @@ def _maybe_fallback(ufunc: Callable, method: str, *inputs: Any, **kwargs: Any): return NotImplemented -def array_ufunc(self, ufunc: Callable, method: str, *inputs: Any, **kwargs: Any): +def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any): """ Compatibility with numpy ufuncs. @@ -341,9 +341,7 @@ def reconstruct(result): result = result.__finalize__(self) return result - if self.ndim > 1 and ( - len(inputs) > 1 or ufunc.nout > 1 # type: ignore[attr-defined] - ): + if self.ndim > 1 and (len(inputs) > 1 or ufunc.nout > 1): # Just give up on preserving types in the complex case. # In theory we could preserve them for them. # * nout>1 is doable if BlockManager.apply took nout and @@ -367,7 +365,7 @@ def reconstruct(result): # Those can have an axis keyword and thus can't be called block-by-block result = getattr(ufunc, method)(np.asarray(inputs[0]), **kwargs) - if ufunc.nout > 1: # type: ignore[attr-defined] + if ufunc.nout > 1: result = tuple(reconstruct(x) for x in result) else: result = reconstruct(result) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 162a69370bc61..3dd170f60a62c 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -445,8 +445,7 @@ def _validate_comparison_value(self, other): raise InvalidComparison(other) if isinstance(other, self._recognized_scalars) or other is NaT: - # pandas\core\arrays\datetimelike.py:432: error: Too many arguments - # for "object" [call-arg] + # error: Too many arguments for "object" other = self._scalar_type(other) # type: ignore[call-arg] try: self._check_compatible_with(other) @@ -497,8 +496,7 @@ def _validate_shift_value(self, fill_value): if is_valid_na_for_dtype(fill_value, self.dtype): fill_value = NaT elif isinstance(fill_value, self._recognized_scalars): - # pandas\core\arrays\datetimelike.py:746: error: Too many arguments - # for "object" [call-arg] + # error: Too many arguments for "object" fill_value = self._scalar_type(fill_value) # type: ignore[call-arg] else: # only warn if we're not going to raise @@ -506,8 +504,7 @@ def _validate_shift_value(self, fill_value): # kludge for #31971 since Period(integer) tries to cast to str new_fill = Period._from_ordinal(fill_value, freq=self.freq) else: - # pandas\core\arrays\datetimelike.py:753: error: Too many - # arguments for "object" [call-arg] + # error: Too many arguments for "object" new_fill = self._scalar_type(fill_value) # type: ignore[call-arg] # stacklevel here is chosen to be correct when called from @@ -562,8 +559,14 @@ def _validate_scalar( # GH#18295 value = NaT + elif isna(value): + # if we are dt64tz and value is dt64("NaT"), dont cast to NaT, + # or else we'll fail to raise in _unbox_scalar + msg = self._validation_error_message(value, allow_listlike) + raise TypeError(msg) + elif isinstance(value, self._recognized_scalars): - # error: Too many arguments for "object" [call-arg] + # error: Too many arguments for "object" value = self._scalar_type(value) # type: ignore[call-arg] else: @@ -1679,7 +1682,7 @@ def factorize(self, na_sentinel=-1, sort: bool = False): # TODO: overload __getitem__, a slice indexer returns same type as self # error: Incompatible types in assignment (expression has type # "Union[DatetimeLikeArrayMixin, Union[Any, Any]]", variable - # has type "TimelikeOps") [assignment] + # has type "TimelikeOps") uniques = uniques[::-1] # type: ignore[assignment] return codes, uniques # FIXME: shouldn't get here; we are ignoring sort diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 144a7186f5826..70c2015c6d41c 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -464,10 +464,8 @@ def _generate_range( def _unbox_scalar(self, value, setitem: bool = False) -> np.datetime64: if not isinstance(value, self._scalar_type) and value is not NaT: raise ValueError("'value' should be a Timestamp.") - if not isna(value): - self._check_compatible_with(value, setitem=setitem) - return value.asm8 - return np.datetime64(value.value, "ns") + self._check_compatible_with(value, setitem=setitem) + return value.asm8 def _scalar_from_string(self, value): return Timestamp(value, tz=self.tz) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 0f3e028c34c05..c720f4bdacaff 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -9,6 +9,7 @@ from pandas._config import get_option +from pandas._libs import NaT from pandas._libs.interval import ( VALID_CLOSED, Interval, @@ -23,7 +24,8 @@ from pandas.core.dtypes.cast import maybe_convert_platform from pandas.core.dtypes.common import ( is_categorical_dtype, - is_datetime64_any_dtype, + is_datetime64_dtype, + is_datetime64tz_dtype, is_dtype_equal, is_float_dtype, is_integer_dtype, @@ -999,9 +1001,12 @@ def _validate_setitem_value(self, value): if is_integer_dtype(self.dtype.subtype): # can't set NaN on a numpy integer array needs_float_conversion = True - elif is_datetime64_any_dtype(self.dtype.subtype): + elif is_datetime64_dtype(self.dtype.subtype): # need proper NaT to set directly on the numpy array value = np.datetime64("NaT") + elif is_datetime64tz_dtype(self.dtype.subtype): + # need proper NaT to set directly on the DatetimeArray array + value = NaT elif is_timedelta64_dtype(self.dtype.subtype): # need proper NaT to set directly on the numpy array value = np.timedelta64("NaT") @@ -1508,7 +1513,7 @@ def isin(self, values) -> np.ndarray: # GH#38353 instead of casting to object, operating on a # complex128 ndarray is much more performant. - # error: "ArrayLike" has no attribute "view" [attr-defined] + # error: "ArrayLike" has no attribute "view" left = self._combined.view("complex128") # type:ignore[attr-defined] right = values._combined.view("complex128") return np.in1d(left, right) diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 65618ce32b6d7..b318757e8978a 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -190,9 +190,8 @@ def __init__(self, values, copy=False): values = extract_array(values) super().__init__(values, copy=copy) - # pandas\core\arrays\string_.py:188: error: Incompatible types in - # assignment (expression has type "StringDtype", variable has type - # "PandasDtype") [assignment] + # error: Incompatible types in assignment (expression has type "StringDtype", + # variable has type "PandasDtype") self._dtype = StringDtype() # type: ignore[assignment] if not isinstance(values, type(self)): self._validate() diff --git a/pandas/core/base.py b/pandas/core/base.py index da8ed8a59f981..3f3b4cd1afec1 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -95,8 +95,7 @@ def __sizeof__(self): either a value or Series of values """ if hasattr(self, "memory_usage"): - # pandas\core\base.py:84: error: "PandasObject" has no attribute - # "memory_usage" [attr-defined] + # error: "PandasObject" has no attribute "memory_usage" mem = self.memory_usage(deep=True) # type: ignore[attr-defined] return int(mem if is_scalar(mem) else mem.sum()) @@ -206,17 +205,14 @@ def _selection_list(self): @cache_readonly def _selected_obj(self): - # pandas\core\base.py:195: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" if self._selection is None or isinstance( self.obj, ABCSeries # type: ignore[attr-defined] ): - # pandas\core\base.py:194: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" return self.obj # type: ignore[attr-defined] else: - # pandas\core\base.py:204: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" return self.obj[self._selection] # type: ignore[attr-defined] @cache_readonly @@ -225,29 +221,22 @@ def ndim(self) -> int: @cache_readonly def _obj_with_exclusions(self): - # pandas\core\base.py:209: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" if self._selection is not None and isinstance( self.obj, ABCDataFrame # type: ignore[attr-defined] ): - # pandas\core\base.py:217: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" return self.obj.reindex( # type: ignore[attr-defined] columns=self._selection_list ) - # pandas\core\base.py:207: error: "SelectionMixin" has no attribute - # "exclusions" [attr-defined] + # error: "SelectionMixin" has no attribute "exclusions" if len(self.exclusions) > 0: # type: ignore[attr-defined] - # pandas\core\base.py:208: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] - - # pandas\core\base.py:208: error: "SelectionMixin" has no attribute - # "exclusions" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" + # error: "SelectionMixin" has no attribute "exclusions" return self.obj.drop(self.exclusions, axis=1) # type: ignore[attr-defined] else: - # pandas\core\base.py:210: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" return self.obj # type: ignore[attr-defined] def __getitem__(self, key): @@ -255,13 +244,11 @@ def __getitem__(self, key): raise IndexError(f"Column(s) {self._selection} already selected") if isinstance(key, (list, tuple, ABCSeries, ABCIndex, np.ndarray)): - # pandas\core\base.py:217: error: "SelectionMixin" has no attribute - # "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" if len( self.obj.columns.intersection(key) # type: ignore[attr-defined] ) != len(key): - # pandas\core\base.py:218: error: "SelectionMixin" has no - # attribute "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" bad_keys = list( set(key).difference(self.obj.columns) # type: ignore[attr-defined] ) @@ -269,13 +256,13 @@ def __getitem__(self, key): return self._gotitem(list(key), ndim=2) elif not getattr(self, "as_index", False): - # error: "SelectionMixin" has no attribute "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" if key not in self.obj.columns: # type: ignore[attr-defined] raise KeyError(f"Column not found: {key}") return self._gotitem(key, ndim=2) else: - # error: "SelectionMixin" has no attribute "obj" [attr-defined] + # error: "SelectionMixin" has no attribute "obj" if key not in self.obj: # type: ignore[attr-defined] raise KeyError(f"Column not found: {key}") return self._gotitem(key, ndim=1) @@ -601,8 +588,7 @@ def to_numpy( dtype='datetime64[ns]') """ if is_extension_array_dtype(self.dtype): - # pandas\core\base.py:837: error: Too many arguments for "to_numpy" - # of "ExtensionArray" [call-arg] + # error: Too many arguments for "to_numpy" of "ExtensionArray" return self.array.to_numpy( # type: ignore[call-arg] dtype, copy=copy, na_value=na_value, **kwargs ) @@ -914,13 +900,11 @@ def _map_values(self, mapper, na_action=None): # use the built in categorical series mapper which saves # time by mapping the categories instead of all values - # pandas\core\base.py:893: error: Incompatible types in - # assignment (expression has type "Categorical", variable has - # type "IndexOpsMixin") [assignment] + # error: Incompatible types in assignment (expression has type + # "Categorical", variable has type "IndexOpsMixin") self = cast("Categorical", self) # type: ignore[assignment] - # pandas\core\base.py:894: error: Item "ExtensionArray" of - # "Union[ExtensionArray, Any]" has no attribute "map" - # [union-attr] + # error: Item "ExtensionArray" of "Union[ExtensionArray, Any]" has no + # attribute "map" return self._values.map(mapper) # type: ignore[union-attr] values = self._values @@ -938,8 +922,7 @@ def _map_values(self, mapper, na_action=None): raise NotImplementedError map_f = lambda values, f: values.map(f) else: - # pandas\core\base.py:1142: error: "IndexOpsMixin" has no attribute - # "astype" [attr-defined] + # error: "IndexOpsMixin" has no attribute "astype" values = self.astype(object)._values # type: ignore[attr-defined] if na_action == "ignore": map_f = lambda values, f: lib.map_infer_mask( @@ -1177,8 +1160,7 @@ def memory_usage(self, deep=False): are not components of the array if deep=False or if used on PyPy """ if hasattr(self.array, "memory_usage"): - # pandas\core\base.py:1379: error: "ExtensionArray" has no - # attribute "memory_usage" [attr-defined] + # error: "ExtensionArray" has no attribute "memory_usage" return self.array.memory_usage(deep=deep) # type: ignore[attr-defined] v = self.array.nbytes @@ -1313,8 +1295,7 @@ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray: def drop_duplicates(self, keep="first"): duplicated = self.duplicated(keep=keep) - # pandas\core\base.py:1507: error: Value of type "IndexOpsMixin" is not - # indexable [index] + # error: Value of type "IndexOpsMixin" is not indexable return self[~duplicated] # type: ignore[index] def duplicated(self, keep="first"): diff --git a/pandas/core/common.py b/pandas/core/common.py index aa24e12bf2cf1..89ba33da92661 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -268,10 +268,6 @@ 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 babf8116a5588..ee91ab4a282cf 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -659,8 +659,7 @@ def visit_Call(self, node, side=None, **kwargs): raise if res is None: - # pandas\core\computation\expr.py:663: error: "expr" has no - # attribute "id" [attr-defined] + # error: "expr" has no attribute "id" raise ValueError( f"Invalid function call {node.func.id}" # type: ignore[attr-defined] ) @@ -684,8 +683,7 @@ def visit_Call(self, node, side=None, **kwargs): for key in node.keywords: if not isinstance(key, ast.keyword): - # pandas\core\computation\expr.py:684: error: "expr" has no - # attribute "id" [attr-defined] + # error: "expr" has no attribute "id" raise ValueError( "keyword error in function call " # type: ignore[attr-defined] f"'{node.func.id}'" diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 7b42b21cadc1f..e8eae710623c5 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -71,8 +71,7 @@ def __init__(self, name: str, is_local: Optional[bool] = None): class Term: def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls - # pandas\core\computation\ops.py:72: error: Argument 2 for "super" not - # an instance of argument 1 [misc] + # error: Argument 2 for "super" not an instance of argument 1 supr_new = super(Term, klass).__new__ # type: ignore[misc] return supr_new(klass) @@ -593,7 +592,7 @@ def __init__(self, func, args): self.func = func def __call__(self, env): - # pandas\core\computation\ops.py:592: error: "Op" not callable [operator] + # error: "Op" not callable operands = [op(env) for op in self.operands] # type: ignore[operator] with np.errstate(all="ignore"): return self.func.func(*operands) diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index c2ba7f9892ef0..71d725051977f 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -131,17 +131,14 @@ def __init__( # scope when we align terms (alignment accesses the underlying # numpy array of pandas objects) - # pandas\core\computation\scope.py:132: error: Incompatible types - # in assignment (expression has type "ChainMap[str, Any]", variable - # has type "DeepChainMap[str, Any]") [assignment] + # error: Incompatible types in assignment (expression has type + # "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]") self.scope = self.scope.new_child( # type: ignore[assignment] (global_dict or frame.f_globals).copy() ) if not isinstance(local_dict, Scope): - # pandas\core\computation\scope.py:134: error: Incompatible - # types in assignment (expression has type "ChainMap[str, - # Any]", variable has type "DeepChainMap[str, Any]") - # [assignment] + # error: Incompatible types in assignment (expression has type + # "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]") self.scope = self.scope.new_child( # type: ignore[assignment] (local_dict or frame.f_locals).copy() ) @@ -150,8 +147,7 @@ def __init__( # assumes that resolvers are going from outermost scope to inner if isinstance(local_dict, Scope): - # pandas\core\computation\scope.py:140: error: Cannot determine - # type of 'resolvers' [has-type] + # error: Cannot determine type of 'resolvers' resolvers += tuple(local_dict.resolvers.maps) # type: ignore[has-type] self.resolvers = DeepChainMap(*resolvers) self.temps = {} @@ -239,8 +235,7 @@ def swapkey(self, old_key: str, new_key: str, new_value=None): for mapping in maps: if old_key in mapping: - # pandas\core\computation\scope.py:228: error: Unsupported - # target for indexed assignment ("Mapping[Any, Any]") [index] + # error: Unsupported target for indexed assignment ("Mapping[Any, Any]") mapping[new_key] = new_value # type: ignore[index] return @@ -260,10 +255,8 @@ def _get_vars(self, stack, scopes: List[str]): for scope, (frame, _, _, _, _, _) in variables: try: d = getattr(frame, "f_" + scope) - # pandas\core\computation\scope.py:247: error: Incompatible - # types in assignment (expression has type "ChainMap[str, - # Any]", variable has type "DeepChainMap[str, Any]") - # [assignment] + # error: Incompatible types in assignment (expression has type + # "ChainMap[str, Any]", variable has type "DeepChainMap[str, Any]") self.scope = self.scope.new_child(d) # type: ignore[assignment] finally: # won't remove it, but DECREF it @@ -331,13 +324,10 @@ def full_scope(self): vars : DeepChainMap All variables in this scope. """ - # pandas\core\computation\scope.py:314: error: Unsupported operand - # types for + ("List[Dict[Any, Any]]" and "List[Mapping[Any, Any]]") - # [operator] - - # pandas\core\computation\scope.py:314: error: Unsupported operand - # types for + ("List[Dict[Any, Any]]" and "List[Mapping[str, Any]]") - # [operator] + # error: Unsupported operand types for + ("List[Dict[Any, Any]]" and + # "List[Mapping[Any, Any]]") + # error: Unsupported operand types for + ("List[Dict[Any, Any]]" and + # "List[Mapping[str, Any]]") maps = ( [self.temps] + self.resolvers.maps # type: ignore[operator] diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e27c519304e2e..74d750288bdeb 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -5,7 +5,7 @@ from __future__ import annotations from contextlib import suppress -from datetime import datetime, timedelta +from datetime import date, datetime, timedelta from typing import ( TYPE_CHECKING, Any, @@ -549,16 +549,46 @@ def maybe_promote(dtype: np.dtype, fill_value=np.nan): # returns tuple of (dtype, fill_value) if issubclass(dtype.type, np.datetime64): - if isinstance(fill_value, datetime) and fill_value.tzinfo is not None: - # Trying to insert tzaware into tznaive, have to cast to object - dtype = np.dtype(np.object_) - elif is_integer(fill_value) or is_float(fill_value): - dtype = np.dtype(np.object_) - else: + inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True) + if inferred == dtype: + return dtype, fv + + # TODO(2.0): once this deprecation is enforced, this whole case + # becomes equivalent to: + # dta = DatetimeArray._from_sequence([], dtype="M8[ns]") + # try: + # fv = dta._validate_setitem_value(fill_value) + # return dta.dtype, fv + # except (ValueError, TypeError): + # return np.dtype(object), fill_value + if isinstance(fill_value, date) and not isinstance(fill_value, datetime): + # deprecate casting of date object to match infer_dtype_from_scalar + # and DatetimeArray._validate_setitem_value try: - fill_value = Timestamp(fill_value).to_datetime64() - except (TypeError, ValueError): - dtype = np.dtype(np.object_) + fv = Timestamp(fill_value).to_datetime64() + except OutOfBoundsDatetime: + pass + else: + warnings.warn( + "Using a `date` object for fill_value with `datetime64[ns]` " + "dtype is deprecated. In a future version, this will be cast " + "to object dtype. Pass `fill_value=Timestamp(date_obj)` instead.", + FutureWarning, + stacklevel=7, + ) + return dtype, fv + elif isinstance(fill_value, str): + try: + # explicitly wrap in str to convert np.str_ + fv = Timestamp(str(fill_value)) + except (ValueError, TypeError): + pass + else: + if fv.tz is None: + return dtype, fv.asm8 + + return np.dtype(object), fill_value + elif issubclass(dtype.type, np.timedelta64): if ( is_integer(fill_value) @@ -723,13 +753,13 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, if val is NaT or val.tz is None: dtype = np.dtype("M8[ns]") + val = val.to_datetime64() else: if pandas_dtype: dtype = DatetimeTZDtype(unit="ns", tz=val.tz) else: # return datetimetz as object return np.dtype(object), val - val = val.value elif isinstance(val, (np.timedelta64, timedelta)): try: diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index ef645313de614..7ebbbdc9ce7f9 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -604,7 +604,11 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool: if not lib.is_scalar(obj) or not isna(obj): return False if dtype.kind == "M": - return not isinstance(obj, np.timedelta64) + if isinstance(dtype, np.dtype): + # i.e. not tzaware + return not isinstance(obj, np.timedelta64) + # we have to rule out tznaive dt64("NaT") + return not isinstance(obj, (np.timedelta64, np.datetime64)) if dtype.kind == "m": return not isinstance(obj, np.datetime64) if dtype.kind in ["i", "u", "f", "c"]: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 63d238da12101..4f3b1357b1000 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1163,8 +1163,8 @@ def __len__(self) -> int: """ return len(self.index) - # pandas/core/frame.py:1146: error: Overloaded function signatures 1 and 2 - # overlap with incompatible return types [misc] + # error: Overloaded function signatures 1 and 2 overlap with incompatible return + # types @overload def dot(self, other: Series) -> Series: # type: ignore[misc] ... @@ -4822,8 +4822,8 @@ def set_index( elif isinstance(col, (Index, Series)): # if Index then not MultiIndex (treated above) - # error: Argument 1 to "append" of "list" has incompatible - # type "Union[Index, Series]"; expected "Index" [arg-type] + # error: Argument 1 to "append" of "list" has incompatible type + # "Union[Index, Series]"; expected "Index" arrays.append(col) # type:ignore[arg-type] names.append(col.name) elif isinstance(col, (list, np.ndarray)): @@ -7686,7 +7686,7 @@ def aggregate(self, func=None, axis: Axis = 0, *args, **kwargs): result = None try: - result, how = self._aggregate(func, axis, *args, **kwargs) + result = self._aggregate(func, axis, *args, **kwargs) except TypeError as err: exc = TypeError( "DataFrame constructor called with " @@ -7720,14 +7720,14 @@ def _aggregate(self, arg, axis: Axis = 0, *args, **kwargs): args=args, kwargs=kwargs, ) - result, how = op.agg() + result = op.agg() if axis == 1: # NDFrame.aggregate returns a tuple, and we need to transpose # only result result = result.T if result is not None else result - return result, how + return result agg = aggregate @@ -7814,6 +7814,12 @@ def apply( DataFrame.aggregate: Only perform aggregating type operations. DataFrame.transform: Only perform transforming type operations. + Notes + ----- + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`udf-mutation` + for more details. + Examples -------- >>> df = pd.DataFrame([[4, 9]] * 3, columns=['A', 'B']) @@ -9723,12 +9729,3 @@ def _reindex_for_setitem(value: FrameOrSeriesUnion, index: Index) -> ArrayLike: "incompatible index of inserted column with frame index" ) from err return reindexed_value - - -def _maybe_atleast_2d(value): - # TODO(EA2D): not needed with 2D EAs - - if is_extension_array_dtype(value): - return value - - return np.atleast_2d(np.asarray(value)) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ec37da66760c3..6413489a74ae6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10530,8 +10530,7 @@ def _add_numeric_operations(cls): def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): return NDFrame.any(self, axis, bool_only, skipna, level, **kwargs) - # pandas\core\generic.py:10725: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.any = any # type: ignore[assignment] @doc( @@ -10547,13 +10546,11 @@ def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): return NDFrame.all(self, axis, bool_only, skipna, level, **kwargs) - # pandas\core\generic.py:10719: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method - # pandas\core\generic.py:10719: error: Incompatible types in assignment - # (expression has type "Callable[[Iterable[object]], bool]", variable - # has type "Callable[[NDFrame, Any, Any, Any, Any, KwArg(Any)], Any]") - # [assignment] + # error: Incompatible types in assignment (expression has type + # "Callable[[Iterable[object]], bool]", variable has type "Callable[[NDFrame, + # Any, Any, Any, Any, KwArg(Any)], Any]") cls.all = all # type: ignore[assignment] # error: Argument 1 to "doc" has incompatible type "Optional[str]"; expected @@ -10571,8 +10568,7 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): def mad(self, axis=None, skipna=None, level=None): return NDFrame.mad(self, axis, skipna, level) - # pandas\core\generic.py:10736: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.mad = mad # type: ignore[assignment] @doc( @@ -10595,8 +10591,7 @@ def sem( ): return NDFrame.sem(self, axis, skipna, level, ddof, numeric_only, **kwargs) - # pandas\core\generic.py:10758: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.sem = sem # type: ignore[assignment] @doc( @@ -10618,8 +10613,7 @@ def var( ): return NDFrame.var(self, axis, skipna, level, ddof, numeric_only, **kwargs) - # pandas\core\generic.py:10779: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.var = var # type: ignore[assignment] @doc( @@ -10642,8 +10636,7 @@ def std( ): return NDFrame.std(self, axis, skipna, level, ddof, numeric_only, **kwargs) - # pandas\core\generic.py:10801: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.std = std # type: ignore[assignment] @doc( @@ -10658,8 +10651,7 @@ def std( def cummin(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cummin(self, axis, skipna, *args, **kwargs) - # pandas\core\generic.py:10815: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.cummin = cummin # type: ignore[assignment] @doc( @@ -10674,8 +10666,7 @@ def cummin(self, axis=None, skipna=True, *args, **kwargs): def cummax(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cummax(self, axis, skipna, *args, **kwargs) - # pandas\core\generic.py:10829: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.cummax = cummax # type: ignore[assignment] @doc( @@ -10690,8 +10681,7 @@ def cummax(self, axis=None, skipna=True, *args, **kwargs): def cumsum(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) - # pandas\core\generic.py:10843: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.cumsum = cumsum # type: ignore[assignment] @doc( @@ -10706,8 +10696,7 @@ def cumsum(self, axis=None, skipna=True, *args, **kwargs): def cumprod(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cumprod(self, axis, skipna, *args, **kwargs) - # pandas\core\generic.py:10857: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.cumprod = cumprod # type: ignore[assignment] @doc( @@ -10734,8 +10723,7 @@ def sum( self, axis, skipna, level, numeric_only, min_count, **kwargs ) - # pandas\core\generic.py:10883: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.sum = sum # type: ignore[assignment] @doc( @@ -10761,8 +10749,7 @@ def prod( self, axis, skipna, level, numeric_only, min_count, **kwargs ) - # pandas\core\generic.py:10908: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.prod = prod # type: ignore[assignment] cls.product = prod @@ -10779,8 +10766,7 @@ def prod( def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs) - # pandas\core\generic.py:10924: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.mean = mean # type: ignore[assignment] @doc( @@ -10796,8 +10782,7 @@ def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.skew(self, axis, skipna, level, numeric_only, **kwargs) - # pandas\core\generic.py:10939: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.skew = skew # type: ignore[assignment] @doc( @@ -10816,8 +10801,7 @@ def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def kurt(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.kurt(self, axis, skipna, level, numeric_only, **kwargs) - # pandas\core\generic.py:10957: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.kurt = kurt # type: ignore[assignment] cls.kurtosis = kurt @@ -10836,8 +10820,7 @@ def median( ): return NDFrame.median(self, axis, skipna, level, numeric_only, **kwargs) - # pandas\core\generic.py:10975: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.median = median # type: ignore[assignment] @doc( @@ -10855,8 +10838,7 @@ def median( def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.max(self, axis, skipna, level, numeric_only, **kwargs) - # pandas\core\generic.py:10992: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.max = max # type: ignore[assignment] @doc( @@ -10874,8 +10856,7 @@ def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.min(self, axis, skipna, level, numeric_only, **kwargs) - # pandas\core\generic.py:11009: error: Cannot assign to a method - # [assignment] + # error: Cannot assign to a method cls.min = min # type: ignore[assignment] @final diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 594c5899209df..9f1446b359f66 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -57,8 +57,7 @@ def _gotitem(self, key, ndim, subset=None): """ # create a new object to prevent aliasing if subset is None: - # pandas\core\groupby\base.py:52: error: "GotItemMixin" has no - # attribute "obj" [attr-defined] + # error: "GotItemMixin" has no attribute "obj" subset = self.obj # type: ignore[attr-defined] # we need to make a shallow copy of ourselves @@ -70,22 +69,15 @@ def _gotitem(self, key, ndim, subset=None): # Try to select from a DataFrame, falling back to a Series try: - # pandas\core\groupby\base.py:60: error: "GotItemMixin" has no - # attribute "_groupby" [attr-defined] + # error: "GotItemMixin" has no attribute "_groupby" groupby = self._groupby[key] # type: ignore[attr-defined] except IndexError: - # pandas\core\groupby\base.py:62: error: "GotItemMixin" has no - # attribute "_groupby" [attr-defined] + # error: "GotItemMixin" has no attribute "_groupby" groupby = self._groupby # type: ignore[attr-defined] - # pandas\core\groupby\base.py:64: error: Too many arguments for - # "GotItemMixin" [call-arg] - - # pandas\core\groupby\base.py:64: error: Unexpected keyword argument - # "groupby" for "GotItemMixin" [call-arg] - - # pandas\core\groupby\base.py:64: error: Unexpected keyword argument - # "parent" for "GotItemMixin" [call-arg] + # error: Too many arguments for "GotItemMixin" + # error: Unexpected keyword argument "groupby" for "GotItemMixin" + # error: Unexpected keyword argument "parent" for "GotItemMixin" self = type(self)( subset, groupby=groupby, parent=self, **kwargs # type: ignore[call-arg] ) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index a7297923f1034..9369dc61ca5f6 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -46,6 +46,7 @@ ensure_platform_int, is_bool, is_categorical_dtype, + is_dict_like, is_integer_dtype, is_interval_dtype, is_numeric_dtype, @@ -580,6 +581,12 @@ def filter(self, func, dropna=True, *args, **kwargs): dropna : Drop groups that do not pass the filter. True by default; if False, groups that evaluate False are filled with NaNs. + Notes + ----- + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`udf-mutation` + for more details. + Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', @@ -962,8 +969,8 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) func = maybe_mangle_lambdas(func) op = GroupByApply(self, func, args, kwargs) - result, how = op.agg() - if how is None: + result = op.agg() + if not is_dict_like(func) and result is not None: return result if result is None: @@ -982,7 +989,7 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) # try to treat as if we are passing a list try: - result, _ = GroupByApply( + result = GroupByApply( self, [func], args=(), kwargs={"_axis": self.axis} ).agg() @@ -1506,6 +1513,10 @@ def filter(self, func, dropna=True, *args, **kwargs): Each subframe is endowed the attribute 'name' in case you need to know which group you are working on. + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`udf-mutation` + for more details. + Examples -------- >>> df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 5758762c13984..66e7bc78b2f81 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -344,7 +344,7 @@ class providing the base-class of operations. in the subframe. If f also supports application to the entire subframe, then a fast path is used starting from the second chunk. * f must not mutate groups. Mutation is not supported and may - produce unexpected results. + produce unexpected results. See :ref:`udf-mutation` for more details. When using ``engine='numba'``, there will be no "fall back" behavior internally. The group data and group index will be passed as numpy arrays to the JITed @@ -447,6 +447,10 @@ class providing the base-class of operations. The group data and group index will be passed as numpy arrays to the JITed user defined function, and no alternative execution attempts will be tried. {examples} + +Functions that mutate the passed object can produce unexpected +behavior or errors and are not supported. See :ref:`udf-mutation` +for more details. """ diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index c7dc6d021a4c3..6a789bc26cabc 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -281,9 +281,8 @@ def _get_grouper(self, obj, validate: bool = True): a tuple of binner, grouper, obj (possibly sorted) """ self._set_grouper(obj) - # pandas\core\groupby\grouper.py:310: error: Value of type variable - # "FrameOrSeries" of "get_grouper" cannot be "Optional[Any]" - # [type-var] + # error: Value of type variable "FrameOrSeries" of "get_grouper" cannot be + # "Optional[Any]" self.grouper, _, self.obj = get_grouper( # type: ignore[type-var] self.obj, [self.key], @@ -370,8 +369,7 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): @final @property def groups(self): - # pandas\core\groupby\grouper.py:382: error: Item "None" of - # "Optional[Any]" has no attribute "groups" [union-attr] + # error: Item "None" of "Optional[Any]" has no attribute "groups" return self.grouper.groups # type: ignore[union-attr] @final diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 789ca04b894cd..f12a4fd382e7a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6071,14 +6071,14 @@ def ensure_index( if hasattr(index_like, "name"): # https://github.com/python/mypy/issues/1424 # error: Item "ExtensionArray" of "Union[ExtensionArray, - # Sequence[Any]]" has no attribute "name" [union-attr] + # Sequence[Any]]" has no attribute "name" # error: Item "Sequence[Any]" of "Union[ExtensionArray, Sequence[Any]]" - # has no attribute "name" [union-attr] - # error: "Sequence[Any]" has no attribute "name" [attr-defined] + # has no attribute "name" + # error: "Sequence[Any]" has no attribute "name" # error: Item "Sequence[Any]" of "Union[Series, Sequence[Any]]" has no - # attribute "name" [union-attr] + # attribute "name" # error: Item "Sequence[Any]" of "Union[Any, Sequence[Any]]" has no - # attribute "name" [union-attr] + # attribute "name" name = index_like.name # type: ignore[union-attr, attr-defined] return Index(index_like, name=name, copy=copy) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 265170dd28a3b..7e6d7d911b065 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -318,8 +318,7 @@ def _format_attrs(self): "categories", ibase.default_pprint(self.categories, max_seq_items=max_categories), ), - # pandas\core\indexes\category.py:315: error: "CategoricalIndex" - # has no attribute "ordered" [attr-defined] + # error: "CategoricalIndex" has no attribute "ordered" ("ordered", self.ordered), # type: ignore[attr-defined] ] if self.name is not None: diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 00f47c0aaf538..2e6519a3b73ad 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -714,7 +714,7 @@ def _intersection(self, other: Index, sort=False) -> Index: left_chunk = left._values[lslice] # error: Argument 1 to "_simple_new" of "DatetimeIndexOpsMixin" has # incompatible type "Union[ExtensionArray, Any]"; expected - # "Union[DatetimeArray, TimedeltaArray, PeriodArray]" [arg-type] + # "Union[DatetimeArray, TimedeltaArray, PeriodArray]" result = type(self)._simple_new(left_chunk) # type: ignore[arg-type] return self._wrap_setop_result(other, result) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index ea3678a7e15d9..a0e783a74df3c 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -226,8 +226,8 @@ def __getitem__(self, key): if result.ndim == 1: return type(self)(result, name=self.name) # Unpack to ndarray for MPL compat - # pandas\core\indexes\extension.py:220: error: "ExtensionArray" has - # no attribute "_data" [attr-defined] + + # error: "ExtensionArray" has no attribute "_data" result = result._data # type: ignore[attr-defined] # Includes cases where we get a 2D ndarray back for MPL compat diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index af353cf3fb5f7..70adcd841a57d 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -533,6 +533,10 @@ def _maybe_convert_i8(self, key): key_dtype, key_i8 = infer_dtype_from_scalar(key, pandas_dtype=True) if lib.is_period(key): key_i8 = key.ordinal + elif isinstance(key_i8, Timestamp): + key_i8 = key_i8.value + elif isinstance(key_i8, (np.datetime64, np.timedelta64)): + key_i8 = key_i8.view("i8") else: # DatetimeIndex/TimedeltaIndex key_dtype, key_i8 = key.dtype, Index(key.asi8) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 26d59db1b08fd..1fdffcf8e5980 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1448,8 +1448,7 @@ def _set_names(self, names, level=None, validate=True): raise TypeError( f"{type(self).__name__}.name must be a hashable type" ) - # pandas\core\indexes\multi.py:1448: error: Cannot determine type - # of '__setitem__' [has-type] + # error: Cannot determine type of '__setitem__' self._names[lev] = name # type: ignore[has-type] # If .levels has been accessed, the names in our cache will be stale. diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index a9561cc477d4a..9664f41362c8a 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -166,21 +166,21 @@ def to_timestamp(self, freq=None, how="start") -> DatetimeIndex: return DatetimeIndex._simple_new(arr, name=self.name) # https://github.com/python/mypy/issues/1362 - # error: Decorated property not supported [misc] + # error: Decorated property not supported @property # type:ignore[misc] @doc(PeriodArray.hour.fget) def hour(self) -> Int64Index: return Int64Index(self._data.hour, name=self.name) # https://github.com/python/mypy/issues/1362 - # error: Decorated property not supported [misc] + # error: Decorated property not supported @property # type:ignore[misc] @doc(PeriodArray.minute.fget) def minute(self) -> Int64Index: return Int64Index(self._data.minute, name=self.name) # https://github.com/python/mypy/issues/1362 - # error: Decorated property not supported [misc] + # error: Decorated property not supported @property # type:ignore[misc] @doc(PeriodArray.second.fget) def second(self) -> Int64Index: diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index a8493e647f39a..083f32488acd4 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -659,24 +659,53 @@ def idelete(self, indexer): 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 + Set new column(s). + + This changes the ArrayManager in-place, but replaces (an) existing + column(s), not changing column values in-place). + + Parameters + ---------- + loc : integer, slice or boolean mask + Positional location (already bounds checked) + value : array-like """ + # single column -> single integer index if lib.is_integer(loc): - # TODO normalize array -> this should in theory not be needed? + # TODO the extract array should in theory not be needed? value = extract_array(value, extract_numpy=True) + + # TODO can we avoid needing to unpack this here? That means converting + # DataFrame into 1D array when loc is an integer if isinstance(value, np.ndarray) and value.ndim == 2: + assert value.shape[1] == 1 value = value[0, :] assert isinstance(value, (np.ndarray, ExtensionArray)) - # value = np.asarray(value) - # assert isinstance(value, np.ndarray) + assert value.ndim == 1 assert len(value) == len(self._axes[0]) self.arrays[loc] = value return - # TODO - raise Exception + # multiple columns -> convert slice or array to integer indices + elif isinstance(loc, slice): + indices = range( + loc.start if loc.start is not None else 0, + loc.stop if loc.stop is not None else self.shape_proper[1], + loc.step if loc.step is not None else 1, + ) + else: + assert isinstance(loc, np.ndarray) + assert loc.dtype == "bool" + indices = np.nonzero(loc)[0] + + assert value.ndim == 2 + assert value.shape[0] == len(self._axes[0]) + + for value_idx, mgr_idx in enumerate(indices): + value_arr = value[:, value_idx] + self.arrays[mgr_idx] = value_arr + return def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False): """ diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8ba6018e743bb..06bf2e5d7b18e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -8,6 +8,7 @@ from pandas._libs import ( Interval, + NaT, Period, Timestamp, algos as libalgos, @@ -32,14 +33,11 @@ soft_convert_objects, ) from pandas.core.dtypes.common import ( - DT64NS_DTYPE, - TD64NS_DTYPE, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, is_dtype_equal, is_extension_array_dtype, - is_integer, is_list_like, is_object_dtype, is_sparse, @@ -144,7 +142,8 @@ def __init__(self, values, placement, ndim: int): f"placement implies {len(self.mgr_locs)}" ) - def _maybe_coerce_values(self, values): + @classmethod + def _maybe_coerce_values(cls, values): """ Ensure we have correctly-typed values. @@ -442,8 +441,7 @@ def fillna( if self._can_hold_element(value): nb = self if inplace else self.copy() putmask_inplace(nb.values, mask, value) - # TODO: should be nb._maybe_downcast? - return self._maybe_downcast([nb], downcast) + return nb._maybe_downcast([nb], downcast) if noop: # we can't process the value, but nothing to do @@ -722,6 +720,9 @@ def copy(self, deep: bool = True): values = values.copy() return self.make_block_same_class(values, ndim=self.ndim) + # --------------------------------------------------------------------- + # Replace + def replace( self, to_replace, @@ -872,6 +873,57 @@ def _replace_list( rb = new_rb return rb + def _replace_coerce( + self, + to_replace, + value, + mask: np.ndarray, + inplace: bool = True, + regex: bool = False, + ) -> List[Block]: + """ + Replace value corresponding to the given boolean array with another + value. + + Parameters + ---------- + to_replace : object or pattern + Scalar to replace or regular expression to match. + value : object + Replacement object. + mask : np.ndarray[bool] + True indicate corresponding element is ignored. + inplace : bool, default True + Perform inplace modification. + regex : bool, default False + If true, perform regular expression substitution. + + Returns + ------- + List[Block] + """ + if mask.any(): + if not regex: + nb = self.coerce_to_target_dtype(value) + if nb is self and not inplace: + nb = nb.copy() + putmask_inplace(nb.values, mask, value) + return [nb] + else: + regex = should_use_regex(regex, to_replace) + if regex: + return self._replace_regex( + to_replace, + value, + inplace=inplace, + convert=False, + mask=mask, + ) + return self.replace(to_replace, value, inplace=inplace, regex=False) + return [self] + + # --------------------------------------------------------------------- + def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. @@ -1402,55 +1454,6 @@ def quantile( return make_block(result, placement=self.mgr_locs, ndim=2) - def _replace_coerce( - self, - to_replace, - value, - mask: np.ndarray, - inplace: bool = True, - regex: bool = False, - ) -> List[Block]: - """ - Replace value corresponding to the given boolean array with another - value. - - Parameters - ---------- - to_replace : object or pattern - Scalar to replace or regular expression to match. - value : object - Replacement object. - mask : np.ndarray[bool] - True indicate corresponding element is ignored. - inplace : bool, default True - Perform inplace modification. - regex : bool, default False - If true, perform regular expression substitution. - - Returns - ------- - List[Block] - """ - if mask.any(): - if not regex: - nb = self.coerce_to_target_dtype(value) - if nb is self and not inplace: - nb = nb.copy() - putmask_inplace(nb.values, mask, value) - return [nb] - else: - regex = should_use_regex(regex, to_replace) - if regex: - return self._replace_regex( - to_replace, - value, - inplace=inplace, - convert=False, - mask=mask, - ) - return self.replace(to_replace, value, inplace=inplace, regex=False) - return [self] - class ExtensionBlock(Block): """ @@ -1543,7 +1546,8 @@ def putmask(self, mask, new) -> List[Block]: new_values[mask] = new return [self.make_block(values=new_values)] - def _maybe_coerce_values(self, values): + @classmethod + def _maybe_coerce_values(cls, values): """ Unbox to an extension array. @@ -1934,13 +1938,39 @@ def to_native_types( class DatetimeLikeBlockMixin(HybridMixin, Block): """Mixin class for DatetimeBlock, DatetimeTZBlock, and TimedeltaBlock.""" - @property - def _holder(self): - return DatetimeArray + _dtype: np.dtype + _holder: Type[Union[DatetimeArray, TimedeltaArray]] - @property - def fill_value(self): - return np.datetime64("NaT", "ns") + @classmethod + def _maybe_coerce_values(cls, values): + """ + Input validation for values passed to __init__. Ensure that + we have nanosecond datetime64/timedelta64, coercing if necessary. + + Parameters + ---------- + values : array-like + Must be convertible to datetime64/timedelta64 + + Returns + ------- + values : ndarray[datetime64ns/timedelta64ns] + + Overridden by DatetimeTZBlock. + """ + if values.dtype != cls._dtype: + # non-nano we will convert to nano + if values.dtype.kind != cls._dtype.kind: + # caller is responsible for ensuring td64/dt64 dtype + raise TypeError(values.dtype) # pragma: no cover + + values = cls._holder._from_sequence(values)._data + + if isinstance(values, cls._holder): + values = values._data + + assert isinstance(values, np.ndarray), type(values) + return values def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: """ @@ -2036,36 +2066,14 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: class DatetimeBlock(DatetimeLikeBlockMixin): __slots__ = () is_datetime = True + fill_value = np.datetime64("NaT", "ns") + _dtype = fill_value.dtype + _holder = DatetimeArray @property def _can_hold_na(self): return True - def _maybe_coerce_values(self, values): - """ - Input validation for values passed to __init__. Ensure that - we have datetime64ns, coercing if necessary. - - Parameters - ---------- - values : array-like - Must be convertible to datetime64 - - Returns - ------- - values : ndarray[datetime64ns] - - Overridden by DatetimeTZBlock. - """ - if values.dtype != DT64NS_DTYPE: - values = conversion.ensure_datetime64ns(values) - - if isinstance(values, DatetimeArray): - values = values._data - - assert isinstance(values, np.ndarray), type(values) - return values - def set_inplace(self, locs, values): """ See Block.set.__doc__ @@ -2084,21 +2092,20 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): is_datetimetz = True is_extension = True + _holder = DatetimeArray + internal_values = Block.internal_values _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types diff = DatetimeBlock.diff - fill_value = np.datetime64("NaT", "ns") + fill_value = NaT where = DatetimeBlock.where putmask = DatetimeLikeBlockMixin.putmask array_values = ExtensionBlock.array_values - @property - def _holder(self): - return DatetimeArray - - def _maybe_coerce_values(self, values): + @classmethod + def _maybe_coerce_values(cls, values): """ Input validation for values passed to __init__. Ensure that we have datetime64TZ, coercing if necessary. @@ -2112,8 +2119,8 @@ def _maybe_coerce_values(self, values): ------- values : DatetimeArray """ - if not isinstance(values, self._holder): - values = self._holder(values) + if not isinstance(values, cls._holder): + values = cls._holder(values) if values.tz is None: raise ValueError("cannot create a DatetimeTZBlock without a tz") @@ -2160,10 +2167,8 @@ def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: def external_values(self): # NB: this is different from np.asarray(self.values), since that # return an object-dtype ndarray of Timestamps. - if self.is_datetimetz: - # avoid FutureWarning in .astype in casting from dt64t to dt64 - return self.values._data - return np.asarray(self.values.astype("datetime64[ns]", copy=False)) + # avoid FutureWarning in .astype in casting from dt64t to dt64 + return self.values._data def fillna( self, value, limit=None, inplace: bool = False, downcast=None @@ -2206,38 +2211,17 @@ class TimeDeltaBlock(DatetimeLikeBlockMixin): is_timedelta = True _can_hold_na = True is_numeric = False + _holder = TimedeltaArray fill_value = np.timedelta64("NaT", "ns") - - def _maybe_coerce_values(self, values): - if values.dtype != TD64NS_DTYPE: - # non-nano we will convert to nano - if values.dtype.kind != "m": - # caller is responsible for ensuring timedelta64 dtype - raise TypeError(values.dtype) # pragma: no cover - - values = TimedeltaArray._from_sequence(values)._data - if isinstance(values, TimedeltaArray): - values = values._data - assert isinstance(values, np.ndarray), type(values) - return values - - @property - def _holder(self): - return TimedeltaArray + _dtype = fill_value.dtype def fillna( self, value, limit=None, inplace: bool = False, downcast=None ) -> List[Block]: - # TODO(EA2D): if we operated on array_values, TDA.fillna would handle - # raising here. - if is_integer(value): - # Deprecation GH#24694, GH#19233 - raise TypeError( - "Passing integers to fillna for timedelta64[ns] dtype is no " - "longer supported. To obtain the old behavior, pass " - "`pd.Timedelta(seconds=n)` instead." - ) - return super().fillna(value, limit=limit, inplace=inplace, downcast=downcast) + values = self.array_values() + values = values if inplace else values.copy() + new_values = values.fillna(value=value, limit=limit) + return [self.make_block_same_class(values=new_values)] class ObjectBlock(Block): @@ -2245,7 +2229,8 @@ class ObjectBlock(Block): is_object = True _can_hold_na = True - def _maybe_coerce_values(self, values): + @classmethod + def _maybe_coerce_values(cls, values): if issubclass(values.dtype.type, str): values = np.array(values, dtype=object) return values @@ -2475,6 +2460,7 @@ def _block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. + # error: "ExtensionArray" has no attribute "reshape" values = values.reshape(tuple((1,) + shape)) # type: ignore[attr-defined] return values diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 1c45b39ba990a..ccac2696b34c5 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1140,8 +1140,7 @@ def insert(self, loc: int, item: Hashable, value, allow_duplicates: bool = False if value.ndim == 2: value = value.T - - if value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype): + elif value.ndim == self.ndim - 1 and not is_extension_array_dtype(value.dtype): # TODO(EA2D): special case not needed with 2D EAs value = safe_reshape(value, (1,) + value.shape) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 68f791ac0a837..670c2f9f6da6c 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -96,9 +96,8 @@ def __init__(self, obj, groupby=None, axis=0, kind=None, **kwargs): self.as_index = True self.exclusions = set() self.binner = None - # pandas\core\resample.py:96: error: Incompatible types in assignment - # (expression has type "None", variable has type "BaseGrouper") - # [assignment] + # error: Incompatible types in assignment (expression has type "None", variable + # has type "BaseGrouper") self.grouper = None # type: ignore[assignment] if self.groupby is not None: @@ -301,7 +300,7 @@ def pipe( def aggregate(self, func, *args, **kwargs): self._set_binner() - result, how = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() + result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() if result is None: how = func grouper = None @@ -419,8 +418,7 @@ def _apply_loffset(self, result): result : Series or DataFrame the result of resample """ - # pandas\core\resample.py:409: error: Cannot determine type of - # 'loffset' [has-type] + # error: Cannot determine type of 'loffset' needs_offset = ( isinstance( self.loffset, # type: ignore[has-type] @@ -431,8 +429,7 @@ def _apply_loffset(self, result): ) if needs_offset: - # pandas\core\resample.py:415: error: Cannot determine type of - # 'loffset' [has-type] + # error: Cannot determine type of 'loffset' result.index = result.index + self.loffset # type: ignore[has-type] self.loffset = None @@ -869,8 +866,7 @@ def std(self, ddof=1, *args, **kwargs): Standard deviation of values within each group. """ nv.validate_resampler_func("std", args, kwargs) - # pandas\core\resample.py:850: error: Unexpected keyword argument - # "ddof" for "_downsample" [call-arg] + # error: Unexpected keyword argument "ddof" for "_downsample" return self._downsample("std", ddof=ddof) # type: ignore[call-arg] def var(self, ddof=1, *args, **kwargs): @@ -888,8 +884,7 @@ def var(self, ddof=1, *args, **kwargs): Variance of values within each group. """ nv.validate_resampler_func("var", args, kwargs) - # pandas\core\resample.py:867: error: Unexpected keyword argument - # "ddof" for "_downsample" [call-arg] + # error: Unexpected keyword argument "ddof" for "_downsample" return self._downsample("var", ddof=ddof) # type: ignore[call-arg] @doc(GroupBy.size) @@ -948,11 +943,8 @@ def quantile(self, q=0.5, **kwargs): Return a DataFrame, where the coulmns are groupby columns, and the values are its quantiles. """ - # pandas\core\resample.py:920: error: Unexpected keyword argument "q" - # for "_downsample" [call-arg] - - # pandas\core\resample.py:920: error: Too many arguments for - # "_downsample" [call-arg] + # error: Unexpected keyword argument "q" for "_downsample" + # error: Too many arguments for "_downsample" return self._downsample("quantile", q=q, **kwargs) # type: ignore[call-arg] @@ -1005,8 +997,7 @@ def __init__(self, obj, *args, **kwargs): for attr in self._attributes: setattr(self, attr, kwargs.get(attr, getattr(parent, attr))) - # pandas\core\resample.py:972: error: Too many arguments for "__init__" - # of "object" [call-arg] + # error: Too many arguments for "__init__" of "object" super().__init__(None) # type: ignore[call-arg] self._groupby = groupby self._groupby.mutated = True @@ -1070,8 +1061,8 @@ def _downsample(self, how, **kwargs): return obj # do we have a regular frequency - # pandas\core\resample.py:1037: error: "BaseGrouper" has no - # attribute "binlabels" [attr-defined] + + # error: "BaseGrouper" has no attribute "binlabels" if ( (ax.freq is not None or ax.inferred_freq is not None) and len(self.grouper.binlabels) > len(ax) # type: ignore[attr-defined] diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 8704d757c3289..963d071dc2768 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -996,9 +996,8 @@ def _get_merge_keys(self): """ left_keys = [] right_keys = [] - # pandas\core\reshape\merge.py:966: error: Need type annotation for - # 'join_names' (hint: "join_names: List[<type>] = ...") - # [var-annotated] + # error: Need type annotation for 'join_names' (hint: "join_names: List[<type>] + # = ...") join_names = [] # type: ignore[var-annotated] right_drop = [] left_drop = [] diff --git a/pandas/core/series.py b/pandas/core/series.py index 7d97c9f6189f3..c98fc98db5116 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3973,7 +3973,7 @@ def aggregate(self, func=None, axis=0, *args, **kwargs): func = dict(kwargs.items()) op = series_apply(self, func, args=args, kwargs=kwargs) - result, how = op.agg() + result = op.agg() if result is None: # we can be called from an inner function which @@ -4044,6 +4044,12 @@ def apply( Series.agg: Only perform aggregating type operations. Series.transform: Only perform transforming type operations. + Notes + ----- + Functions that mutate the passed object can produce unexpected + behavior or errors and are not supported. See :ref:`udf-mutation` + for more details. + Examples -------- Create a series with typical summer temperatures for each city. diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index ad2eafe7295b0..49eb87a3bc8ba 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -41,6 +41,10 @@ ----- `agg` is an alias for `aggregate`. Use the alias. +Functions that mutate the passed object can produce unexpected +behavior or errors and are not supported. See :ref:`udf-mutation` +for more details. + A passed user-defined-function will be passed a Series for evaluation. {examples}""" @@ -296,6 +300,12 @@ {klass}.agg : Only perform aggregating type operations. {klass}.apply : Invoke function on a {klass}. +Notes +----- +Functions that mutate the passed object can produce unexpected +behavior or errors and are not supported. See :ref:`udf-mutation` +for more details. + Examples -------- >>> df = pd.DataFrame({{'A': range(3), 'B': range(1, 4)}}) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b5714dbcd9e91..1538975b260c0 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -510,7 +510,7 @@ def calc(x): return self._apply_tablewise(homogeneous_func, name) def aggregate(self, func, *args, **kwargs): - result, how = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() + result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() if result is None: return self.apply(func, raw=False, args=args, kwargs=kwargs) return result @@ -994,7 +994,7 @@ def calc(x): axis="", ) def aggregate(self, func, *args, **kwargs): - result, how = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() + result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() if result is None: # these must apply directly diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index f12a530ea6c34..8902d45144c56 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -893,8 +893,8 @@ def check_extension(cls, ext: str): """ if ext.startswith("."): ext = ext[1:] - # error: "Callable[[ExcelWriter], Any]" has no attribute "__iter__" - # (not iterable) [attr-defined] + # error: "Callable[[ExcelWriter], Any]" has no attribute "__iter__" (not + # iterable) if not any( ext in extension for extension in cls.supported_extensions # type: ignore[attr-defined] diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 3a753a707166e..15f49660dc6dc 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -1,13 +1,12 @@ from __future__ import annotations -from distutils.version import LooseVersion import mmap from typing import TYPE_CHECKING, Dict, List, Optional import numpy as np from pandas._typing import FilePathOrBuffer, Scalar, StorageOptions -from pandas.compat._optional import get_version, import_optional_dependency +from pandas.compat._optional import import_optional_dependency from pandas.io.excel._base import BaseExcelReader, ExcelWriter from pandas.io.excel._util import validate_freeze_panes @@ -509,40 +508,20 @@ def get_sheet_by_index(self, index: int): def _convert_cell(self, cell, convert_float: bool) -> Scalar: - from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC + from openpyxl.cell.cell import TYPE_ERROR, TYPE_NUMERIC if cell.value is None: return "" # compat with xlrd - elif cell.is_date: - return cell.value elif cell.data_type == TYPE_ERROR: return np.nan - elif cell.data_type == TYPE_BOOL: - return bool(cell.value) - elif cell.data_type == TYPE_NUMERIC: - # GH5394 - if convert_float: - val = int(cell.value) - if val == cell.value: - return val - else: - return float(cell.value) + elif not convert_float and cell.data_type == TYPE_NUMERIC: + return float(cell.value) return cell.value def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: - # GH 39001 - # Reading of excel file depends on dimension data being correct but - # writers sometimes omit or get it wrong - import openpyxl - - version = LooseVersion(get_version(openpyxl)) - - # There is no good way of determining if a sheet is read-only - # https://foss.heptapod.net/openpyxl/openpyxl/-/issues/1605 - is_readonly = hasattr(sheet, "reset_dimensions") - if version >= "3.0.0" and is_readonly: + if self.book.read_only: sheet.reset_dimensions() data: List[List[Scalar]] = [] @@ -556,7 +535,7 @@ def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: # Trim trailing empty rows data = data[: last_row_with_data + 1] - if version >= "3.0.0" and is_readonly and len(data) > 0: + if self.book.read_only and len(data) > 0: # With dimension reset, openpyxl no longer pads rows max_width = max(len(data_row) for data_row in data) if min(len(data_row) for data_row in data) < max_width: diff --git a/pandas/io/formats/console.py b/pandas/io/formats/console.py index ea291bcbfa44c..bdd2b3d6e4c6a 100644 --- a/pandas/io/formats/console.py +++ b/pandas/io/formats/console.py @@ -69,8 +69,7 @@ def check_main(): return not hasattr(main, "__file__") or get_option("mode.sim_interactive") try: - # pandas\io\formats\console.py:72: error: Name '__IPYTHON__' is not - # defined [name-defined] + # error: Name '__IPYTHON__' is not defined return __IPYTHON__ or check_main() # type: ignore[name-defined] except NameError: return check_main() @@ -85,8 +84,7 @@ def in_ipython_frontend(): bool """ try: - # pandas\io\formats\console.py:86: error: Name 'get_ipython' is not - # defined [name-defined] + # error: Name 'get_ipython' is not defined ip = get_ipython() # type: ignore[name-defined] return "zmq" in str(type(ip)).lower() except NameError: diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index b027d8139f24b..099688b2449db 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -475,7 +475,7 @@ def __init__( if not len(Index(cols).intersection(df.columns)): raise KeyError("passes columns are not ALL present dataframe") - if len(Index(cols).intersection(df.columns)) != len(cols): + if len(Index(cols).intersection(df.columns)) != len(set(cols)): # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") @@ -613,9 +613,8 @@ def _format_header(self) -> Iterable[ExcelCell]: "" ] * len(self.columns) if reduce(lambda x, y: x and y, map(lambda x: x != "", row)): - # pandas\io\formats\excel.py:618: error: Incompatible types in - # assignment (expression has type "Generator[ExcelCell, None, - # None]", variable has type "Tuple[]") [assignment] + # error: Incompatible types in assignment (expression has type + # "Generator[ExcelCell, None, None]", variable has type "Tuple[]") gen2 = ( # type: ignore[assignment] ExcelCell(self.rowcounter, colindex, val, self.header_style) for colindex, val in enumerate(row) @@ -819,9 +818,8 @@ def write( if isinstance(writer, ExcelWriter): need_save = False else: - # pandas\io\formats\excel.py:808: error: Cannot instantiate - # abstract class 'ExcelWriter' with abstract attributes 'engine', - # 'save', 'supported_extensions' and 'write_cells' [abstract] + # error: Cannot instantiate abstract class 'ExcelWriter' with abstract + # attributes 'engine', 'save', 'supported_extensions' and 'write_cells' writer = ExcelWriter( # type: ignore[abstract] writer, engine=engine, storage_options=storage_options ) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 05d94366e6623..48b2fae8c6de5 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1347,11 +1347,9 @@ def _value_formatter( def base_formatter(v): assert float_format is not None # for mypy - # pandas\io\formats\format.py:1411: error: "str" not callable - # [operator] - - # pandas\io\formats\format.py:1411: error: Unexpected keyword - # argument "value" for "__call__" of "EngFormatter" [call-arg] + # error: "str" not callable + # error: Unexpected keyword argument "value" for "__call__" of + # "EngFormatter" return ( float_format(value=v) # type: ignore[operator,call-arg] if notna(v) diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 735fb345363c7..8322587a096d4 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -158,13 +158,12 @@ def __init__( uuid_len: int = 5, ): # validate ordered args - if not isinstance(data, (pd.Series, pd.DataFrame)): - raise TypeError("``data`` must be a Series or DataFrame") - if data.ndim == 1: + if isinstance(data, pd.Series): data = data.to_frame() + if not isinstance(data, DataFrame): + raise TypeError("``data`` must be a Series or DataFrame") if not data.index.is_unique or not data.columns.is_unique: raise ValueError("style is not supported for non-unique indices.") - assert isinstance(data, DataFrame) self.data: DataFrame = data self.index: pd.Index = data.index self.columns: pd.Index = data.columns @@ -1740,8 +1739,8 @@ def from_custom_template(cls, searchpath, name): loader = jinja2.ChoiceLoader([jinja2.FileSystemLoader(searchpath), cls.loader]) # mypy doesn't like dynamically-defined classes - # error: Variable "cls" is not valid as a type [valid-type] - # error: Invalid base class "cls" [misc] + # error: Variable "cls" is not valid as a type + # error: Invalid base class "cls" class MyStyler(cls): # type:ignore[valid-type,misc] env = jinja2.Environment(loader=loader) template = env.get_template(name) diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index d1d77c5e044be..27f06dc84a275 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -25,29 +25,23 @@ def __init__(self, src: FilePathOrBuffer, **kwds): for key in ("storage_options", "encoding", "memory_map", "compression"): kwds.pop(key, None) if self.handles.is_mmap and hasattr(self.handles.handle, "mmap"): - # pandas\io\parsers.py:1861: error: Item "IO[Any]" of - # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, - # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + # error: Item "IO[Any]" of "Union[IO[Any], RawIOBase, BufferedIOBase, + # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap" - # pandas\io\parsers.py:1861: error: Item "RawIOBase" of - # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, - # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + # error: Item "RawIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase, + # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap" - # pandas\io\parsers.py:1861: error: Item "BufferedIOBase" of - # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, - # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + # error: Item "BufferedIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase, + # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap" - # pandas\io\parsers.py:1861: error: Item "TextIOBase" of - # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, - # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + # error: Item "TextIOBase" of "Union[IO[Any], RawIOBase, BufferedIOBase, + # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap" - # pandas\io\parsers.py:1861: error: Item "TextIOWrapper" of - # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, - # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + # error: Item "TextIOWrapper" of "Union[IO[Any], RawIOBase, BufferedIOBase, + # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap" - # pandas\io\parsers.py:1861: error: Item "mmap" of "Union[IO[Any], - # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]" has - # no attribute "mmap" [union-attr] + # error: Item "mmap" of "Union[IO[Any], RawIOBase, BufferedIOBase, + # TextIOBase, TextIOWrapper, mmap]" has no attribute "mmap" self.handles.handle = self.handles.handle.mmap # type: ignore[union-attr] try: diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 223acdea80ca6..cfd648636753d 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -217,10 +217,9 @@ def _read(): reader = _read() - # pandas\io\parsers.py:2427: error: Incompatible types in assignment - # (expression has type "_reader", variable has type "Union[IO[Any], - # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap, None]") - # [assignment] + # error: Incompatible types in assignment (expression has type "_reader", + # variable has type "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap, None]") self.data = reader # type: ignore[assignment] def read(self, rows=None): @@ -278,8 +277,7 @@ def _exclude_implicit_index(self, alldata): # legacy def get_chunk(self, size=None): if size is None: - # pandas\io\parsers.py:2528: error: "PythonParser" has no attribute - # "chunksize" [attr-defined] + # error: "PythonParser" has no attribute "chunksize" size = self.chunksize # type: ignore[attr-defined] return self.read(rows=size) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 8917be1f558b2..077686d9bd642 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3410,8 +3410,8 @@ def queryables(self) -> Dict[str, Any]: (v.cname, v) for v in self.values_axes if v.name in set(self.data_columns) ] - # error: Unsupported operand types for + ("List[Tuple[str, IndexCol]]" - # and "List[Tuple[str, None]]") + # error: Unsupported operand types for + ("List[Tuple[str, IndexCol]]" and + # "List[Tuple[str, None]]") return dict(d1 + d2 + d3) # type: ignore[operator] def index_cols(self): diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 7d743075674f1..2b6dd5347c3e7 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -594,17 +594,14 @@ def _make_legend(self): if self.legend: if self.legend == "reverse": - # pandas\plotting\_matplotlib\core.py:578: error: - # Incompatible types in assignment (expression has type + # error: Incompatible types in assignment (expression has type # "Iterator[Any]", variable has type "List[Any]") - # [assignment] self.legend_handles = reversed( # type: ignore[assignment] self.legend_handles ) - # pandas\plotting\_matplotlib\core.py:579: error: - # Incompatible types in assignment (expression has type + # error: Incompatible types in assignment (expression has type # "Iterator[Optional[Hashable]]", variable has type - # "List[Optional[Hashable]]") [assignment] + # "List[Optional[Hashable]]") self.legend_labels = reversed( # type: ignore[assignment] self.legend_labels ) @@ -1149,10 +1146,9 @@ def _make_plot(self): it = self._iter_data(data=data, keep_index=True) else: x = self._get_xticks(convert_period=True) - # pandas\plotting\_matplotlib\core.py:1100: error: Incompatible - # types in assignment (expression has type "Callable[[Any, Any, - # Any, Any, Any, Any, KwArg(Any)], Any]", variable has type - # "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") [assignment] + # error: Incompatible types in assignment (expression has type + # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has + # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") plotf = self._plot # type: ignore[assignment] it = self._iter_data() @@ -1601,9 +1597,8 @@ def blank_labeler(label, value): if labels is not None: blabels = [blank_labeler(left, value) for left, value in zip(labels, y)] else: - # pandas\plotting\_matplotlib\core.py:1546: error: Incompatible - # types in assignment (expression has type "None", variable has - # type "List[Any]") [assignment] + # error: Incompatible types in assignment (expression has type "None", + # variable has type "List[Any]") blabels = None # type: ignore[assignment] results = ax.pie(y, labels=blabels, **kwds) diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 58f44104b99d6..e0a860b9d8709 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -530,8 +530,7 @@ def reset(self): ------- None """ - # pandas\plotting\_misc.py:533: error: Cannot access "__init__" - # directly [misc] + # error: Cannot access "__init__" directly self.__init__() # type: ignore[misc] def _get_canonical_key(self, key): diff --git a/pandas/tests/dtypes/cast/test_infer_dtype.py b/pandas/tests/dtypes/cast/test_infer_dtype.py index a47c5555d3e9f..2b18d110346e4 100644 --- a/pandas/tests/dtypes/cast/test_infer_dtype.py +++ b/pandas/tests/dtypes/cast/test_infer_dtype.py @@ -105,13 +105,11 @@ def test_infer_from_scalar_tz(tz, pandas_dtype): if pandas_dtype: exp_dtype = f"datetime64[ns, {tz}]" - exp_val = dt.value else: exp_dtype = np.object_ - exp_val = dt assert dtype == exp_dtype - assert val == exp_val + assert val == dt @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py index 08303fc601b3e..786944816bcf6 100644 --- a/pandas/tests/dtypes/cast/test_promote.py +++ b/pandas/tests/dtypes/cast/test_promote.py @@ -24,6 +24,7 @@ from pandas.core.dtypes.missing import isna import pandas as pd +import pandas._testing as tm @pytest.fixture( @@ -403,7 +404,13 @@ def test_maybe_promote_any_with_datetime64( expected_dtype = np.dtype(object) exp_val_for_scalar = fill_value - _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar) + warn = None + if type(fill_value) is datetime.date and dtype.kind == "M": + # Casting date to dt64 is deprecated + warn = FutureWarning + + with tm.assert_produces_warning(warn, check_stacklevel=False): + _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar) @pytest.mark.parametrize( diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 0f4cef772458f..f3cb3f45a167f 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -55,6 +55,51 @@ from pandas.core.arrays import IntegerArray +class MockNumpyLikeArray: + """ + A class which is numpy-like (e.g. Pint's Quantity) but not actually numpy + The key is that it is not actually a numpy array so + ``util.is_array(mock_numpy_like_array_instance)`` returns ``False``. Other + important properties are that the class defines a :meth:`__iter__` method + (so that ``isinstance(abc.Iterable)`` returns ``True``) and has a + :meth:`ndim` property which can be used as a check for whether it is a + scalar or not. + """ + + def __init__(self, values): + self._values = values + + def __iter__(self): + iter_values = iter(self._values) + + def it_outer(): + yield from iter_values + + return it_outer() + + def __len__(self): + return len(self._values) + + def __array__(self, t=None): + return self._values + + @property + def ndim(self): + return self._values.ndim + + @property + def dtype(self): + return self._values.dtype + + @property + def size(self): + return self._values.size + + @property + def shape(self): + return self._values.shape + + @pytest.fixture(params=[True, False], ids=str) def coerce(request): return request.param @@ -94,6 +139,15 @@ def coerce(request): (np.ndarray((2,) * 4), True, "ndarray-4d"), (np.array([[[[]]]]), True, "ndarray-4d-empty"), (np.array(2), False, "ndarray-0d"), + (MockNumpyLikeArray(np.ndarray((2,) * 1)), True, "duck-ndarray-1d"), + (MockNumpyLikeArray(np.array([])), True, "duck-ndarray-1d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 2)), True, "duck-ndarray-2d"), + (MockNumpyLikeArray(np.array([[]])), True, "duck-ndarray-2d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 3)), True, "duck-ndarray-3d"), + (MockNumpyLikeArray(np.array([[[]]])), True, "duck-ndarray-3d-empty"), + (MockNumpyLikeArray(np.ndarray((2,) * 4)), True, "duck-ndarray-4d"), + (MockNumpyLikeArray(np.array([[[[]]]])), True, "duck-ndarray-4d-empty"), + (MockNumpyLikeArray(np.array(2)), False, "duck-ndarray-0d"), (1, False, "int"), (b"123", False, "bytes"), (b"", False, "bytes-empty"), @@ -154,6 +208,8 @@ def test_is_array_like(): assert inference.is_array_like(Series([1, 2])) assert inference.is_array_like(np.array(["a", "b"])) assert inference.is_array_like(Index(["2016-01-01"])) + assert inference.is_array_like(np.array([2, 3])) + assert inference.is_array_like(MockNumpyLikeArray(np.array([2, 3]))) class DtypeList(list): dtype = "special" diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py index 4282db6933371..7c48c412fd694 100644 --- a/pandas/tests/frame/indexing/test_getitem.py +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -10,6 +10,7 @@ MultiIndex, Series, Timestamp, + concat, get_dummies, period_range, ) @@ -176,6 +177,87 @@ def test_getitem_bool_mask_categorical_index(self): with pytest.raises(TypeError, match=msg): df4[df4.index > 1] + @pytest.mark.parametrize( + "data1,data2,expected_data", + ( + ( + [[1, 2], [3, 4]], + [[0.5, 6], [7, 8]], + [[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]], + ), + ( + [[1, 2], [3, 4]], + [[5, 6], [7, 8]], + [[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]], + ), + ), + ) + def test_getitem_bool_mask_duplicate_columns_mixed_dtypes( + self, + data1, + data2, + expected_data, + ): + # GH#31954 + + df1 = DataFrame(np.array(data1)) + df2 = DataFrame(np.array(data2)) + df = concat([df1, df2], axis=1) + + result = df[df > 2] + + exdict = {i: np.array(col) for i, col in enumerate(expected_data)} + expected = DataFrame(exdict).rename(columns={2: 0, 3: 1}) + tm.assert_frame_equal(result, expected) + + @pytest.fixture + def df_dup_cols(self): + dups = ["A", "A", "C", "D"] + df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") + return df + + def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self, df_dup_cols): + # `df.A > 6` is a DataFrame with a different shape from df + + # boolean with the duplicate raises + df = df_dup_cols + msg = "cannot reindex from a duplicate axis" + with pytest.raises(ValueError, match=msg): + df[df.A > 6] + + def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols): + # boolean indexing + # GH#4879 + df = DataFrame( + np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" + ) + expected = df[df.C > 6] + expected.columns = df_dup_cols.columns + + df = df_dup_cols + result = df[df.C > 6] + + tm.assert_frame_equal(result, expected) + result.dtypes + str(result) + + def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols): + + # where + df = DataFrame( + np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" + ) + # `df > 6` is a DataFrame with the same shape+alignment as df + expected = df[df > 6] + expected.columns = df_dup_cols.columns + + df = df_dup_cols + result = df[df > 6] + + tm.assert_frame_equal(result, expected) + result.dtypes + str(result) + class TestGetitemSlice: def test_getitem_slice_float64(self, frame_or_series): diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 9318764a1b5ad..4dfbc0b918aaa 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -2,18 +2,26 @@ import pytest from pandas.core.dtypes.base import registry as ea_registry +from pandas.core.dtypes.common import ( + is_categorical_dtype, + is_interval_dtype, + is_object_dtype, +) from pandas.core.dtypes.dtypes import DatetimeTZDtype, IntervalDtype, PeriodDtype from pandas import ( Categorical, DataFrame, + DatetimeIndex, Index, Interval, + IntervalIndex, NaT, Period, PeriodIndex, Series, Timestamp, + cut, date_range, notna, period_range, @@ -395,6 +403,90 @@ def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self): with pytest.raises(ValueError, match=msg): df[["a", "b"]] = rhs + def test_setitem_intervals(self): + + df = DataFrame({"A": range(10)}) + ser = cut(df["A"], 5) + assert isinstance(ser.cat.categories, IntervalIndex) + + # B & D end up as Categoricals + # the remainer are converted to in-line objects + # contining an IntervalIndex.values + df["B"] = ser + df["C"] = np.array(ser) + df["D"] = ser.values + df["E"] = np.array(ser.values) + + assert is_categorical_dtype(df["B"].dtype) + assert is_interval_dtype(df["B"].cat.categories) + assert is_categorical_dtype(df["D"].dtype) + assert is_interval_dtype(df["D"].cat.categories) + + assert is_object_dtype(df["C"]) + assert is_object_dtype(df["E"]) + + # they compare equal as Index + # when converted to numpy objects + c = lambda x: Index(np.array(x)) + tm.assert_index_equal(c(df.B), c(df.B)) + tm.assert_index_equal(c(df.B), c(df.C), check_names=False) + tm.assert_index_equal(c(df.B), c(df.D), check_names=False) + tm.assert_index_equal(c(df.C), c(df.D), check_names=False) + + # B & D are the same Series + tm.assert_series_equal(df["B"], df["B"]) + tm.assert_series_equal(df["B"], df["D"], check_names=False) + + # C & E are the same Series + tm.assert_series_equal(df["C"], df["C"]) + tm.assert_series_equal(df["C"], df["E"], check_names=False) + + +class TestSetitemTZAwareValues: + @pytest.fixture + def idx(self): + naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") + idx = naive.tz_localize("US/Pacific") + return idx + + @pytest.fixture + def expected(self, idx): + expected = Series(np.array(idx.tolist(), dtype="object"), name="B") + assert expected.dtype == idx.dtype + return expected + + def test_setitem_dt64series(self, idx, expected): + # convert to utc + df = DataFrame(np.random.randn(2, 1), columns=["A"]) + df["B"] = idx + + with tm.assert_produces_warning(FutureWarning) as m: + df["B"] = idx.to_series(keep_tz=False, index=[0, 1]) + msg = "do 'idx.tz_convert(None)' before calling" + assert msg in str(m[0].message) + + result = df["B"] + comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B") + tm.assert_series_equal(result, comp) + + def test_setitem_datetimeindex(self, idx, expected): + # setting a DataFrame column with a tzaware DTI retains the dtype + df = DataFrame(np.random.randn(2, 1), columns=["A"]) + + # assign to frame + df["B"] = idx + result = df["B"] + tm.assert_series_equal(result, expected) + + def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected): + # setting a DataFrame column with a tzaware DTI retains the dtype + df = DataFrame(np.random.randn(2, 1), columns=["A"]) + + # object array of datetimes with a tz + df["B"] = idx.to_pydatetime() + result = df["B"] + tm.assert_series_equal(result, expected) + class TestDataFrameSetItemWithExpansion: def test_setitem_listlike_views(self): diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index e4e2656f4337c..5b7d096d0ab99 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -21,10 +21,69 @@ import pandas.core.common as com +class TestReindexSetIndex: + # Tests that check both reindex and set_index + + def test_dti_set_index_reindex_datetimeindex(self): + # GH#6631 + df = DataFrame(np.random.random(6)) + idx1 = date_range("2011/01/01", periods=6, freq="M", tz="US/Eastern") + idx2 = date_range("2013", periods=6, freq="A", tz="Asia/Tokyo") + + df = df.set_index(idx1) + tm.assert_index_equal(df.index, idx1) + df = df.reindex(idx2) + tm.assert_index_equal(df.index, idx2) + + def test_dti_set_index_reindex_freq_with_tz(self): + # GH#11314 with tz + index = date_range( + datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="H", tz="US/Eastern" + ) + df = DataFrame(np.random.randn(24, 1), columns=["a"], index=index) + new_index = date_range( + datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="H", tz="US/Eastern" + ) + + result = df.set_index(new_index) + assert result.index.freq == index.freq + + def test_set_reset_index_intervalindex(self): + + df = DataFrame({"A": range(10)}) + ser = pd.cut(df.A, 5) + df["B"] = ser + df = df.set_index("B") + + df = df.reset_index() + + class TestDataFrameSelectReindex: # These are specific reindex-based tests; other indexing tests should go in # test_indexing + def test_reindex_date_fill_value(self): + # passing date to dt64 is deprecated + arr = date_range("2016-01-01", periods=6).values.reshape(3, 2) + df = DataFrame(arr, columns=["A", "B"], index=range(3)) + + ts = df.iloc[0, 0] + fv = ts.date() + + with tm.assert_produces_warning(FutureWarning): + res = df.reindex(index=range(4), columns=["A", "B", "C"], fill_value=fv) + + expected = DataFrame( + {"A": df["A"].tolist() + [ts], "B": df["B"].tolist() + [ts], "C": [ts] * 4} + ) + tm.assert_frame_equal(res, expected) + + # same with a datetime-castable str + res = df.reindex( + index=range(4), columns=["A", "B", "C"], fill_value="2016-01-01" + ) + tm.assert_frame_equal(res, expected) + def test_reindex_with_multi_index(self): # https://github.com/pandas-dev/pandas/issues/29896 # tests for reindexing a multi-indexed DataFrame with a new MultiIndex diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py index b66a95bae51c5..70232dfd1d79a 100644 --- a/pandas/tests/frame/methods/test_set_index.py +++ b/pandas/tests/frame/methods/test_set_index.py @@ -1,3 +1,7 @@ +""" +See also: test_reindex.py:TestReindexSetIndex +""" + from datetime import datetime, timedelta import numpy as np diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 862f5b87785f5..c68171ab254c7 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -1,111 +1,13 @@ from datetime import datetime -import numpy as np -import pytest import pytz -from pandas.core.dtypes.common import ( - is_categorical_dtype, - is_interval_dtype, - is_object_dtype, -) - -from pandas import ( - DataFrame, - DatetimeIndex, - Index, - IntervalIndex, - Series, - Timestamp, - cut, - date_range, -) +from pandas import DataFrame import pandas._testing as tm class TestDataFrameAlterAxes: - @pytest.fixture - def idx_expected(self): - idx = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B").tz_localize( - "US/Pacific" - ) - - expected = Series( - np.array( - [ - Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), - Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), - ], - dtype="object", - ), - name="B", - ) - assert expected.dtype == idx.dtype - return idx, expected - - def test_to_series_keep_tz_deprecated_true(self, idx_expected): - # convert to series while keeping the timezone - idx, expected = idx_expected - - msg = "stop passing 'keep_tz'" - with tm.assert_produces_warning(FutureWarning) as m: - result = idx.to_series(keep_tz=True, index=[0, 1]) - assert msg in str(m[0].message) - - tm.assert_series_equal(result, expected) - - def test_to_series_keep_tz_deprecated_false(self, idx_expected): - idx, expected = idx_expected - - with tm.assert_produces_warning(FutureWarning) as m: - result = idx.to_series(keep_tz=False, index=[0, 1]) - tm.assert_series_equal(result, expected.dt.tz_convert(None)) - msg = "do 'idx.tz_convert(None)' before calling" - assert msg in str(m[0].message) - - def test_setitem_dt64series(self, idx_expected): - # convert to utc - idx, expected = idx_expected - df = DataFrame(np.random.randn(2, 1), columns=["A"]) - df["B"] = idx - - with tm.assert_produces_warning(FutureWarning) as m: - df["B"] = idx.to_series(keep_tz=False, index=[0, 1]) - msg = "do 'idx.tz_convert(None)' before calling" - assert msg in str(m[0].message) - - result = df["B"] - comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B") - tm.assert_series_equal(result, comp) - - def test_setitem_datetimeindex(self, idx_expected): - # setting a DataFrame column with a tzaware DTI retains the dtype - idx, expected = idx_expected - df = DataFrame(np.random.randn(2, 1), columns=["A"]) - - # assign to frame - df["B"] = idx - result = df["B"] - tm.assert_series_equal(result, expected) - - def test_setitem_object_array_of_tzaware_datetimes(self, idx_expected): - # setting a DataFrame column with a tzaware DTI retains the dtype - idx, expected = idx_expected - df = DataFrame(np.random.randn(2, 1), columns=["A"]) - - # object array of datetimes with a tz - df["B"] = idx.to_pydatetime() - result = df["B"] - tm.assert_series_equal(result, expected) - - def test_constructor_from_tzaware_datetimeindex(self, idx_expected): - # don't cast a DatetimeIndex WITH a tz, leave as object - # GH 6032 - idx, expected = idx_expected - - # convert index to series - result = Series(idx) - tm.assert_series_equal(result, expected) + # Tests for setting index/columns attributes directly (i.e. __setattr__) def test_set_axis_setattr_index(self): # GH 6785 @@ -117,31 +19,6 @@ def test_set_axis_setattr_index(self): df.pop("ts") tm.assert_frame_equal(df, expected) - def test_dti_set_index_reindex(self): - # GH 6631 - df = DataFrame(np.random.random(6)) - idx1 = date_range("2011/01/01", periods=6, freq="M", tz="US/Eastern") - idx2 = date_range("2013", periods=6, freq="A", tz="Asia/Tokyo") - - df = df.set_index(idx1) - tm.assert_index_equal(df.index, idx1) - df = df.reindex(idx2) - tm.assert_index_equal(df.index, idx2) - - def test_dti_set_index_reindex_with_tz(self): - # GH 11314 - # with tz - index = date_range( - datetime(2015, 10, 1), datetime(2015, 10, 1, 23), freq="H", tz="US/Eastern" - ) - df = DataFrame(np.random.randn(24, 1), columns=["a"], index=index) - new_index = date_range( - datetime(2015, 10, 2), datetime(2015, 10, 2, 23), freq="H", tz="US/Eastern" - ) - - result = df.set_index(new_index) - assert result.index.freq == index.freq - # Renaming def test_assign_columns(self, float_frame): @@ -151,52 +28,3 @@ def test_assign_columns(self, float_frame): df.columns = ["foo", "bar", "baz", "quux", "foo2"] tm.assert_series_equal(float_frame["C"], df["baz"], check_names=False) tm.assert_series_equal(float_frame["hi"], df["foo2"], check_names=False) - - -class TestIntervalIndex: - def test_setitem(self): - - df = DataFrame({"A": range(10)}) - ser = cut(df["A"], 5) - assert isinstance(ser.cat.categories, IntervalIndex) - - # B & D end up as Categoricals - # the remainer are converted to in-line objects - # contining an IntervalIndex.values - df["B"] = ser - df["C"] = np.array(ser) - df["D"] = ser.values - df["E"] = np.array(ser.values) - - assert is_categorical_dtype(df["B"].dtype) - assert is_interval_dtype(df["B"].cat.categories) - assert is_categorical_dtype(df["D"].dtype) - assert is_interval_dtype(df["D"].cat.categories) - - assert is_object_dtype(df["C"]) - assert is_object_dtype(df["E"]) - - # they compare equal as Index - # when converted to numpy objects - c = lambda x: Index(np.array(x)) - tm.assert_index_equal(c(df.B), c(df.B)) - tm.assert_index_equal(c(df.B), c(df.C), check_names=False) - tm.assert_index_equal(c(df.B), c(df.D), check_names=False) - tm.assert_index_equal(c(df.C), c(df.D), check_names=False) - - # B & D are the same Series - tm.assert_series_equal(df["B"], df["B"]) - tm.assert_series_equal(df["B"], df["D"], check_names=False) - - # C & E are the same Series - tm.assert_series_equal(df["C"], df["C"]) - tm.assert_series_equal(df["C"], df["E"], check_names=False) - - def test_set_reset_index(self): - - df = DataFrame({"A": range(10)}) - s = cut(df.A, 5) - df["B"] = s - df = df.set_index("B") - - df = df.reset_index() diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 9ec745932514f..5fcab5200e305 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -20,6 +20,7 @@ Categorical, CategoricalIndex, DataFrame, + DatetimeIndex, Index, Interval, MultiIndex, @@ -48,6 +49,19 @@ class TestDataFrameConstructors: + def test_constructor_from_tzaware_datetimeindex(self): + # don't cast a DatetimeIndex WITH a tz, leave as object + # GH#6032 + naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") + idx = naive.tz_localize("US/Pacific") + + expected = Series(np.array(idx.tolist(), dtype="object"), name="B") + assert expected.dtype == idx.dtype + + # convert index to series + result = Series(idx) + tm.assert_series_equal(result, expected) + def test_array_of_dt64_nat_with_td64dtype_raises(self, frame_or_series): # GH#39462 nat = np.datetime64("NaT", "ns") diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 8dcf6f2188058..1f892c3a03e85 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -33,6 +33,7 @@ def test_column_dups_operations(self): expected = DataFrame([[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=idx) check(df, expected) + def test_insert_with_duplicate_columns(self): # insert df = DataFrame( [[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], @@ -119,6 +120,7 @@ def test_column_dups_operations(self): ) tm.assert_frame_equal(df, expected) + def test_dup_across_dtypes(self): # dup across dtypes df = DataFrame( [[1, 1, 1.0, 5], [1, 1, 2.0, 5], [2, 1, 3.0, 5]], @@ -155,12 +157,14 @@ def test_column_dups_operations(self): ) check(df, expected) + def test_values_with_duplicate_columns(self): # values df = DataFrame([[1, 2.5], [3, 4.5]], index=[1, 2], columns=["x", "x"]) result = df.values expected = np.array([[1, 2.5], [3, 4.5]]) assert (result == expected).all().all() + def test_rename_with_duplicate_columns(self): # rename, GH 4403 df4 = DataFrame( {"RT": [0.0454], "TClose": [22.02], "TExg": [0.0422]}, @@ -201,6 +205,8 @@ def test_column_dups_operations(self): ).set_index(["STK_ID", "RPT_Date"], drop=False) tm.assert_frame_equal(result, expected) + def test_reindex_with_duplicate_columns(self): + # reindex is invalid! df = DataFrame( [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] @@ -211,6 +217,8 @@ def test_column_dups_operations(self): with pytest.raises(ValueError, match=msg): df.reindex(columns=["bar", "foo"]) + def test_drop_with_duplicate_columns(self): + # drop df = DataFrame( [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "a", "a"] @@ -221,6 +229,7 @@ def test_column_dups_operations(self): result = df.drop("a", axis=1) check(result, expected) + def test_describe_with_duplicate_columns(self): # describe df = DataFrame( [[1, 1, 1], [2, 2, 2], [3, 3, 3]], @@ -232,6 +241,7 @@ def test_column_dups_operations(self): expected = pd.concat([s, s, s], keys=df.columns, axis=1) check(result, expected) + def test_column_dups_indexes(self): # check column dups with index equal and not equal to df's index df = DataFrame( np.random.randn(5, 3), @@ -248,6 +258,8 @@ def test_column_dups_operations(self): this_df["A"] = index check(this_df, expected_df) + def test_arithmetic_with_dups(self): + # operations for op in ["__add__", "__mul__", "__sub__", "__truediv__"]: df = DataFrame({"A": np.arange(10), "B": np.random.rand(10)}) @@ -257,6 +269,7 @@ def test_column_dups_operations(self): result = getattr(df, op)(df) check(result, expected) + def test_changing_dtypes_with_duplicate_columns(self): # multiple assignments that change dtypes # the location indexer is a slice # GH 6120 @@ -272,7 +285,7 @@ def test_column_dups_operations(self): df["that"] = 1 check(df, expected) - def test_column_dups2(self): + def test_column_dups_drop(self): # drop buggy GH 6240 df = DataFrame( @@ -289,6 +302,7 @@ def test_column_dups2(self): result = df2.drop("C", axis=1) tm.assert_frame_equal(result, expected) + def test_column_dups_dropna(self): # dropna df = DataFrame( { @@ -310,43 +324,6 @@ def test_column_dups2(self): result = df.dropna(subset=["A", "C"], how="all") tm.assert_frame_equal(result, expected) - def test_getitem_boolean_series_with_duplicate_columns(self): - # boolean indexing - # GH 4879 - dups = ["A", "A", "C", "D"] - df = DataFrame( - np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" - ) - expected = df[df.C > 6] - expected.columns = dups - df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") - result = df[df.C > 6] - check(result, expected) - - def test_getitem_boolean_frame_with_duplicate_columns(self): - dups = ["A", "A", "C", "D"] - - # where - df = DataFrame( - np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" - ) - # `df > 6` is a DataFrame with the same shape+alignment as df - expected = df[df > 6] - expected.columns = dups - df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") - result = df[df > 6] - check(result, expected) - - def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self): - # `df.A > 6` is a DataFrame with a different shape from df - dups = ["A", "A", "C", "D"] - - # boolean with the duplicate raises - df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") - msg = "cannot reindex from a duplicate axis" - with pytest.raises(ValueError, match=msg): - df[df.A > 6] - def test_column_dups_indexing(self): # dup aligning operations should work @@ -357,6 +334,7 @@ def test_column_dups_indexing(self): result = df1.sub(df2) tm.assert_frame_equal(result, expected) + def test_dup_columns_comparisons(self): # equality df1 = DataFrame([[1, 2], [2, np.nan], [3, 4], [4, 4]], columns=["A", "B"]) df2 = DataFrame([[0, 1], [2, 4], [2, np.nan], [4, 5]], columns=["A", "A"]) @@ -374,6 +352,7 @@ def test_column_dups_indexing(self): ) tm.assert_frame_equal(result, expected) + def test_mixed_column_selection(self): # mixed column selection # GH 5639 dfbool = DataFrame( @@ -387,6 +366,7 @@ def test_column_dups_indexing(self): result = dfbool[["one", "three", "one"]] check(result, expected) + def test_multi_axis_dups(self): # multi-axis dups # GH 6121 df = DataFrame( @@ -422,6 +402,7 @@ def test_columns_with_dups(self): expected = DataFrame([[1, 2, 3]], columns=["b", "a", "a.1"]) tm.assert_frame_equal(df, expected) + def test_columns_with_dup_index(self): # with a dup index df = DataFrame([[1, 2]], columns=["a", "a"]) df.columns = ["b", "b"] @@ -429,6 +410,7 @@ def test_columns_with_dups(self): expected = DataFrame([[1, 2]], columns=["b", "b"]) tm.assert_frame_equal(df, expected) + def test_multi_dtype(self): # multi-dtype df = DataFrame( [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], @@ -441,12 +423,14 @@ def test_columns_with_dups(self): ) tm.assert_frame_equal(df, expected) + def test_multi_dtype2(self): df = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a", "a", "a"]) df.columns = ["a", "a.1", "a.2", "a.3"] str(df) expected = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a.1", "a.2", "a.3"]) tm.assert_frame_equal(df, expected) + def test_dups_across_blocks(self): # dups across blocks df_float = DataFrame(np.random.randn(10, 3), dtype="float64") df_int = DataFrame(np.random.randn(10, 3), dtype="int64") @@ -464,6 +448,7 @@ def test_columns_with_dups(self): for i in range(len(df.columns)): df.iloc[:, i] + def test_dup_columns_across_dtype(self): # dup columns across dtype GH 2079/2194 vals = [[1, -1, 2.0], [2, -2, 3.0]] rs = DataFrame(vals, columns=["A", "A", "B"]) @@ -486,36 +471,3 @@ def test_set_value_by_index(self): df.iloc[:, 0] = 3 tm.assert_series_equal(df.iloc[:, 1], expected) - - @pytest.mark.parametrize( - "data1,data2,expected_data", - ( - ( - [[1, 2], [3, 4]], - [[0.5, 6], [7, 8]], - [[np.nan, 3.0], [np.nan, 4.0], [np.nan, 7.0], [6.0, 8.0]], - ), - ( - [[1, 2], [3, 4]], - [[5, 6], [7, 8]], - [[np.nan, 3.0], [np.nan, 4.0], [5, 7], [6, 8]], - ), - ), - ) - def test_masking_duplicate_columns_mixed_dtypes( - self, - data1, - data2, - expected_data, - ): - # GH31954 - - df1 = DataFrame(np.array(data1)) - df2 = DataFrame(np.array(data2)) - df = pd.concat([df1, df2], axis=1) - - result = df[df > 2] - expected = DataFrame( - {i: np.array(col) for i, col in enumerate(expected_data)} - ).rename(columns={2: 0, 3: 1}) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 3f04f0f1163e7..04eb2f42d745b 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -769,6 +769,18 @@ def test_transform_numeric_ret(cols, exp, comp_func, agg_func, request): comp_func(result, exp) +def test_transform_ffill(): + # GH 24211 + data = [["a", 0.0], ["a", float("nan")], ["b", 1.0], ["b", float("nan")]] + df = DataFrame(data, columns=["key", "values"]) + result = df.groupby("key").transform("ffill") + expected = DataFrame({"values": [0.0, 0.0, 1.0, 1.0]}) + tm.assert_frame_equal(result, expected) + result = df.groupby("key")["values"].transform("ffill") + expected = Series([0.0, 0.0, 1.0, 1.0], name="values") + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("mix_groupings", [True, False]) @pytest.mark.parametrize("as_series", [True, False]) @pytest.mark.parametrize("val1,val2", [("foo", "bar"), (1, 2), (1.0, 2.0)]) diff --git a/pandas/tests/indexes/datetimes/methods/test_to_series.py b/pandas/tests/indexes/datetimes/methods/test_to_series.py new file mode 100644 index 0000000000000..5998fc0dde499 --- /dev/null +++ b/pandas/tests/indexes/datetimes/methods/test_to_series.py @@ -0,0 +1,37 @@ +import numpy as np +import pytest + +from pandas import DatetimeIndex, Series +import pandas._testing as tm + + +class TestToSeries: + @pytest.fixture + def idx_expected(self): + naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B") + idx = naive.tz_localize("US/Pacific") + + expected = Series(np.array(idx.tolist(), dtype="object"), name="B") + + assert expected.dtype == idx.dtype + return idx, expected + + def test_to_series_keep_tz_deprecated_true(self, idx_expected): + # convert to series while keeping the timezone + idx, expected = idx_expected + + msg = "stop passing 'keep_tz'" + with tm.assert_produces_warning(FutureWarning) as m: + result = idx.to_series(keep_tz=True, index=[0, 1]) + assert msg in str(m[0].message) + + tm.assert_series_equal(result, expected) + + def test_to_series_keep_tz_deprecated_false(self, idx_expected): + idx, expected = idx_expected + + with tm.assert_produces_warning(FutureWarning) as m: + result = idx.to_series(keep_tz=False, index=[0, 1]) + tm.assert_series_equal(result, expected.dt.tz_convert(None)) + msg = "do 'idx.tz_convert(None)' before calling" + assert msg in str(m[0].message) diff --git a/pandas/tests/indexes/datetimes/test_insert.py b/pandas/tests/indexes/datetimes/test_insert.py index 684c6b813b48f..6dbd1287b7306 100644 --- a/pandas/tests/indexes/datetimes/test_insert.py +++ b/pandas/tests/indexes/datetimes/test_insert.py @@ -13,8 +13,12 @@ class TestInsert: @pytest.mark.parametrize("tz", [None, "UTC", "US/Eastern"]) def test_insert_nat(self, tz, null): # GH#16537, GH#18295 (test missing) + idx = DatetimeIndex(["2017-01-01"], tz=tz) expected = DatetimeIndex(["NaT", "2017-01-01"], tz=tz) + if tz is not None and isinstance(null, np.datetime64): + expected = Index([null, idx[0]], dtype=object) + res = idx.insert(0, null) tm.assert_index_equal(res, expected) diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py index f4e7296598d54..95f5115a8c28b 100644 --- a/pandas/tests/indexing/interval/test_interval.py +++ b/pandas/tests/indexing/interval/test_interval.py @@ -7,87 +7,83 @@ class TestIntervalIndex: - def setup_method(self, method): - self.s = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) + @pytest.fixture + def series_with_interval_index(self): + return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) - def test_getitem_with_scalar(self): + def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl): - s = self.s + ser = series_with_interval_index.copy() - expected = s.iloc[:3] - tm.assert_series_equal(expected, s[:3]) - tm.assert_series_equal(expected, s[:2.5]) - tm.assert_series_equal(expected, s[0.1:2.5]) + expected = ser.iloc[:3] + tm.assert_series_equal(expected, indexer_sl(ser)[:3]) + tm.assert_series_equal(expected, indexer_sl(ser)[:2.5]) + tm.assert_series_equal(expected, indexer_sl(ser)[0.1:2.5]) + if indexer_sl is tm.loc: + tm.assert_series_equal(expected, ser.loc[-1:3]) - expected = s.iloc[1:4] - tm.assert_series_equal(expected, s[[1.5, 2.5, 3.5]]) - tm.assert_series_equal(expected, s[[2, 3, 4]]) - tm.assert_series_equal(expected, s[[1.5, 3, 4]]) + expected = ser.iloc[1:4] + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]]) - expected = s.iloc[2:5] - tm.assert_series_equal(expected, s[s >= 2]) + expected = ser.iloc[2:5] + tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) @pytest.mark.parametrize("direction", ["increasing", "decreasing"]) - def test_nonoverlapping_monotonic(self, direction, closed): + def test_nonoverlapping_monotonic(self, direction, closed, indexer_sl): tpls = [(0, 1), (2, 3), (4, 5)] if direction == "decreasing": tpls = tpls[::-1] idx = IntervalIndex.from_tuples(tpls, closed=closed) - s = Series(list("abc"), idx) + ser = Series(list("abc"), idx) - for key, expected in zip(idx.left, s): + for key, expected in zip(idx.left, ser): if idx.closed_left: - assert s[key] == expected - assert s.loc[key] == expected + assert indexer_sl(ser)[key] == expected else: with pytest.raises(KeyError, match=str(key)): - s[key] - with pytest.raises(KeyError, match=str(key)): - s.loc[key] + indexer_sl(ser)[key] - for key, expected in zip(idx.right, s): + for key, expected in zip(idx.right, ser): if idx.closed_right: - assert s[key] == expected - assert s.loc[key] == expected + assert indexer_sl(ser)[key] == expected else: with pytest.raises(KeyError, match=str(key)): - s[key] - with pytest.raises(KeyError, match=str(key)): - s.loc[key] + indexer_sl(ser)[key] - for key, expected in zip(idx.mid, s): - assert s[key] == expected - assert s.loc[key] == expected + for key, expected in zip(idx.mid, ser): + assert indexer_sl(ser)[key] == expected - def test_non_matching(self): - s = self.s + def test_non_matching(self, series_with_interval_index, indexer_sl): + ser = series_with_interval_index.copy() # this is a departure from our current # indexing scheme, but simpler with pytest.raises(KeyError, match=r"^\[-1\]$"): - s.loc[[-1, 3, 4, 5]] + indexer_sl(ser)[[-1, 3, 4, 5]] with pytest.raises(KeyError, match=r"^\[-1\]$"): - s.loc[[-1, 3]] + indexer_sl(ser)[[-1, 3]] @pytest.mark.arm_slow def test_large_series(self): - s = Series( + ser = Series( np.arange(1000000), index=IntervalIndex.from_breaks(np.arange(1000001)) ) - result1 = s.loc[:80000] - result2 = s.loc[0:80000] - result3 = s.loc[0:80000:1] + result1 = ser.loc[:80000] + result2 = ser.loc[0:80000] + result3 = ser.loc[0:80000:1] tm.assert_series_equal(result1, result2) tm.assert_series_equal(result1, result3) def test_loc_getitem_frame(self): # CategoricalIndex with IntervalIndex categories df = DataFrame({"A": range(10)}) - s = pd.cut(df.A, 5) - df["B"] = s + ser = pd.cut(df.A, 5) + df["B"] = ser df = df.set_index("B") result = df.loc[4] diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py index a9512bc97d9de..8935eb94c1c49 100644 --- a/pandas/tests/indexing/interval/test_interval_new.py +++ b/pandas/tests/indexing/interval/test_interval_new.py @@ -8,89 +8,65 @@ class TestIntervalIndex: - def setup_method(self, method): - self.s = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) + @pytest.fixture + def series_with_interval_index(self): + return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) - def test_loc_with_interval(self): + def test_loc_with_interval(self, series_with_interval_index, indexer_sl): # loc with single label / list of labels: # - Intervals: only exact matches # - scalars: those that contain it - s = self.s + ser = series_with_interval_index.copy() expected = 0 - result = s.loc[Interval(0, 1)] - assert result == expected - result = s[Interval(0, 1)] + result = indexer_sl(ser)[Interval(0, 1)] assert result == expected - expected = s.iloc[3:5] - result = s.loc[[Interval(3, 4), Interval(4, 5)]] - tm.assert_series_equal(expected, result) - result = s[[Interval(3, 4), Interval(4, 5)]] + expected = ser.iloc[3:5] + result = indexer_sl(ser)[[Interval(3, 4), Interval(4, 5)]] tm.assert_series_equal(expected, result) # missing or not exact with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")): - s.loc[Interval(3, 5, closed="left")] - - with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='left')")): - s[Interval(3, 5, closed="left")] - - with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): - s[Interval(3, 5)] + indexer_sl(ser)[Interval(3, 5, closed="left")] with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): - s.loc[Interval(3, 5)] - - with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): - s[Interval(3, 5)] - - with pytest.raises( - KeyError, match=re.escape("Interval(-2, 0, closed='right')") - ): - s.loc[Interval(-2, 0)] + indexer_sl(ser)[Interval(3, 5)] with pytest.raises( KeyError, match=re.escape("Interval(-2, 0, closed='right')") ): - s[Interval(-2, 0)] - - with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")): - s.loc[Interval(5, 6)] + indexer_sl(ser)[Interval(-2, 0)] with pytest.raises(KeyError, match=re.escape("Interval(5, 6, closed='right')")): - s[Interval(5, 6)] + indexer_sl(ser)[Interval(5, 6)] - def test_loc_with_scalar(self): + def test_loc_with_scalar(self, series_with_interval_index, indexer_sl): # loc with single label / list of labels: # - Intervals: only exact matches # - scalars: those that contain it - s = self.s + ser = series_with_interval_index.copy() - assert s.loc[1] == 0 - assert s.loc[1.5] == 1 - assert s.loc[2] == 1 + assert indexer_sl(ser)[1] == 0 + assert indexer_sl(ser)[1.5] == 1 + assert indexer_sl(ser)[2] == 1 - assert s[1] == 0 - assert s[1.5] == 1 - assert s[2] == 1 + expected = ser.iloc[1:4] + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2.5, 3.5]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[2, 3, 4]]) + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 3, 4]]) - expected = s.iloc[1:4] - tm.assert_series_equal(expected, s.loc[[1.5, 2.5, 3.5]]) - tm.assert_series_equal(expected, s.loc[[2, 3, 4]]) - tm.assert_series_equal(expected, s.loc[[1.5, 3, 4]]) + expected = ser.iloc[[1, 1, 2, 1]] + tm.assert_series_equal(expected, indexer_sl(ser)[[1.5, 2, 2.5, 1.5]]) - expected = s.iloc[[1, 1, 2, 1]] - tm.assert_series_equal(expected, s.loc[[1.5, 2, 2.5, 1.5]]) + expected = ser.iloc[2:5] + tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) - expected = s.iloc[2:5] - tm.assert_series_equal(expected, s.loc[s >= 2]) - - def test_loc_with_slices(self): + def test_loc_with_slices(self, series_with_interval_index, indexer_sl): # loc with slices: # - Interval objects: only works with exact matches @@ -99,178 +75,130 @@ def test_loc_with_slices(self): # contains them: # (slice_loc(start, stop) == (idx.get_loc(start), idx.get_loc(stop)) - s = self.s + ser = series_with_interval_index.copy() # slice of interval - expected = s.iloc[:3] - result = s.loc[Interval(0, 1) : Interval(2, 3)] - tm.assert_series_equal(expected, result) - result = s[Interval(0, 1) : Interval(2, 3)] + expected = ser.iloc[:3] + result = indexer_sl(ser)[Interval(0, 1) : Interval(2, 3)] tm.assert_series_equal(expected, result) - expected = s.iloc[3:] - result = s.loc[Interval(3, 4) :] - tm.assert_series_equal(expected, result) - result = s[Interval(3, 4) :] + expected = ser.iloc[3:] + result = indexer_sl(ser)[Interval(3, 4) :] tm.assert_series_equal(expected, result) msg = "Interval objects are not currently supported" with pytest.raises(NotImplementedError, match=msg): - s.loc[Interval(3, 6) :] + indexer_sl(ser)[Interval(3, 6) :] with pytest.raises(NotImplementedError, match=msg): - s[Interval(3, 6) :] - - with pytest.raises(NotImplementedError, match=msg): - s.loc[Interval(3, 4, closed="left") :] - - with pytest.raises(NotImplementedError, match=msg): - s[Interval(3, 4, closed="left") :] - - # slice of scalar + indexer_sl(ser)[Interval(3, 4, closed="left") :] - expected = s.iloc[:3] - tm.assert_series_equal(expected, s.loc[:3]) - tm.assert_series_equal(expected, s.loc[:2.5]) - tm.assert_series_equal(expected, s.loc[0.1:2.5]) - tm.assert_series_equal(expected, s.loc[-1:3]) - - tm.assert_series_equal(expected, s[:3]) - tm.assert_series_equal(expected, s[:2.5]) - tm.assert_series_equal(expected, s[0.1:2.5]) - - def test_slice_step_ne1(self): + def test_slice_step_ne1(self, series_with_interval_index): # GH#31658 slice of scalar with step != 1 - s = self.s - expected = s.iloc[0:4:2] + ser = series_with_interval_index.copy() + expected = ser.iloc[0:4:2] - result = s[0:4:2] + result = ser[0:4:2] tm.assert_series_equal(result, expected) - result2 = s[0:4][::2] + result2 = ser[0:4][::2] tm.assert_series_equal(result2, expected) - def test_slice_float_start_stop(self): + def test_slice_float_start_stop(self, series_with_interval_index): # GH#31658 slicing with integers is positional, with floats is not # supported - ser = Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) + ser = series_with_interval_index.copy() msg = "label-based slicing with step!=1 is not supported for IntervalIndex" with pytest.raises(ValueError, match=msg): ser[1.5:9.5:2] - def test_slice_interval_step(self): + def test_slice_interval_step(self, series_with_interval_index): # GH#31658 allows for integer step!=1, not Interval step - s = self.s + ser = series_with_interval_index.copy() msg = "label-based slicing with step!=1 is not supported for IntervalIndex" with pytest.raises(ValueError, match=msg): - s[0 : 4 : Interval(0, 1)] + ser[0 : 4 : Interval(0, 1)] - def test_loc_with_overlap(self): + def test_loc_with_overlap(self, indexer_sl): idx = IntervalIndex.from_tuples([(1, 5), (3, 7)]) - s = Series(range(len(idx)), index=idx) + ser = Series(range(len(idx)), index=idx) # scalar - expected = s - result = s.loc[4] - tm.assert_series_equal(expected, result) - - result = s[4] - tm.assert_series_equal(expected, result) - - result = s.loc[[4]] + expected = ser + result = indexer_sl(ser)[4] tm.assert_series_equal(expected, result) - result = s[[4]] + result = indexer_sl(ser)[[4]] tm.assert_series_equal(expected, result) # interval expected = 0 - result = s.loc[Interval(1, 5)] + result = indexer_sl(ser)[Interval(1, 5)] result == expected - result = s[Interval(1, 5)] - result == expected - - expected = s - result = s.loc[[Interval(1, 5), Interval(3, 7)]] - tm.assert_series_equal(expected, result) - - result = s[[Interval(1, 5), Interval(3, 7)]] + expected = ser + result = indexer_sl(ser)[[Interval(1, 5), Interval(3, 7)]] tm.assert_series_equal(expected, result) with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): - s.loc[Interval(3, 5)] + indexer_sl(ser)[Interval(3, 5)] with pytest.raises(KeyError, match=r"^\[Interval\(3, 5, closed='right'\)\]$"): - s.loc[[Interval(3, 5)]] - - with pytest.raises(KeyError, match=re.escape("Interval(3, 5, closed='right')")): - s[Interval(3, 5)] - - with pytest.raises(KeyError, match=r"^\[Interval\(3, 5, closed='right'\)\]$"): - s[[Interval(3, 5)]] + indexer_sl(ser)[[Interval(3, 5)]] # slices with interval (only exact matches) - expected = s - result = s.loc[Interval(1, 5) : Interval(3, 7)] - tm.assert_series_equal(expected, result) - - result = s[Interval(1, 5) : Interval(3, 7)] + expected = ser + result = indexer_sl(ser)[Interval(1, 5) : Interval(3, 7)] tm.assert_series_equal(expected, result) msg = "'can only get slices from an IntervalIndex if bounds are" " non-overlapping and all monotonic increasing or decreasing'" with pytest.raises(KeyError, match=msg): - s.loc[Interval(1, 6) : Interval(3, 8)] + indexer_sl(ser)[Interval(1, 6) : Interval(3, 8)] - with pytest.raises(KeyError, match=msg): - s[Interval(1, 6) : Interval(3, 8)] - - # slices with scalar raise for overlapping intervals - # TODO KeyError is the appropriate error? - with pytest.raises(KeyError, match=msg): - s.loc[1:4] + if indexer_sl is tm.loc: + # slices with scalar raise for overlapping intervals + # TODO KeyError is the appropriate error? + with pytest.raises(KeyError, match=msg): + ser.loc[1:4] - def test_non_unique(self): + def test_non_unique(self, indexer_sl): idx = IntervalIndex.from_tuples([(1, 3), (3, 7)]) - s = Series(range(len(idx)), index=idx) + ser = Series(range(len(idx)), index=idx) - result = s.loc[Interval(1, 3)] + result = indexer_sl(ser)[Interval(1, 3)] assert result == 0 - result = s.loc[[Interval(1, 3)]] - expected = s.iloc[0:1] + result = indexer_sl(ser)[[Interval(1, 3)]] + expected = ser.iloc[0:1] tm.assert_series_equal(expected, result) - def test_non_unique_moar(self): + def test_non_unique_moar(self, indexer_sl): idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)]) - s = Series(range(len(idx)), index=idx) - - expected = s.iloc[[0, 1]] - result = s.loc[Interval(1, 3)] - tm.assert_series_equal(expected, result) + ser = Series(range(len(idx)), index=idx) - expected = s - result = s.loc[Interval(1, 3) :] + expected = ser.iloc[[0, 1]] + result = indexer_sl(ser)[Interval(1, 3)] tm.assert_series_equal(expected, result) - expected = s - result = s[Interval(1, 3) :] + expected = ser + result = indexer_sl(ser)[Interval(1, 3) :] tm.assert_series_equal(expected, result) - expected = s.iloc[[0, 1]] - result = s[[Interval(1, 3)]] + expected = ser.iloc[[0, 1]] + result = indexer_sl(ser)[[Interval(1, 3)]] tm.assert_series_equal(expected, result) - def test_missing_key_error_message(self, frame_or_series): + def test_missing_key_error_message( + self, frame_or_series, series_with_interval_index + ): # GH#27365 - obj = frame_or_series( - np.arange(5), index=IntervalIndex.from_breaks(np.arange(6)) - ) + ser = series_with_interval_index.copy() + obj = frame_or_series(ser) with pytest.raises(KeyError, match=r"\[6\]"): obj.loc[[4, 5, 6]] diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 1b9b6452b2e33..3b6bc42544c51 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -322,6 +322,7 @@ def test_loc_listlike_dtypes(self): with pytest.raises(KeyError, match=re.escape(msg)): df.loc[["a", "x"]] + def test_loc_listlike_dtypes_duplicated_categories_and_codes(self): # duplicated categories and codes index = CategoricalIndex(["a", "b", "a"]) df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}, index=index) @@ -341,9 +342,11 @@ def test_loc_listlike_dtypes(self): ) tm.assert_frame_equal(res, exp, check_index_type=True) + msg = "The following labels were missing: Index(['x'], dtype='object')" with pytest.raises(KeyError, match=re.escape(msg)): df.loc[["a", "x"]] + def test_loc_listlike_dtypes_unused_category(self): # contains unused category index = CategoricalIndex(["a", "b", "a", "c"], categories=list("abcde")) df = DataFrame({"A": [1, 2, 3, 4], "B": [5, 6, 7, 8]}, index=index) @@ -363,6 +366,7 @@ def test_loc_listlike_dtypes(self): ) tm.assert_frame_equal(res, exp, check_index_type=True) + msg = "The following labels were missing: Index(['x'], dtype='object')" with pytest.raises(KeyError, match=re.escape(msg)): df.loc[["a", "x"]] @@ -405,6 +409,8 @@ def test_ix_categorical_index(self): expect = DataFrame(df.loc[:, ["X", "Y"]], index=cdf.index, columns=exp_columns) tm.assert_frame_equal(cdf.loc[:, ["X", "Y"]], expect) + def test_ix_categorical_index_non_unique(self): + # non-unique df = DataFrame(np.random.randn(3, 3), index=list("ABA"), columns=list("XYX")) cdf = df.copy() diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 1ac2a16660f93..25d4692e4cd1d 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -373,6 +373,7 @@ def test_setting_with_copy_bug(self): with pytest.raises(com.SettingWithCopyError, match=msg): df[["c"]][mask] = df[["b"]][mask] + def test_setting_with_copy_bug_no_warning(self): # invalid warning as we are returning a new object # GH 8730 df1 = DataFrame({"x": Series(["a", "b", "c"]), "y": Series(["d", "e", "f"])}) diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index 44a5e2ae6d9e9..9f58f4af0ba55 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -37,6 +37,7 @@ def test_indexing_with_datetime_tz(self): ) tm.assert_series_equal(result, expected) + def test_indexing_fast_xs(self): # indexing - fast_xs df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC")}) result = df.iloc[5] @@ -53,6 +54,7 @@ def test_indexing_with_datetime_tz(self): expected = df.iloc[4:] tm.assert_frame_equal(result, expected) + def test_setitem_with_expansion(self): # indexing - setting an element df = DataFrame( data=pd.to_datetime(["2015-03-30 20:12:32", "2015-03-12 00:11:11"]), @@ -234,21 +236,23 @@ def test_loc_setitem_with_existing_dst(self): def test_getitem_millisecond_resolution(self, frame_or_series): # GH#33589 + + keys = [ + "2017-10-25T16:25:04.151", + "2017-10-25T16:25:04.252", + "2017-10-25T16:50:05.237", + "2017-10-25T16:50:05.238", + ] obj = frame_or_series( [1, 2, 3, 4], - index=[ - Timestamp("2017-10-25T16:25:04.151"), - Timestamp("2017-10-25T16:25:04.252"), - Timestamp("2017-10-25T16:50:05.237"), - Timestamp("2017-10-25T16:50:05.238"), - ], + index=[Timestamp(x) for x in keys], ) - result = obj["2017-10-25T16:25:04.252":"2017-10-25T16:50:05.237"] + result = obj[keys[1] : keys[2]] expected = frame_or_series( [2, 3], index=[ - Timestamp("2017-10-25T16:25:04.252"), - Timestamp("2017-10-25T16:50:05.237"), + Timestamp(keys[1]), + Timestamp(keys[2]), ], ) tm.assert_equal(result, expected) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index dcd073681cecf..63313589d64f7 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -125,6 +125,7 @@ def test_inf_upcast(self): expected = pd.Float64Index([1, 2, np.inf]) tm.assert_index_equal(result, expected) + def test_inf_upcast_empty(self): # Test with np.inf in columns df = DataFrame() df.loc[0, 0] = 1 @@ -148,6 +149,9 @@ def test_setitem_dtype_upcast(self): ) tm.assert_frame_equal(df, expected) + @pytest.mark.parametrize("val", [3.14, "wxyz"]) + def test_setitem_dtype_upcast2(self, val): + # GH10280 df = DataFrame( np.arange(6, dtype="int64").reshape(2, 3), @@ -155,19 +159,19 @@ def test_setitem_dtype_upcast(self): columns=["foo", "bar", "baz"], ) - for val in [3.14, "wxyz"]: - left = df.copy() - left.loc["a", "bar"] = val - right = DataFrame( - [[0, val, 2], [3, 4, 5]], - index=list("ab"), - columns=["foo", "bar", "baz"], - ) + left = df.copy() + left.loc["a", "bar"] = val + right = DataFrame( + [[0, val, 2], [3, 4, 5]], + index=list("ab"), + columns=["foo", "bar", "baz"], + ) - tm.assert_frame_equal(left, right) - assert is_integer_dtype(left["foo"]) - assert is_integer_dtype(left["baz"]) + tm.assert_frame_equal(left, right) + assert is_integer_dtype(left["foo"]) + assert is_integer_dtype(left["baz"]) + def test_setitem_dtype_upcast3(self): left = DataFrame( np.arange(6, dtype="int64").reshape(2, 3) / 10.0, index=list("ab"), @@ -195,6 +199,8 @@ def test_dups_fancy_indexing(self): expected = Index(["b", "a", "a"]) tm.assert_index_equal(result, expected) + def test_dups_fancy_indexing_across_dtypes(self): + # across dtypes df = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa")) df.head() @@ -208,6 +214,7 @@ def test_dups_fancy_indexing(self): tm.assert_frame_equal(df, result) + def test_dups_fancy_indexing_not_in_order(self): # GH 3561, dups not in selected order df = DataFrame( {"test": [5, 7, 9, 11], "test1": [4.0, 5, 6, 7], "other": list("abcd")}, @@ -232,6 +239,8 @@ def test_dups_fancy_indexing(self): with pytest.raises(KeyError, match="with any missing labels"): df.loc[rows] + def test_dups_fancy_indexing_only_missing_label(self): + # List containing only missing label dfnu = DataFrame(np.random.randn(5, 3), index=list("AABCD")) with pytest.raises( @@ -244,6 +253,8 @@ def test_dups_fancy_indexing(self): # ToDo: check_index_type can be True after GH 11497 + def test_dups_fancy_indexing_missing_label(self): + # GH 4619; duplicate indexer with missing label df = DataFrame({"A": [0, 1, 2]}) with pytest.raises(KeyError, match="with any missing labels"): @@ -253,6 +264,8 @@ def test_dups_fancy_indexing(self): with pytest.raises(KeyError, match="with any missing labels"): df.loc[[0, 8, 0]] + def test_dups_fancy_indexing_non_unique(self): + # non unique with non unique selector df = DataFrame({"test": [5, 7, 9, 11]}, index=["A", "A", "B", "C"]) with pytest.raises(KeyError, match="with any missing labels"): @@ -447,6 +460,7 @@ def test_multi_assign(self): df2.loc[mask, cols] = dft.loc[mask, cols].values tm.assert_frame_equal(df2, expected) + def test_multi_assign_broadcasting_rhs(self): # broadcasting on the rhs is required df = DataFrame( { @@ -781,14 +795,16 @@ def test_non_reducing_slice(self, slc): tslice_ = non_reducing_slice(slc) assert isinstance(df.loc[tslice_], DataFrame) - def test_list_slice(self): + @pytest.mark.parametrize("box", [list, Series, np.array]) + def test_list_slice(self, box): # like dataframe getitem - slices = [["A"], Series(["A"]), np.array(["A"])] + subset = box(["A"]) + df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"]) expected = pd.IndexSlice[:, ["A"]] - for subset in slices: - result = non_reducing_slice(subset) - tm.assert_frame_equal(df.loc[result], df.loc[expected]) + + result = non_reducing_slice(subset) + tm.assert_frame_equal(df.loc[result], df.loc[expected]) def test_maybe_numeric_slice(self): df = DataFrame({"A": [1, 2], "B": ["c", "d"], "C": [True, False]}) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 0a50ef2831534..3203b7fa1893d 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -1233,8 +1233,8 @@ def check_frame_setitem(self, elem, index: Index, inplace: bool): if inplace: # assertion here implies setting was done inplace - # error: Item "ArrayManager" of "Union[ArrayManager, BlockManager]" - # has no attribute "blocks" [union-attr] + # error: Item "ArrayManager" of "Union[ArrayManager, BlockManager]" has no + # attribute "blocks" assert df._mgr.blocks[0].values is arr # type:ignore[union-attr] else: assert df.dtypes[0] == object diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 0962b719efd4d..8128e958141e2 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -1,11 +1,8 @@ -from distutils.version import LooseVersion from pathlib import Path import numpy as np import pytest -from pandas.compat._optional import get_version - import pandas as pd from pandas import DataFrame import pandas._testing as tm @@ -157,10 +154,6 @@ def test_read_with_bad_dimension( datapath, ext, header, expected_data, filename, read_only, request ): # GH 38956, 39001 - no/incorrect dimension information - version = LooseVersion(get_version(openpyxl)) - if (read_only or read_only is None) and version < "3.0.0": - msg = "openpyxl read-only sheet is incorrect when dimension data is wrong" - request.node.add_marker(pytest.mark.xfail(reason=msg)) path = datapath("io", "data", "excel", f"{filename}{ext}") if read_only is None: result = pd.read_excel(path, header=header) @@ -195,10 +188,6 @@ def test_append_mode_file(ext): @pytest.mark.parametrize("read_only", [True, False, None]) def test_read_with_empty_trailing_rows(datapath, ext, read_only, request): # GH 39181 - version = LooseVersion(get_version(openpyxl)) - if (read_only or read_only is None) and version < "3.0.0": - msg = "openpyxl read-only sheet is incorrect when dimension data is wrong" - request.node.add_marker(pytest.mark.xfail(reason=msg)) path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}") if read_only is None: result = pd.read_excel(path) diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 0c61a8a18e153..0aebcda83993d 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -1305,6 +1305,15 @@ def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path): with pytest.raises(ValueError, match="Excel does not support"): df.to_excel(path) + def test_excel_duplicate_columns_with_names(self, path): + # GH#39695 + df = DataFrame({"A": [0, 1], "B": [10, 11]}) + df.to_excel(path, columns=["A", "B", "A"], index=False) + + result = pd.read_excel(path) + expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"]) + tm.assert_frame_equal(result, expected) + class TestExcelWriterEngineTests: @pytest.mark.parametrize( diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index d97410562083c..e047317acd24d 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -559,7 +559,7 @@ def test_dt64_series_assign_nat(nat_val, tz, indexer_sli): base = Series(dti) expected = Series([pd.NaT] + list(dti[1:]), dtype=dti.dtype) - should_cast = nat_val is pd.NaT or base.dtype.kind == nat_val.dtype.kind + should_cast = nat_val is pd.NaT or base.dtype == nat_val.dtype if not should_cast: expected = expected.astype(object) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 3a9ec0948b29a..36948c3dc05f3 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -671,6 +671,43 @@ def key(self): return 0 +class TestSetitemNADatetime64Dtype(SetitemCastingEquivalents): + # some nat-like values should be cast to datetime64 when inserting + # into a datetime64 series. Others should coerce to object + # and retain their dtypes. + + @pytest.fixture(params=[None, "UTC", "US/Central"]) + def obj(self, request): + tz = request.param + dti = date_range("2016-01-01", periods=3, tz=tz) + return Series(dti) + + @pytest.fixture( + params=[NaT, np.timedelta64("NaT", "ns"), np.datetime64("NaT", "ns")] + ) + def val(self, request): + return request.param + + @pytest.fixture + def is_inplace(self, val, obj): + if obj._values.tz is None: + # cast to object iff val is timedelta64("NaT") + return val is NaT or val.dtype.kind == "M" + + # otherwise we have to exclude tznaive dt64("NaT") + return val is NaT + + @pytest.fixture + def expected(self, obj, val, is_inplace): + dtype = obj.dtype if is_inplace else object + expected = Series([val] + list(obj[1:]), dtype=dtype) + return expected + + @pytest.fixture + def key(self): + return 0 + + class TestSetitemMismatchedTZCastsToObject(SetitemCastingEquivalents): # GH#24024 @pytest.fixture diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 0bcb37d4880a6..7e33b766a1413 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -204,8 +204,9 @@ def test_timedelta_fillna(self, frame_or_series): expected = frame_or_series(expected) tm.assert_equal(result, expected) - # interpreted as seconds, deprecated - with pytest.raises(TypeError, match="Passing integers to fillna"): + # interpreted as seconds, no longer supported + msg = "value should be a 'Timedelta', 'NaT', or array of those. Got 'int'" + with pytest.raises(TypeError, match=msg): obj.fillna(1) result = obj.fillna(Timedelta(seconds=1)) diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index a13fb1ce57f6c..268c636ab9353 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -78,8 +78,8 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]: {dedent(doc)}""" ) - # error: Incompatible return value type (got "Callable[[VarArg(Any), - # KwArg(Any)], Callable[...,Any]]", expected "Callable[[F], F]") + # error: Incompatible return value type (got "Callable[[VarArg(Any), KwArg(Any)], + # Callable[...,Any]]", expected "Callable[[F], F]") return wrapper # type: ignore[return-value] @@ -362,10 +362,10 @@ def decorator(decorated: F) -> F: for docstring in docstrings: if hasattr(docstring, "_docstring_components"): - # error: Item "str" of "Union[str, Callable[..., Any]]" has no - # attribute "_docstring_components" [union-attr] - # error: Item "function" of "Union[str, Callable[..., Any]]" - # has no attribute "_docstring_components" [union-attr] + # error: Item "str" of "Union[str, Callable[..., Any]]" has no attribute + # "_docstring_components" + # error: Item "function" of "Union[str, Callable[..., Any]]" has no + # attribute "_docstring_components" docstring_components.extend( docstring._docstring_components # type: ignore[union-attr] ) diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py index d521f2ee421be..f991b16fea192 100755 --- a/scripts/validate_rst_title_capitalization.py +++ b/scripts/validate_rst_title_capitalization.py @@ -1,17 +1,17 @@ -#!/usr/bin/env python3 """ Validate that the titles in the rst files follow the proper capitalization convention. Print the titles that do not follow the convention. Usage:: -./scripts/validate_rst_title_capitalization.py doc/source/development/contributing.rst -./scripts/validate_rst_title_capitalization.py doc/source/ +As pre-commit hook (recommended): + pre-commit run title-capitalization --all-files + +From the command-line: + python scripts/validate_rst_title_capitalization.py <rst file> """ import argparse -import glob -import os import re import sys from typing import Iterable, List, Tuple @@ -233,36 +233,7 @@ def find_titles(rst_file: str) -> Iterable[Tuple[str, int]]: previous_line = line -def find_rst_files(source_paths: List[str]) -> Iterable[str]: - """ - Given the command line arguments of directory paths, this method - yields the strings of the .rst file directories that these paths contain. - - Parameters - ---------- - source_paths : str - List of directories to validate, provided through command line arguments. - - Yields - ------- - str - Directory address of a .rst files found in command line argument directories. - """ - - for directory_address in source_paths: - if not os.path.exists(directory_address): - raise ValueError( - "Please enter a valid path, pointing to a valid file/directory." - ) - elif directory_address.endswith(".rst"): - yield directory_address - else: - yield from glob.glob( - pathname=f"{directory_address}/**/*.rst", recursive=True - ) - - -def main(source_paths: List[str], output_format: str) -> int: +def main(source_paths: List[str]) -> int: """ The main method to print all headings with incorrect capitalization. @@ -270,8 +241,6 @@ def main(source_paths: List[str], output_format: str) -> int: ---------- source_paths : str List of directories to validate, provided through command line arguments. - output_format : str - Output format of the script. Returns ------- @@ -281,7 +250,7 @@ def main(source_paths: List[str], output_format: str) -> int: number_of_errors: int = 0 - for filename in find_rst_files(source_paths): + for filename in source_paths: for title, line_number in find_titles(filename): if title != correct_title_capitalization(title): print( @@ -297,16 +266,9 @@ def main(source_paths: List[str], output_format: str) -> int: parser = argparse.ArgumentParser(description="Validate heading capitalization") parser.add_argument( - "paths", nargs="+", default=".", help="Source paths of file/directory to check." - ) - - parser.add_argument( - "--format", - "-f", - default="{source_path}:{line_number}:{msg}:{heading}:{correct_heading}", - help="Output format of incorrectly capitalized titles", + "paths", nargs="*", help="Source paths of file/directory to check." ) args = parser.parse_args() - sys.exit(main(args.paths, args.format)) + sys.exit(main(args.paths))
- [ ] follows #39852 - [x] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39830
2021-02-16T02:25:41Z
2021-06-16T13:31:13Z
null
2021-06-16T13:31:13Z
BUG: DataFrame.append broken on master
diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index a2c930f6d9b22..01d8cde3e9af2 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -291,9 +291,7 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: if len(values) and values[0] is None: fill_value = None - if is_datetime64tz_dtype(blk_dtype) or is_datetime64tz_dtype( - empty_dtype - ): + if is_datetime64tz_dtype(empty_dtype): # TODO(EA2D): special case unneeded with 2D EAs i8values = np.full(self.shape[1], fill_value.value) return DatetimeArray(i8values, dtype=empty_dtype) @@ -302,9 +300,8 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: elif is_extension_array_dtype(blk_dtype): pass elif is_extension_array_dtype(empty_dtype): - missing_arr = empty_dtype.construct_array_type()._from_sequence( - [], dtype=empty_dtype - ) + cls = empty_dtype.construct_array_type() + missing_arr = cls._from_sequence([], dtype=empty_dtype) ncols, nrows = self.shape assert ncols == 1, ncols empty_arr = -1 * np.ones((nrows,), dtype=np.intp)
Should get the CI to green.
https://api.github.com/repos/pandas-dev/pandas/pulls/39829
2021-02-16T02:05:55Z
2021-02-16T04:02:07Z
2021-02-16T04:02:07Z
2021-02-16T04:02:37Z
BUG: PandasArray._from_sequence with list-of-tuples
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 9999a9ed411d8..8a8c4be012d99 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -10,6 +10,7 @@ from pandas._typing import Dtype, NpDtype, Scalar from pandas.compat.numpy import function as nv +from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.dtypes import PandasDtype from pandas.core.dtypes.missing import isna @@ -86,6 +87,14 @@ def _from_sequence( dtype = dtype._dtype result = np.asarray(scalars, dtype=dtype) + if ( + result.ndim > 1 + and not hasattr(scalars, "dtype") + and (dtype is None or dtype == object) + ): + # e.g. list-of-tuples + result = construct_1d_object_array_from_listlike(scalars) + if copy and result is scalars: result = result.copy() return cls(result) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 3c27e34dcbcf6..0bdfb7ffb20d3 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -182,10 +182,17 @@ def _check_ndim(self, values, ndim): if ndim is None: ndim = values.ndim - if self._validate_ndim and values.ndim != ndim: + if self._validate_ndim: + if values.ndim != ndim: + raise ValueError( + "Wrong number of dimensions. " + f"values.ndim != ndim [{values.ndim} != {ndim}]" + ) + elif values.ndim > ndim: + # ExtensionBlock raise ValueError( "Wrong number of dimensions. " - f"values.ndim != ndim [{values.ndim} != {ndim}]" + f"values.ndim > ndim [{values.ndim} > {ndim}]" ) return ndim @@ -2178,28 +2185,6 @@ def fillna( value, limit=limit, inplace=inplace, downcast=downcast ) - def _check_ndim(self, values, ndim): - """ - ndim inference and validation. - - This is overridden by the DatetimeTZBlock to check the case of 2D - data (values.ndim == 2), which should only be allowed if ndim is - also 2. - The case of 1D array is still allowed with both ndim of 1 or 2, as - if the case for other EAs. Therefore, we are only checking - `values.ndim > ndim` instead of `values.ndim != ndim` as for - consolidated blocks. - """ - if ndim is None: - ndim = values.ndim - - if values.ndim > ndim: - raise ValueError( - "Wrong number of dimensions. " - f"values.ndim != ndim [{values.ndim} != {ndim}]" - ) - return ndim - class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index a5b54bc153f5d..1e876d137319d 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -186,11 +186,6 @@ def test_getitem_scalar(self, data): # AssertionError super().test_getitem_scalar(data) - @skip_nested - def test_take_series(self, data): - # ValueError: PandasArray must be 1-dimensional. - super().test_take_series(data) - class TestGroupby(BaseNumPyTests, base.BaseGroupbyTests): def test_groupby_extension_apply( @@ -219,13 +214,6 @@ def test_shift_fill_value(self, data): # np.array shape inference. Shift implementation fails. super().test_shift_fill_value(data) - @skip_nested - @pytest.mark.parametrize("box", [pd.Series, lambda x: x]) - @pytest.mark.parametrize("method", [lambda x: x.unique(), pd.unique]) - def test_unique(self, data, box, method): - # Fails creating expected - super().test_unique(data, box, method) - @skip_nested def test_fillna_copy_frame(self, data_missing): # The "scalar" for this array isn't a scalar. @@ -241,31 +229,10 @@ def test_searchsorted(self, data_for_sorting, as_series): # Test setup fails. super().test_searchsorted(data_for_sorting, as_series) - @skip_nested - def test_where_series(self, data, na_value, as_frame): - # Test setup fails. - super().test_where_series(data, na_value, as_frame) - - @pytest.mark.parametrize("repeats", [0, 1, 2, [1, 2, 3]]) - def test_repeat(self, data, repeats, as_series, use_numpy, request): - if data.dtype.numpy_dtype == object and repeats != 0: - mark = pytest.mark.xfail(reason="mask shapes mismatch") - request.node.add_marker(mark) - super().test_repeat(data, repeats, as_series, use_numpy) - @pytest.mark.xfail(reason="PandasArray.diff may fail on dtype") def test_diff(self, data, periods): return super().test_diff(data, periods) - @pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame]) - def test_equals(self, data, na_value, as_series, box, request): - # Fails creating with _from_sequence - if box is pd.DataFrame and data.dtype.numpy_dtype == object: - mark = pytest.mark.xfail(reason="AssertionError in _get_same_shape_values") - request.node.add_marker(mark) - - super().test_equals(data, na_value, as_series, box) - class TestArithmetics(BaseNumPyTests, base.BaseArithmeticOpsTests): divmod_exc = None @@ -286,8 +253,11 @@ def test_divmod_series_array(self, data): def test_arith_series_with_scalar(self, data, all_arithmetic_operators): super().test_arith_series_with_scalar(data, all_arithmetic_operators) - @skip_nested - def test_arith_series_with_array(self, data, all_arithmetic_operators): + def test_arith_series_with_array(self, data, all_arithmetic_operators, request): + opname = all_arithmetic_operators + if data.dtype.numpy_dtype == object and opname not in ["__add__", "__radd__"]: + mark = pytest.mark.xfail(reason="Fails for object dtype") + request.node.add_marker(mark) super().test_arith_series_with_array(data, all_arithmetic_operators) @skip_nested @@ -322,11 +292,6 @@ def test_fillna_scalar(self, data_missing): # Non-scalar "scalar" values. super().test_fillna_scalar(data_missing) - @skip_nested - def test_fillna_series_method(self, data_missing, fillna_method): - # Non-scalar "scalar" values. - super().test_fillna_series_method(data_missing, fillna_method) - @skip_nested def test_fillna_series(self, data_missing): # Non-scalar "scalar" values. @@ -355,20 +320,6 @@ def test_merge(self, data, na_value): # Fails creating expected (key column becomes a PandasDtype because) super().test_merge(data, na_value) - @skip_nested - def test_merge_on_extension_array(self, data): - # Fails creating expected - super().test_merge_on_extension_array(data) - - @skip_nested - def test_merge_on_extension_array_duplicates(self, data): - # Fails creating expected - super().test_merge_on_extension_array_duplicates(data) - - @skip_nested - def test_transpose_frame(self, data): - super().test_transpose_frame(data) - class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): @skip_nested
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39828
2021-02-15T23:15:00Z
2021-02-17T01:33:01Z
2021-02-17T01:33:01Z
2021-02-17T01:45:36Z
Backport PR #39800 on branch 1.2.x (Regression in to_excel when setting duplicate column names)
diff --git a/doc/source/whatsnew/v1.2.3.rst b/doc/source/whatsnew/v1.2.3.rst index e675b3ea921d1..4231b6d94b1b9 100644 --- a/doc/source/whatsnew/v1.2.3.rst +++ b/doc/source/whatsnew/v1.2.3.rst @@ -15,7 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Fixed regression in :func:`pandas.to_excel` raising ``KeyError`` when giving duplicate columns with ``columns`` attribute (:issue:`39695`) - .. --------------------------------------------------------------------------- diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 0cad67169feff..6e77406948202 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -465,7 +465,7 @@ def __init__( if not len(Index(cols).intersection(df.columns)): raise KeyError("passes columns are not ALL present dataframe") - if len(Index(cols).intersection(df.columns)) != len(cols): + if len(Index(cols).intersection(df.columns)) != len(set(cols)): # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index af0de05965398..6d0684d4d1315 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -1295,6 +1295,15 @@ def test_raise_when_saving_timezones(self, dtype, tz_aware_fixture, path): with pytest.raises(ValueError, match="Excel does not support"): df.to_excel(path) + def test_excel_duplicate_columns_with_names(self, path): + # GH#39695 + df = DataFrame({"A": [0, 1], "B": [10, 11]}) + df.to_excel(path, columns=["A", "B", "A"], index=False) + + result = pd.read_excel(path) + expected = DataFrame([[0, 10, 0], [1, 11, 1]], columns=["A", "B", "A.1"]) + tm.assert_frame_equal(result, expected) + class TestExcelWriterEngineTests: @pytest.mark.parametrize(
Backport PR #39800: Regression in to_excel when setting duplicate column names
https://api.github.com/repos/pandas-dev/pandas/pulls/39827
2021-02-15T22:43:06Z
2021-02-16T09:41:00Z
2021-02-16T09:41:00Z
2021-02-16T09:41:00Z
Dont raise exception when subattr was not found in JSON parsing
diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index f9fc5c301b3b2..cbaa63f4ac9c3 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -267,6 +267,9 @@ static PyObject *get_sub_attr(PyObject *obj, char *attr, char *subAttr) { return 0; } ret = PyObject_GetAttrString(tmp, subAttr); + if (ret == 0) { + return 0; + } Py_DECREF(tmp); return ret;
https://api.github.com/repos/pandas-dev/pandas/pulls/39826
2021-02-15T21:52:43Z
2021-02-16T08:49:40Z
null
2021-02-16T08:49:46Z
PERF: use arr.size instead of np.prod(arr.shape) in _can_use_numexpr
diff --git a/pandas/core/array_algos/transforms.py b/pandas/core/array_algos/transforms.py index 371425f325d76..1dde9b221a90b 100644 --- a/pandas/core/array_algos/transforms.py +++ b/pandas/core/array_algos/transforms.py @@ -19,7 +19,7 @@ def shift(values: np.ndarray, periods: int, axis: int, fill_value) -> np.ndarray new_values = new_values.T axis = new_values.ndim - axis - 1 - if np.prod(new_values.shape): + if new_values.size: new_values = np.roll(new_values, ensure_platform_int(periods), axis=axis) axis_indexer = [slice(None)] * values.ndim diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 087b7f39e3374..ca62e8a31be7a 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -76,7 +76,7 @@ def _can_use_numexpr(op, op_str, a, b, dtype_check): if op_str is not None: # required min elements (otherwise we are adding overhead) - if np.prod(a.shape) > _MIN_ELEMENTS: + if a.size > _MIN_ELEMENTS: # check for dtype compatibility dtypes: Set[str] = set() for o in [a, b]: diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e27c519304e2e..2fc6aa9842b73 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1497,7 +1497,7 @@ def maybe_cast_to_datetime(value, dtype: Optional[DtypeObj]): value = iNaT # we have an array of datetime or timedeltas & nulls - elif np.prod(value.shape) or not is_dtype_equal(value.dtype, dtype): + elif value.size or not is_dtype_equal(value.dtype, dtype): _disallow_mismatched_datetimelike(value, dtype) try: diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index ef645313de614..657b10c46fed7 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -429,7 +429,7 @@ def array_equivalent( # NaNs can occur in float and complex arrays. if is_float_dtype(left.dtype) or is_complex_dtype(left.dtype): - if not (np.prod(left.shape) and np.prod(right.shape)): + if not (left.size and right.size): return True return ((left == right) | (isna(left) & isna(right))).all()
xref https://github.com/pandas-dev/pandas/pull/39772 Using `np.prod` gives quite some overhead, and I *think* it's always equivalent to `.size` ? ``` In [1]: arr = np.random.randn(3, 2) In [2]: %timeit arr.size 42.8 ns ± 0.628 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) In [3]: %timeit np.prod(arr.shape) 6.63 µs ± 344 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/39825
2021-02-15T19:19:54Z
2021-02-16T22:55:57Z
2021-02-16T22:55:57Z
2021-02-17T07:09:29Z
REF: remove unnecessary Block attrs
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 06bf2e5d7b18e..5fae48ae5d4b2 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -99,9 +99,6 @@ class Block(PandasObject): __slots__ = ["_mgr_locs", "values", "ndim"] is_numeric = False is_float = False - is_datetime = False - is_datetimetz = False - is_timedelta = False is_bool = False is_object = False is_extension = False @@ -213,11 +210,6 @@ def is_view(self) -> bool: def is_categorical(self) -> bool: return self._holder is Categorical - @property - def is_datelike(self) -> bool: - """ return True if I am a non-datelike """ - return self.is_datetime or self.is_timedelta - def external_values(self): """ The array that Series.values returns (public attribute). @@ -547,7 +539,8 @@ def _maybe_downcast(self, blocks: List[Block], downcast=None) -> List[Block]: # no need to downcast our float # unless indicated - if downcast is None and (self.is_float or self.is_datelike): + if downcast is None and self.dtype.kind in ["f", "m", "M"]: + # TODO: complex? more generally, self._can_hold_na? return blocks return extend_blocks([b.downcast(downcast) for b in blocks]) @@ -634,13 +627,12 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): raise newb = self.make_block(new_values) - if newb.is_numeric and self.is_numeric: - if newb.shape != self.shape: - raise TypeError( - f"cannot set astype for copy = [{copy}] for dtype " - f"({self.dtype.name} [{self.shape}]) to different shape " - f"({newb.dtype.name} [{newb.shape}])" - ) + if newb.shape != self.shape: + raise TypeError( + f"cannot set astype for copy = [{copy}] for dtype " + f"({self.dtype.name} [{self.shape}]) to different shape " + f"({newb.dtype.name} [{newb.shape}])" + ) return newb def _astype(self, dtype: DtypeObj, copy: bool) -> ArrayLike: @@ -2089,7 +2081,6 @@ class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): values: DatetimeArray __slots__ = () - is_datetimetz = True is_extension = True _holder = DatetimeArray @@ -2167,7 +2158,7 @@ def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: def external_values(self): # NB: this is different from np.asarray(self.values), since that # return an object-dtype ndarray of Timestamps. - # avoid FutureWarning in .astype in casting from dt64t to dt64 + # Avoid FutureWarning in .astype in casting from dt64tz to dt64 return self.values._data def fillna( @@ -2208,7 +2199,6 @@ def _check_ndim(self, values, ndim): class TimeDeltaBlock(DatetimeLikeBlockMixin): __slots__ = () - is_timedelta = True _can_hold_na = True is_numeric = False _holder = TimedeltaArray diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 01d8cde3e9af2..c65d104021a47 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -12,7 +12,6 @@ from pandas.core.dtypes.cast import ensure_dtype_can_hold_na, find_common_type from pandas.core.dtypes.common import ( - is_categorical_dtype, is_datetime64tz_dtype, is_dtype_equal, is_extension_array_dtype, @@ -295,8 +294,6 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: # TODO(EA2D): special case unneeded with 2D EAs i8values = np.full(self.shape[1], fill_value.value) return DatetimeArray(i8values, dtype=empty_dtype) - elif is_categorical_dtype(blk_dtype): - pass elif is_extension_array_dtype(blk_dtype): pass elif is_extension_array_dtype(empty_dtype):
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing.html#code-standards) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/39824
2021-02-15T18:52:09Z
2021-02-16T16:52:18Z
2021-02-16T16:52:18Z
2021-02-16T17:55:16Z