title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
BUG: DataFrame.to_html(na_rep="-") with non-scalar data
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 7fc856be374e9..e9e06044eba0a 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1322,6 +1322,7 @@ I/O - Bug in :func:`read_csv` unnecessarily overflowing for extension array dtype when containing ``NA`` (:issue:`32134`) - Bug in :meth:`DataFrame.to_dict` not converting ``NA`` to ``None`` (:issue:`50795`) - Bug in :meth:`DataFrame.to_json` where it would segfault when failing to encode a string (:issue:`50307`) +- Bug in :meth:`DataFrame.to_html` with ``na_rep`` set when the :class:`DataFrame` contains non-scalar data (:issue:`47103`) - Bug in :func:`read_xml` where file-like objects failed when iterparse is used (:issue:`50641`) - Bug in :func:`read_xml` ignored repeated elements when iterparse is used (:issue:`51183`) diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 6ae9c528e4772..141b9a70023b6 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -1814,7 +1814,7 @@ def _maybe_wrap_formatter( if na_rep is None: return func_3 else: - return lambda x: na_rep if isna(x) else func_3(x) + return lambda x: na_rep if (isna(x) is True) else func_3(x) def non_reducing_slice(slice_: Subset): diff --git a/pandas/tests/io/formats/data/html/gh47103_expected_output.html b/pandas/tests/io/formats/data/html/gh47103_expected_output.html new file mode 100644 index 0000000000000..f8c54cb85c815 --- /dev/null +++ b/pandas/tests/io/formats/data/html/gh47103_expected_output.html @@ -0,0 +1,16 @@ +<table border="1" class="dataframe"> + <thead> + <tr style="text-align: right;"> + <th></th> + <th>a</th> + <th>b</th> + </tr> + </thead> + <tbody> + <tr> + <th>0</th> + <td>1</td> + <td>[1, 2, 3]</td> + </tr> + </tbody> +</table> diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py index d878d82f55e51..1867260fbc4b4 100644 --- a/pandas/tests/io/formats/style/test_html.py +++ b/pandas/tests/io/formats/style/test_html.py @@ -976,3 +976,32 @@ def html_lines(foot_prefix: str): ) ) assert expected_css + expected_table == result + + +def test_to_html_na_rep_non_scalar_data(datapath): + # GH47103 + df = DataFrame([dict(a=1, b=[1, 2, 3], c=np.nan)]) + result = df.style.format(na_rep="-").to_html(table_uuid="test") + expected = """\ +<style type="text/css"> +</style> +<table id="T_test"> + <thead> + <tr> + <th class="blank level0" >&nbsp;</th> + <th id="T_test_level0_col0" class="col_heading level0 col0" >a</th> + <th id="T_test_level0_col1" class="col_heading level0 col1" >b</th> + <th id="T_test_level0_col2" class="col_heading level0 col2" >c</th> + </tr> + </thead> + <tbody> + <tr> + <th id="T_test_level0_row0" class="row_heading level0 row0" >0</th> + <td id="T_test_row0_col0" class="data row0 col0" >1</td> + <td id="T_test_row0_col1" class="data row0 col1" >[1, 2, 3]</td> + <td id="T_test_row0_col2" class="data row0 col2" >-</td> + </tr> + </tbody> +</table> +""" + assert result == expected diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index 3059efef09095..a66858d3f983e 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -882,6 +882,14 @@ def test_to_html_na_rep_and_float_format(na_rep, datapath): assert result == expected +def test_to_html_na_rep_non_scalar_data(datapath): + # GH47103 + df = DataFrame([dict(a=1, b=[1, 2, 3])]) + result = df.to_html(na_rep="-") + expected = expected_html(datapath, "gh47103_expected_output") + assert result == expected + + def test_to_html_float_format_object_col(datapath): # GH#40024 df = DataFrame(data={"x": [1000.0, "test"]})
- [x] closes #47103 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51412
2023-02-15T18:57:00Z
2023-02-16T21:59:54Z
2023-02-16T21:59:54Z
2023-02-16T22:54:35Z
ENH: Optimize CoW for fillna with ea dtypes
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 1aba48371b430..9b435aa31bd16 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1758,9 +1758,14 @@ def fillna( downcast=downcast, using_cow=using_cow, ) - new_values = self.values.fillna(value=value, method=None, limit=limit) - nb = self.make_block_same_class(new_values) - return nb._maybe_downcast([nb], downcast) + if using_cow and self._can_hold_na and not self.values._hasna: + refs = self.refs + new_values = self.values + else: + refs = None + new_values = self.values.fillna(value=value, method=None, limit=limit) + nb = self.make_block_same_class(new_values, refs=refs) + return nb._maybe_downcast([nb], downcast, using_cow=using_cow) @cache_readonly def shape(self) -> Shape: diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index c3e1e5f39384b..35bd5d47b36dc 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -2,6 +2,7 @@ import pytest from pandas import ( + NA, DataFrame, Interval, NaT, @@ -271,3 +272,48 @@ def test_fillna_series_empty_arg_inplace(using_copy_on_write): assert np.shares_memory(get_array(ser), arr) if using_copy_on_write: assert ser._mgr._has_no_reference(0) + + +def test_fillna_ea_noop_shares_memory( + using_copy_on_write, any_numeric_ea_and_arrow_dtype +): + df = DataFrame({"a": [1, NA, 3], "b": 1}, dtype=any_numeric_ea_and_arrow_dtype) + df_orig = df.copy() + df2 = df.fillna(100) + + assert not np.shares_memory(get_array(df, "a"), get_array(df2, "a")) + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert not df2._mgr._has_no_reference(1) + else: + assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + + tm.assert_frame_equal(df_orig, df) + + df2.iloc[0, 1] = 100 + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + assert df2._mgr._has_no_reference(1) + assert df._mgr._has_no_reference(1) + tm.assert_frame_equal(df_orig, df) + + +def test_fillna_inplace_ea_noop_shares_memory( + using_copy_on_write, any_numeric_ea_and_arrow_dtype +): + df = DataFrame({"a": [1, NA, 3], "b": 1}, dtype=any_numeric_ea_and_arrow_dtype) + df_orig = df.copy() + view = df[:] + df.fillna(100, inplace=True) + + assert not np.shares_memory(get_array(df, "a"), get_array(view, "a")) + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "b"), get_array(view, "b")) + assert not df._mgr._has_no_reference(1) + assert not view._mgr._has_no_reference(1) + else: + assert not np.shares_memory(get_array(df, "b"), get_array(view, "b")) + df.iloc[0, 1] = 100 + tm.assert_frame_equal(df_orig, view) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 85c2febefb6ce..ca867ffb77296 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -243,24 +243,25 @@ def test_factorize_empty(self, data): def test_fillna_copy_frame(self, data_missing): arr = data_missing.take([1, 1]) df = pd.DataFrame({"A": arr}) + df_orig = df.copy() filled_val = df.iloc[0, 0] result = df.fillna(filled_val) - assert df.A.values is not result.A.values + result.iloc[0, 0] = filled_val - def test_fillna_copy_series(self, data_missing, no_op_with_cow: bool = False): + self.assert_frame_equal(df, df_orig) + + def test_fillna_copy_series(self, data_missing): arr = data_missing.take([1, 1]) ser = pd.Series(arr) + ser_orig = ser.copy() filled_val = ser[0] result = ser.fillna(filled_val) + result.iloc[0] = filled_val - if no_op_with_cow: - assert ser._values is result._values - else: - assert ser._values is not result._values - assert ser._values is arr + self.assert_series_equal(ser, ser_orig) def test_fillna_length_mismatch(self, data_missing): msg = "Length of 'value' does not match." diff --git a/pandas/tests/extension/conftest.py b/pandas/tests/extension/conftest.py index 3827ba234cfd8..0d14128e3bebf 100644 --- a/pandas/tests/extension/conftest.py +++ b/pandas/tests/extension/conftest.py @@ -2,7 +2,10 @@ import pytest -from pandas import Series +from pandas import ( + Series, + options, +) @pytest.fixture @@ -193,3 +196,11 @@ def invalid_scalar(data): If the array can hold any item (i.e. object dtype), then use pytest.skip. """ return object.__new__(object) + + +@pytest.fixture +def using_copy_on_write() -> bool: + """ + Fixture to check if Copy-on-Write is enabled. + """ + return options.mode.copy_on_write and options.mode.data_manager == "block" diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index d7b9874555046..37a7d78d3aa3d 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -301,17 +301,9 @@ def test_searchsorted(self, data_for_sorting): def test_equals(self, data, na_value, as_series): super().test_equals(data, na_value, as_series) - def test_fillna_copy_frame(self, data_missing, using_copy_on_write): - arr = data_missing.take([1, 1]) - df = pd.DataFrame({"A": arr}) - - filled_val = df.iloc[0, 0] - result = df.fillna(filled_val) - - if using_copy_on_write: - assert df.A.values is result.A.values - else: - assert df.A.values is not result.A.values + @pytest.mark.skip("fill-value is interpreted as a dict of values") + def test_fillna_copy_frame(self, data_missing): + super().test_fillna_copy_frame(data_missing) class TestCasting(BaseJSON, base.BaseCastingTests): diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index 0ad2de9e834fa..92796c604333d 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -116,11 +116,6 @@ def test_combine_add(self, data_repeated): # Timestamp.__add__(Timestamp) not defined pass - def test_fillna_copy_series(self, data_missing, using_copy_on_write): - super().test_fillna_copy_series( - data_missing, no_op_with_cow=using_copy_on_write - ) - class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests): pass diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 3cf24d848e453..0f916cea9d518 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -132,11 +132,6 @@ def test_combine_add(self, data_repeated): def test_fillna_length_mismatch(self, data_missing): super().test_fillna_length_mismatch(data_missing) - def test_fillna_copy_series(self, data_missing, using_copy_on_write): - super().test_fillna_copy_series( - data_missing, no_op_with_cow=using_copy_on_write - ) - class TestMissing(BaseInterval, base.BaseMissingTests): # Index.fillna only accepts scalar `value`, so we have to xfail all diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index 1ecd279e1f34b..cb1ebd87875e1 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -105,11 +105,6 @@ def test_diff(self, data, periods): else: super().test_diff(data, periods) - def test_fillna_copy_series(self, data_missing, using_copy_on_write): - super().test_fillna_copy_series( - data_missing, no_op_with_cow=using_copy_on_write - ) - class TestInterface(BasePeriodTests, base.BaseInterfaceTests): pass diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 745911871694c..2aeb2af567ea0 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -272,7 +272,7 @@ def test_fillna_frame(self, data_missing): class TestMethods(BaseSparseTests, base.BaseMethodsTests): _combine_le_expected_dtype = "Sparse[bool]" - def test_fillna_copy_frame(self, data_missing): + def test_fillna_copy_frame(self, data_missing, using_copy_on_write): arr = data_missing.take([1, 1]) df = pd.DataFrame({"A": arr}, copy=False) @@ -280,17 +280,24 @@ def test_fillna_copy_frame(self, data_missing): result = df.fillna(filled_val) if hasattr(df._mgr, "blocks"): - assert df.values.base is not result.values.base + if using_copy_on_write: + assert df.values.base is result.values.base + else: + assert df.values.base is not result.values.base assert df.A._values.to_dense() is arr.to_dense() - def test_fillna_copy_series(self, data_missing): + def test_fillna_copy_series(self, data_missing, using_copy_on_write): arr = data_missing.take([1, 1]) ser = pd.Series(arr) filled_val = ser[0] result = ser.fillna(filled_val) - assert ser._values is not result._values + if using_copy_on_write: + assert ser._values is result._values + + else: + assert ser._values is not result._values assert ser._values.to_dense() is arr.to_dense() @pytest.mark.xfail(reason="Not Applicable") diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py index 76ba4c974b3fd..8851b7669932d 100644 --- a/pandas/tests/groupby/test_raises.py +++ b/pandas/tests/groupby/test_raises.py @@ -303,7 +303,9 @@ def test_groupby_raises_datetime_np(how, by, groupby_series, groupby_func_np): @pytest.mark.parametrize("how", ["method", "agg", "transform"]) -def test_groupby_raises_category(how, by, groupby_series, groupby_func): +def test_groupby_raises_category( + how, by, groupby_series, groupby_func, using_copy_on_write +): # GH#50749 df = DataFrame( { @@ -370,7 +372,9 @@ def test_groupby_raises_category(how, by, groupby_series, groupby_func): TypeError, r"Cannot setitem on a Categorical with a new category \(0\), " + "set the categories first", - ), + ) + if not using_copy_on_write + else (None, ""), # no-op with CoW "first": (None, ""), "idxmax": (None, ""), "idxmin": (None, ""), @@ -491,7 +495,7 @@ def test_groupby_raises_category_np(how, by, groupby_series, groupby_func_np): @pytest.mark.parametrize("how", ["method", "agg", "transform"]) def test_groupby_raises_category_on_category( - how, by, groupby_series, groupby_func, observed + how, by, groupby_series, groupby_func, observed, using_copy_on_write ): # GH#50749 df = DataFrame( @@ -562,7 +566,9 @@ def test_groupby_raises_category_on_category( TypeError, r"Cannot setitem on a Categorical with a new category \(0\), " + "set the categories first", - ), + ) + if not using_copy_on_write + else (None, ""), # no-op with CoW "first": (None, ""), "idxmax": (ValueError, "attempt to get argmax of an empty sequence") if empty_groups
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51411
2023-02-15T18:39:48Z
2023-02-25T22:46:54Z
2023-02-25T22:46:54Z
2023-03-01T09:23:58Z
CLN: assorted comments
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index b5ff69d92492f..51c2486ac5c1d 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -7,6 +7,7 @@ from cython cimport Py_ssize_t cdef extern from "Python.h": + # TODO(cython3): from cpython.pyport cimport PY_SSIZE_T_MAX Py_ssize_t PY_SSIZE_T_MAX import numpy as np diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index 72b46d9e30684..1f6ae49b76adc 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -217,7 +217,6 @@ def count_level_2d( mask: np.ndarray, # ndarray[uint8_t, ndim=2, cast=True], labels: np.ndarray, # const intp_t[:] max_bin: int, - axis: int, ) -> np.ndarray: ... # np.ndarray[np.int64, ndim=2] def get_level_sorter( label: np.ndarray, # const int64_t[:] diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index d79f7068effc3..7f718fde79dd1 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -921,29 +921,19 @@ def get_level_sorter( def count_level_2d(ndarray[uint8_t, ndim=2, cast=True] mask, const intp_t[:] labels, Py_ssize_t max_bin, - int axis): + ): cdef: Py_ssize_t i, j, k, n ndarray[int64_t, ndim=2] counts - assert (axis == 0 or axis == 1) n, k = (<object>mask).shape - if axis == 0: - counts = np.zeros((max_bin, k), dtype="i8") - with nogil: - for i in range(n): - for j in range(k): - if mask[i, j]: - counts[labels[i], j] += 1 - - else: # axis == 1 - counts = np.zeros((n, max_bin), dtype="i8") - with nogil: - for i in range(n): - for j in range(k): - if mask[i, j]: - counts[i, labels[j]] += 1 + counts = np.zeros((n, max_bin), dtype="i8") + with nogil: + for i in range(n): + for j in range(k): + if mask[i, j]: + counts[i, labels[j]] += 1 return counts @@ -1710,6 +1700,7 @@ cdef class Validator: cdef bint is_valid_null(self, object value) except -1: return value is None or value is C_NA or util.is_nan(value) + # TODO: include decimal NA? cdef bint is_array_typed(self) except -1: return False diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 20a25afa6a51f..5bddaa61d3196 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -848,6 +848,9 @@ cdef class TextReader: with nogil: status = tokenize_nrows(self.parser, nrows, self.encoding_errors) + self._check_tokenize_status(status) + + cdef _check_tokenize_status(self, int status): if self.parser.warn_msg != NULL: print(PyUnicode_DecodeUTF8( self.parser.warn_msg, strlen(self.parser.warn_msg), @@ -879,15 +882,7 @@ cdef class TextReader: with nogil: status = tokenize_all_rows(self.parser, self.encoding_errors) - if self.parser.warn_msg != NULL: - print(PyUnicode_DecodeUTF8( - self.parser.warn_msg, strlen(self.parser.warn_msg), - self.encoding_errors), file=sys.stderr) - free(self.parser.warn_msg) - self.parser.warn_msg = NULL - - if status < 0: - raise_parser_error("Error tokenizing data", self.parser) + self._check_tokenize_status(status) if self.parser_start >= self.parser.lines: raise StopIteration diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 71dc3b523fca6..7e7aa93046430 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7814,7 +7814,7 @@ def combine( if self.empty and len(other) == other_idxlen: return other.copy() - # sorts if possible + # sorts if possible; otherwise align above ensures that these are set-equal new_columns = this.columns.union(other.columns) do_fill = fill_value is not None result = {} diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index eecf292e4c3c8..799d9cf350513 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1424,7 +1424,7 @@ def _wrap_applied_output_series( values: list[Series], not_indexed_same: bool, first_not_none, - key_index, + key_index: Index | None, is_transform: bool, ) -> DataFrame | Series: kwargs = first_not_none._construct_axes_dict() diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 8dcf7a0838349..bd7cdbdd40969 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1043,7 +1043,9 @@ def _concat_objects( # when the ax has duplicates # so we resort to this # GH 14776, 30667 + # TODO: can we re-use e.g. _reindex_non_unique? if ax.has_duplicates and not result.axes[self.axis].equals(ax): + # e.g. test_category_order_transformer target = algorithms.unique1d(ax._values) indexer, _ = result.index.get_indexer_non_unique(target) result = result.take(indexer, axis=self.axis) @@ -1460,6 +1462,7 @@ def _agg_py_fallback( NotImplementedError. """ # We get here with a) EADtypes and b) object dtype + assert alt is not None if values.ndim == 1: # For DataFrameGroupBy we only get here with ExtensionArray @@ -1775,7 +1778,7 @@ def hfunc(bvalues: ArrayLike) -> ArrayLike: else: masked = mask & ~isna(bvalues) - counted = lib.count_level_2d(masked, labels=ids, max_bin=ngroups, axis=1) + counted = lib.count_level_2d(masked, labels=ids, max_bin=ngroups) if is_series: assert counted.ndim == 2 assert counted.shape[0] == 1 diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 6031bdc62c38a..633d2c1ab30ac 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -78,7 +78,6 @@ LossySetitemError, can_hold_element, common_dtype_categorical_compat, - ensure_dtype_can_hold_na, find_result_type, infer_dtype_from, maybe_cast_pointwise_result, @@ -351,6 +350,7 @@ def _left_indexer_unique(self: _IndexT, other: _IndexT) -> npt.NDArray[np.intp]: # can_use_libjoin assures sv and ov are ndarrays sv = cast(np.ndarray, sv) ov = cast(np.ndarray, ov) + # similar but not identical to ov.searchsorted(sv) return libjoin.left_join_indexer_unique(sv, ov) @final @@ -3132,7 +3132,7 @@ def union(self, other, sort=None): if not is_dtype_equal(self.dtype, other.dtype): if ( isinstance(self, ABCMultiIndex) - and not is_object_dtype(unpack_nested_dtype(other)) + and not is_object_dtype(_unpack_nested_dtype(other)) and len(other) > 0 ): raise NotImplementedError( @@ -3213,6 +3213,8 @@ def _union(self, other: Index, sort): result_dups = algos.union_with_duplicates(self, other) return _maybe_try_sort(result_dups, sort) + # The rest of this method is analogous to Index._intersection_via_get_indexer + # Self may have duplicates; other already checked as unique # find indexes of things in "other" that are not in "self" if self._index_as_unique: @@ -3800,7 +3802,7 @@ def _should_partial_index(self, target: Index) -> bool: return False # See https://github.com/pandas-dev/pandas/issues/47772 the commented # out code can be restored (instead of hardcoding `return True`) - # once that issue if fixed + # once that issue is fixed # "Index" has no attribute "left" # return self.left._should_compare(target) # type: ignore[attr-defined] return True @@ -4778,6 +4780,9 @@ def _join_monotonic( assert other.dtype == self.dtype if self.equals(other): + # This is a convenient place for this check, but its correctness + # does not depend on monotonicity, so it could go earlier + # in the calling method. ret_index = other if how == "right" else self return ret_index, None, None @@ -5762,6 +5767,9 @@ def get_indexer_non_unique( that = target.astype(dtype, copy=False) return this.get_indexer_non_unique(that) + # TODO: get_indexer has fastpaths for both Categorical-self and + # Categorical-target. Can we do something similar here? + # Note: _maybe_promote ensures we never get here with MultiIndex # self and non-Multi target tgt_values = target._get_engine_target() @@ -5922,7 +5930,7 @@ def _get_indexer_non_comparable( If doing an inequality check, i.e. method is not None. """ if method is not None: - other = unpack_nested_dtype(target) + other = _unpack_nested_dtype(target) raise TypeError(f"Cannot compare dtypes {self.dtype} and {other.dtype}") no_matches = -1 * np.ones(target.shape, dtype=np.intp) @@ -5998,16 +6006,6 @@ def _find_common_type_compat(self, target) -> DtypeObj: Implementation of find_common_type that adjusts for Index-specific special cases. """ - if is_valid_na_for_dtype(target, self.dtype): - # e.g. setting NA value into IntervalArray[int64] - dtype = ensure_dtype_can_hold_na(self.dtype) - if is_dtype_equal(self.dtype, dtype): - raise NotImplementedError( - "This should not be reached. Please report a bug at " - "github.com/pandas-dev/pandas" - ) - return dtype - target_dtype, _ = infer_dtype_from(target, pandas_dtype=True) # special case: if one dtype is uint64 and the other a signed int, return object @@ -6040,7 +6038,7 @@ def _should_compare(self, other: Index) -> bool: # respectively. return False - other = unpack_nested_dtype(other) + other = _unpack_nested_dtype(other) dtype = other.dtype return self._is_comparable_dtype(dtype) or is_object_dtype(dtype) @@ -6052,6 +6050,8 @@ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: return dtype.kind == "b" elif is_numeric_dtype(self.dtype): return is_numeric_dtype(dtype) + # TODO: this was written assuming we only get here with object-dtype, + # which is nom longer correct. Can we specialize for EA? return True @final @@ -7141,7 +7141,7 @@ def get_unanimous_names(*indexes: Index) -> tuple[Hashable, ...]: return names -def unpack_nested_dtype(other: _IndexT) -> _IndexT: +def _unpack_nested_dtype(other: Index) -> Index: """ When checking if our dtype is comparable with another, we need to unpack CategoricalDtype to look at its categories.dtype. @@ -7155,12 +7155,10 @@ def unpack_nested_dtype(other: _IndexT) -> _IndexT: Index """ dtype = other.dtype - if is_categorical_dtype(dtype): + if isinstance(dtype, CategoricalDtype): # If there is ever a SparseIndex, this could get dispatched # here too. - # error: Item "dtype[Any]"/"ExtensionDtype" of "Union[dtype[Any], - # ExtensionDtype]" has no attribute "categories" - return dtype.categories # type: ignore[union-attr] + return dtype.categories return other diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 3d8948615f288..0d0fc4a779120 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2746,6 +2746,7 @@ def _get_loc_single_level_index(self, level_index: Index, key: Hashable) -> int: Index.get_loc : The get_loc method for (single-level) index. """ if is_scalar(key) and isna(key): + # TODO: need is_valid_na_for_dtype(key, level_index.dtype) return -1 else: return level_index.get_loc(key) @@ -2818,6 +2819,8 @@ def _maybe_to_slice(loc): ) if keylen == self.nlevels and self.is_unique: + # TODO: what if we have an IntervalIndex level? + # i.e. do we need _index_as_unique on that level? try: return self._engine.get_loc(key) except TypeError: @@ -3853,6 +3856,8 @@ def maybe_droplevels(index: Index, key) -> Index: # drop levels original_index = index if isinstance(key, tuple): + # Caller is responsible for ensuring the key is not an entry in the first + # level of the MultiIndex. for _ in key: try: index = index._drop_level_numbers([0]) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index d981d8e097dbb..c1435ebbe39ef 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1779,6 +1779,7 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc"): self.obj[key] = empty_value else: + # FIXME: GH#42099#issuecomment-864326014 self.obj[key] = infer_fill_value(value) new_indexer = convert_from_missing_indexer_tuple( @@ -1866,6 +1867,8 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str): self._setitem_with_indexer_frame_value(indexer, value, name) elif np.ndim(value) == 2: + # TODO: avoid np.ndim call in case it isn't an ndarray, since + # that will construct an ndarray, which will be wasteful self._setitem_with_indexer_2d_value(indexer, value) elif len(ilocs) == 1 and lplane_indexer == len(value) and not is_scalar(pi): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index db5cb4a70c8f1..0658b2039f085 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -429,6 +429,7 @@ def _maybe_downcast( return blocks if self.dtype == _dtype_obj: + # TODO: does it matter that self.dtype might not match blocks[i].dtype? # GH#44241 We downcast regardless of the argument; # respecting 'downcast=None' may be worthwhile at some point, # but ATM it breaks too much existing code. @@ -1817,39 +1818,38 @@ def _unwrap_setitem_indexer(self, indexer): """ # TODO: ATM this doesn't work for iget/_slice, can we change that? - if isinstance(indexer, tuple): + if isinstance(indexer, tuple) and len(indexer) == 2: # TODO(EA2D): not needed with 2D EAs # Should never have length > 2. Caller is responsible for checking. # Length 1 is reached vis setitem_single_block and setitem_single_column # each of which pass indexer=(pi,) - if len(indexer) == 2: - if all(isinstance(x, np.ndarray) and x.ndim == 2 for x in indexer): - # GH#44703 went through indexing.maybe_convert_ix - first, second = indexer - if not ( - second.size == 1 and (second == 0).all() and first.shape[1] == 1 - ): - raise NotImplementedError( - "This should not be reached. Please report a bug at " - "github.com/pandas-dev/pandas/" - ) - indexer = first[:, 0] - - elif lib.is_integer(indexer[1]) and indexer[1] == 0: - # reached via setitem_single_block passing the whole indexer - indexer = indexer[0] - - elif com.is_null_slice(indexer[1]): - indexer = indexer[0] - - elif is_list_like(indexer[1]) and indexer[1][0] == 0: - indexer = indexer[0] - - else: + if all(isinstance(x, np.ndarray) and x.ndim == 2 for x in indexer): + # GH#44703 went through indexing.maybe_convert_ix + first, second = indexer + if not ( + second.size == 1 and (second == 0).all() and first.shape[1] == 1 + ): raise NotImplementedError( "This should not be reached. Please report a bug at " "github.com/pandas-dev/pandas/" ) + indexer = first[:, 0] + + elif lib.is_integer(indexer[1]) and indexer[1] == 0: + # reached via setitem_single_block passing the whole indexer + indexer = indexer[0] + + elif com.is_null_slice(indexer[1]): + indexer = indexer[0] + + elif is_list_like(indexer[1]) and indexer[1][0] == 0: + indexer = indexer[0] + + else: + raise NotImplementedError( + "This should not be reached. Please report a bug at " + "github.com/pandas-dev/pandas/" + ) return indexer @property diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 3c357bd7516c0..a33ce8fd5c459 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -596,9 +596,6 @@ def _concatenate_join_units(join_units: list[JoinUnit], copy: bool) -> ArrayLike elif any(is_1d_only_ea_dtype(t.dtype) 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) # error: No overload variant of "__getitem__" of "ExtensionArray" matches # argument type "Tuple[int, slice]" diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 934d08341395c..4dbdd5e5b77fe 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -362,6 +362,7 @@ def ndarray_to_mgr( block_values = [nb] if len(columns) == 0: + # TODO: check len(values) == 0? block_values = [] return create_block_manager_from_blocks( @@ -506,6 +507,8 @@ def _prep_ndarraylike(values, copy: bool = True) -> np.ndarray: # We only get here with `not treat_as_nested(values)` if len(values) == 0: + # TODO: check for length-zero range, in which case return int64 dtype? + # TODO: re-use anything in try_cast? return np.empty((0, 0), dtype=object) elif isinstance(values, range): arr = range_to_ndarray(values) @@ -1007,6 +1010,12 @@ def convert(arr): try_float=coerce_float, convert_to_nullable_dtype=use_nullable_dtypes, ) + # Notes on cases that get here 2023-02-15 + # 1) we DO get here when arr is all Timestamps and dtype=None + # 2) disabling this doesn't break the world, so this must be + # getting caught at a higher level + # 3) passing convert_datetime to maybe_convert_objects get this right + # 4) convert_timedelta? if dtype is None: if arr.dtype == np.dtype("O"): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 9de801b732544..ccfa5ae57b255 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -994,6 +994,8 @@ def fast_xs(self, loc: int) -> SingleBlockManager: np.ndarray or ExtensionArray """ if len(self.blocks) == 1: + # TODO: this could be wrong if blk.mgr_locs is not slice(None)-like; + # is this ruled out in the general case? result = self.blocks[0].iget((slice(None), loc)) # in the case of a single block, the new block is a view block = new_block( diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 4a95daafd82a9..7461bad99462c 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -4024,6 +4024,10 @@ def get_blk_items(mgr): blk_items: list[Index] = get_blk_items(mgr) if len(data_columns): + # TODO: prove that we only get here with axis == 1? + # It is the case in all extant tests, but NOT the case + # outside this `if len(data_columns)` check. + axis, axis_labels = new_non_index_axes[0] new_labels = Index(axis_labels).difference(Index(data_columns)) mgr = frame.reindex(new_labels, axis=axis)._mgr diff --git a/pandas/io/sas/sas.pyx b/pandas/io/sas/sas.pyx index 4fe0f5ce91a51..6669686d7aa2c 100644 --- a/pandas/io/sas/sas.pyx +++ b/pandas/io/sas/sas.pyx @@ -1,5 +1,5 @@ # cython: language_level=3, initializedcheck=False -# cython: warn.undeclared=True, warn.maybe_uninitialized=True, warn.unused=True +# cython: warn.maybe_uninitialized=True, warn.unused=True from cython cimport Py_ssize_t from libc.stddef cimport size_t from libc.stdint cimport ( diff --git a/pandas/tests/extension/test_string.py b/pandas/tests/extension/test_string.py index 0743c1e26c62f..ee855bb1cde8c 100644 --- a/pandas/tests/extension/test_string.py +++ b/pandas/tests/extension/test_string.py @@ -113,8 +113,7 @@ def test_is_not_string_type(self, dtype): class TestInterface(base.BaseInterfaceTests): def test_view(self, data, request): if data.dtype.storage == "pyarrow": - mark = pytest.mark.xfail(reason="not implemented") - request.node.add_marker(mark) + pytest.skip(reason="2D support not implemented for ArrowStringArray") super().test_view(data) @@ -134,8 +133,7 @@ def test_constructor_from_list(self): class TestReshaping(base.BaseReshapingTests): def test_transpose(self, data, request): if data.dtype.storage == "pyarrow": - mark = pytest.mark.xfail(reason="not implemented") - request.node.add_marker(mark) + pytest.skip(reason="2D support not implemented for ArrowStringArray") super().test_transpose(data) @@ -146,8 +144,7 @@ class TestGetitem(base.BaseGetitemTests): class TestSetitem(base.BaseSetitemTests): 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) + pytest.skip(reason="2D support not implemented for ArrowStringArray") super().test_setitem_preserves_views(data) @@ -391,10 +388,7 @@ class Test2DCompat(base.Dim2CompatTests): @pytest.fixture(autouse=True) def arrow_not_supported(self, data, request): if isinstance(data, ArrowStringArray): - mark = pytest.mark.xfail( - reason="2D support not implemented for ArrowStringArray" - ) - request.node.add_marker(mark) + pytest.skip(reason="2D support not implemented for ArrowStringArray") def test_searchsorted_with_na_raises(data_for_sorting, as_series): diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 7ead3890c5130..8abcc52db0500 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -892,7 +892,6 @@ def test_pad_stable_sorting(fill_method): tm.assert_frame_equal(result, expected) -@pytest.mark.parametrize("test_series", [True, False]) @pytest.mark.parametrize( "freq", [ @@ -908,8 +907,8 @@ def test_pad_stable_sorting(fill_method): @pytest.mark.parametrize("periods", [1, -1]) @pytest.mark.parametrize("fill_method", ["ffill", "bfill", None]) @pytest.mark.parametrize("limit", [None, 1]) -def test_pct_change(test_series, freq, periods, fill_method, limit): - # GH 21200, 21621, 30463 +def test_pct_change(frame_or_series, freq, periods, fill_method, limit): + # GH 21200, 21621, 30463 vals = [3, np.nan, np.nan, np.nan, 1, 2, 4, 10, np.nan, 4] keys = ["a", "b"] key_v = np.repeat(keys, len(vals)) @@ -922,16 +921,17 @@ def test_pct_change(test_series, freq, periods, fill_method, limit): expected = grp["vals"].obj / grp["vals"].shift(periods) - 1 - if test_series: - result = df.groupby("key")["vals"].pct_change( - periods=periods, fill_method=fill_method, limit=limit, freq=freq - ) - tm.assert_series_equal(result, expected) + gb = df.groupby("key") + + if frame_or_series is Series: + gb = gb["vals"] else: - result = df.groupby("key").pct_change( - periods=periods, fill_method=fill_method, limit=limit, freq=freq - ) - tm.assert_frame_equal(result, expected.to_frame("vals")) + expected = expected.to_frame("vals") + + result = gb.pct_change( + periods=periods, fill_method=fill_method, limit=limit, freq=freq + ) + tm.assert_equal(result, expected) @pytest.mark.parametrize( @@ -1096,19 +1096,16 @@ def test_transform_invalid_name_raises(): g.transform("some_arbitrary_name") -@pytest.mark.parametrize( - "obj", - [ - DataFrame( - {"a": [0, 0, 0, 1, 1, 1], "b": range(6)}, - index=["A", "B", "C", "D", "E", "F"], - ), - Series([0, 0, 0, 1, 1, 1], index=["A", "B", "C", "D", "E", "F"]), - ], -) -def test_transform_agg_by_name(request, reduction_func, obj): +def test_transform_agg_by_name(request, reduction_func, frame_or_series): func = reduction_func + obj = DataFrame( + {"a": [0, 0, 0, 1, 1, 1], "b": range(6)}, + index=["A", "B", "C", "D", "E", "F"], + ) + if frame_or_series is Series: + obj = obj["a"] + g = obj.groupby(np.repeat([0, 1], 3)) if func == "corrwith" and isinstance(obj, Series): # GH#32293 @@ -1444,18 +1441,15 @@ def test_null_group_str_transformer_series(dropna, transformation_func): @pytest.mark.parametrize( - "func, series, expected_values", + "func, expected_values", [ - (Series.sort_values, False, [5, 4, 3, 2, 1]), - (lambda x: x.head(1), False, [5.0, np.nan, 3, 2, np.nan]), - # SeriesGroupBy already has correct behavior - (Series.sort_values, True, [5, 4, 3, 2, 1]), - (lambda x: x.head(1), True, [5.0, np.nan, 3.0, 2.0, np.nan]), + (Series.sort_values, [5, 4, 3, 2, 1]), + (lambda x: x.head(1), [5.0, np.nan, 3, 2, np.nan]), ], ) @pytest.mark.parametrize("keys", [["a1"], ["a1", "a2"]]) @pytest.mark.parametrize("keys_in_index", [True, False]) -def test_transform_aligns(func, series, expected_values, keys, keys_in_index): +def test_transform_aligns(func, frame_or_series, expected_values, keys, keys_in_index): # GH#45648 - transform should align with the input's index df = DataFrame({"a1": [1, 1, 3, 2, 2], "b": [5, 4, 3, 2, 1]}) if "a2" in keys: @@ -1464,12 +1458,12 @@ def test_transform_aligns(func, series, expected_values, keys, keys_in_index): df = df.set_index(keys, append=True) gb = df.groupby(keys) - if series: + if frame_or_series is Series: gb = gb["b"] result = gb.transform(func) expected = DataFrame({"b": expected_values}, index=df.index) - if series: + if frame_or_series is Series: expected = expected["b"] tm.assert_equal(result, expected) diff --git a/pandas/tests/strings/test_extract.py b/pandas/tests/strings/test_extract.py index e9193113d0220..22a5fd28efd8d 100644 --- a/pandas/tests/strings/test_extract.py +++ b/pandas/tests/strings/test_extract.py @@ -174,22 +174,24 @@ def test_extract_expand_capture_groups(any_string_dtype): tm.assert_frame_equal(result, expected) -def test_extract_expand_capture_groups_index(request, index, any_string_dtype): +def test_extract_expand_capture_groups_index(index, any_string_dtype): # https://github.com/pandas-dev/pandas/issues/6348 # not passing index to the extractor data = ["A1", "B2", "C"] - if len(index) < len(data): - request.node.add_marker(pytest.mark.xfail(reason="Index too short.")) + if len(index) == 0: + pytest.skip("Test requires len(index) > 0") + while len(index) < len(data): + index = index.repeat(2) index = index[: len(data)] - s = Series(data, index=index, dtype=any_string_dtype) + ser = Series(data, index=index, dtype=any_string_dtype) - result = s.str.extract(r"(\d)", expand=False) + result = ser.str.extract(r"(\d)", expand=False) expected = Series(["1", "2", np.nan], index=index, dtype=any_string_dtype) tm.assert_series_equal(result, expected) - result = s.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=False) + result = ser.str.extract(r"(?P<letter>\D)(?P<number>\d)?", expand=False) expected = DataFrame( [["A", "1"], ["B", "2"], ["C", np.nan]], columns=["letter", "number"],
Most of these are from a notes-to-self branch that I'm whittling down to get rid of. I was on the fence about adding some of these comments, but eventually decided that if I find them useful, someone else might too.
https://api.github.com/repos/pandas-dev/pandas/pulls/51410
2023-02-15T16:52:21Z
2023-02-15T20:59:23Z
2023-02-15T20:59:23Z
2023-02-15T21:00:09Z
STYLE remove absolufy-imports, use ruff
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2f13ac4c73fa0..a64f8245886ea 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -19,11 +19,6 @@ repos: rev: v0.0.244 hooks: - id: ruff -- repo: https://github.com/MarcoGorelli/absolufy-imports - rev: v0.3.1 - hooks: - - id: absolufy-imports - files: ^pandas/ - repo: https://github.com/jendrikseipp/vulture rev: 'v2.7' hooks: diff --git a/pyproject.toml b/pyproject.toml index 8cd0155aca09e..511cc6a4d46eb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -212,6 +212,8 @@ select = [ "Q", # pylint "PLE", "PLR", "PLW", + # tidy imports + "TID", ] ignore = [ @@ -273,6 +275,10 @@ exclude = [ "env", ] +[tool.ruff.per-file-ignores] +# relative imports allowed for asv_bench +"asv_bench/*" = ["TID"] + [tool.pylint.messages_control] max-line-length = 88 disable = [ diff --git a/scripts/tests/test_inconsistent_namespace_check.py b/scripts/tests/test_inconsistent_namespace_check.py index eb995158d8cb4..64f66e6168efe 100644 --- a/scripts/tests/test_inconsistent_namespace_check.py +++ b/scripts/tests/test_inconsistent_namespace_check.py @@ -1,6 +1,6 @@ import pytest -from ..check_for_inconsistent_pandas_namespace import ( +from scripts.check_for_inconsistent_pandas_namespace import ( check_for_inconsistent_pandas_namespace, ) diff --git a/scripts/tests/test_validate_docstrings.py b/scripts/tests/test_validate_docstrings.py index 0b7ab145b054a..c413d98957007 100644 --- a/scripts/tests/test_validate_docstrings.py +++ b/scripts/tests/test_validate_docstrings.py @@ -3,7 +3,7 @@ import pytest -from .. import validate_docstrings +from scripts import validate_docstrings class BadDocstrings: diff --git a/scripts/tests/test_validate_unwanted_patterns.py b/scripts/tests/test_validate_unwanted_patterns.py index ef93fd1d21981..81e06f758d700 100644 --- a/scripts/tests/test_validate_unwanted_patterns.py +++ b/scripts/tests/test_validate_unwanted_patterns.py @@ -2,7 +2,7 @@ import pytest -from .. import validate_unwanted_patterns +from scripts import validate_unwanted_patterns class TestBarePytestRaises:
closes #50812 no need for my lockdown project anymore
https://api.github.com/repos/pandas-dev/pandas/pulls/51408
2023-02-15T15:58:40Z
2023-02-16T16:52:27Z
2023-02-16T16:52:27Z
2023-02-16T16:52:35Z
CI: Fix windows build failures
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 2d38e6b75ee65..7abc8e5eb92cc 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -3,7 +3,6 @@ import numpy as np import pytest -from pandas.compat import is_platform_windows from pandas.errors import ( NumExprClobberingError, UndefinedVariableError, @@ -1321,9 +1320,7 @@ def test_ea_dtypes_and_scalar_operation(self, any_numeric_ea_and_arrow_dtype): { "a": Series([1, 3], dtype=any_numeric_ea_and_arrow_dtype), "b": Series([2, 4], dtype=any_numeric_ea_and_arrow_dtype), - "c": Series( - [1, 1], dtype="int64" if not is_platform_windows() else "int32" - ), + "c": Series([1, 1], dtype=result["c"].dtype), } ) tm.assert_frame_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. the dtype really doesn't matter for this test
https://api.github.com/repos/pandas-dev/pandas/pulls/51405
2023-02-15T13:25:02Z
2023-02-15T16:15:02Z
2023-02-15T16:15:02Z
2023-02-15T16:15:06Z
DOC: fix EX02 errors in docstrings
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 567ae6da92ae2..ac53b176f20c9 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -579,9 +579,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX02 --ignore_functions \ pandas.DataFrame.plot.line \ pandas.Series.plot.line \ - pandas.Series.sparse.density \ - pandas.Series.sparse.npoints \ - pandas.Series.sparse.sp_values \ pandas.Timestamp.fromtimestamp \ pandas.api.types.infer_dtype \ pandas.api.types.is_datetime64_any_dtype \ diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 7469e92436e1a..6860c1314bbf1 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -611,6 +611,7 @@ def sp_values(self) -> np.ndarray: Examples -------- + >>> from pandas.arrays import SparseArray >>> s = SparseArray([0, 0, 1, 0, 2], fill_value=0) >>> s.sp_values array([1, 2]) @@ -674,6 +675,7 @@ def density(self) -> float: Examples -------- + >>> from pandas.arrays import SparseArray >>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0) >>> s.density 0.6 @@ -687,6 +689,7 @@ def npoints(self) -> int: Examples -------- + >>> from pandas.arrays import SparseArray >>> s = SparseArray([0, 0, 1, 1, 1], fill_value=0) >>> s.npoints 3
Related to issue #51236 This PR enables functions: `pandas.Series.sparse.density` `pandas.Series.sparse.npoints` `pandas.Series.sparse.sp_values`
https://api.github.com/repos/pandas-dev/pandas/pulls/51404
2023-02-15T12:05:03Z
2023-02-15T15:10:45Z
2023-02-15T15:10:45Z
2023-02-15T15:10:46Z
BUG: Arithmetic inplace ops not respecting CoW
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 75aec514031b4..f6d6dd7f90b02 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -259,6 +259,9 @@ Copy-on-Write improvements - :meth:`DataFrame.replace` will now respect the Copy-on-Write mechanism when ``inplace=True``. +- Arithmetic operations that can be inplace, e.g. ``ser *= 2`` will now respect the + Copy-on-Write mechanism. + Copy-on-Write can be enabled through one of .. code-block:: python diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 78b0a8a7a6ded..96abd98bbdd75 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11737,7 +11737,11 @@ def _inplace_method(self, other, op): and is_dtype_equal(result.dtype, self.dtype) ): # GH#36498 this inplace op can _actually_ be inplace. - self._values[:] = result._values + # Item "ArrayManager" of "Union[ArrayManager, SingleArrayManager, + # BlockManager, SingleBlockManager]" has no attribute "setitem_inplace" + self._mgr.setitem_inplace( # type: ignore[union-attr] + slice(None), result._values + ) return self # Delete cacher diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index eca827bd60e0d..91419ba415fda 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1479,3 +1479,23 @@ def test_xs_multiindex(using_copy_on_write, using_array_manager, key, level, axi result.iloc[0, 0] = 0 tm.assert_frame_equal(df, df_orig) + + +def test_inplace_arithmetic_series(): + ser = Series([1, 2, 3]) + data = get_array(ser) + ser *= 2 + assert np.shares_memory(get_array(ser), data) + tm.assert_numpy_array_equal(data, get_array(ser)) + + +def test_inplace_arithmetic_series_with_reference(using_copy_on_write): + ser = Series([1, 2, 3]) + ser_orig = ser.copy() + view = ser[:] + ser *= 2 + if using_copy_on_write: + assert not np.shares_memory(get_array(ser), get_array(view)) + tm.assert_series_equal(ser_orig, view) + else: + assert np.shares_memory(get_array(ser), get_array(view)) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index d2d2b66df36d7..bcc1ae0183b97 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1988,17 +1988,22 @@ def test_arith_list_of_arraylike_raise(to_add): to_add + df -def test_inplace_arithmetic_series_update(): +def test_inplace_arithmetic_series_update(using_copy_on_write): # https://github.com/pandas-dev/pandas/issues/36373 df = DataFrame({"A": [1, 2, 3]}) + df_orig = df.copy() series = df["A"] vals = series._values series += 1 - assert series._values is vals + if using_copy_on_write: + assert series._values is not vals + tm.assert_frame_equal(df, df_orig) + else: + assert series._values is vals - expected = DataFrame({"A": [2, 3, 4]}) - tm.assert_frame_equal(df, expected) + expected = DataFrame({"A": [2, 3, 4]}) + tm.assert_frame_equal(df, expected) def test_arithemetic_multiindex_align(): diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 2243879050c0c..44c0b654db268 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1105,9 +1105,12 @@ def test_identity_slice_returns_new_object(self, using_copy_on_write): else: assert all(sliced_series[:3] == [7, 8, 9]) - @pytest.mark.xfail(reason="accidental fix reverted - GH37497") - def test_loc_copy_vs_view(self): + def test_loc_copy_vs_view(self, request, using_copy_on_write): # GH 15631 + + if not using_copy_on_write: + mark = pytest.mark.xfail(reason="accidental fix reverted - GH37497") + request.node.add_marker(mark) x = DataFrame(zip(range(3), range(3)), columns=["a", "b"]) y = x.copy()
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. We should add tests for all op-possibilities in a follow up
https://api.github.com/repos/pandas-dev/pandas/pulls/51403
2023-02-15T11:41:40Z
2023-02-15T18:03:30Z
2023-02-15T18:03:29Z
2023-02-15T18:03:34Z
TST: clip inplace doesn't modify views with CoW
diff --git a/pandas/tests/copy_view/test_clip.py b/pandas/tests/copy_view/test_clip.py new file mode 100644 index 0000000000000..6626f724ab7f3 --- /dev/null +++ b/pandas/tests/copy_view/test_clip.py @@ -0,0 +1,21 @@ +import numpy as np + +from pandas import DataFrame +import pandas._testing as tm +from pandas.tests.copy_view.util import get_array + + +def test_clip_inplace_reference(using_copy_on_write): + df = DataFrame({"a": [1.5, 2, 3]}) + df_copy = df.copy() + arr_a = get_array(df, "a") + view = df[:] + df.clip(lower=2, inplace=True) + + # Clip not actually inplace right now but could be + assert not np.shares_memory(get_array(df, "a"), arr_a) + + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + tm.assert_frame_equal(df_copy, view)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51402
2023-02-15T11:33:09Z
2023-02-15T22:43:55Z
2023-02-15T22:43:55Z
2023-02-15T22:50:18Z
ENH: Add support for Index.min/max with arrow string
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 75aec514031b4..14ae995d2fd57 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -308,6 +308,7 @@ Other enhancements - :meth:`Series.dropna` and :meth:`DataFrame.dropna` has gained ``ignore_index`` keyword to reset index (:issue:`31725`) - Improved error message in :func:`to_datetime` for non-ISO8601 formats, informing users about the position of the first error (:issue:`50361`) - Improved error message when trying to align :class:`DataFrame` objects (for example, in :func:`DataFrame.compare`) to clarify that "identically labelled" refers to both index and columns (:issue:`50083`) +- Added support for :meth:`Index.min` and :meth:`Index.max` for pyarrow string dtypes (:issue:`51397`) - Added :meth:`DatetimeIndex.as_unit` and :meth:`TimedeltaIndex.as_unit` to convert to different resolutions; supported resolutions are "s", "ms", "us", and "ns" (:issue:`50616`) - Added :meth:`Series.dt.unit` and :meth:`Series.dt.as_unit` to convert to different resolutions; supported resolutions are "s", "ms", "us", and "ns" (:issue:`51223`) - Added new argument ``dtype`` to :func:`read_sql` to be consistent with :func:`read_sql_query` (:issue:`50797`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 6031bdc62c38a..31e34379fd373 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -6928,8 +6928,7 @@ def min(self, axis=None, skipna: bool = True, *args, **kwargs): return self._na_value if not self._is_multi and not isinstance(self._values, np.ndarray): - # "ExtensionArray" has no attribute "min" - return self._values.min(skipna=skipna) # type: ignore[attr-defined] + return self._values._reduce(name="min", skipna=skipna) return super().min(skipna=skipna) @@ -6954,8 +6953,7 @@ def max(self, axis=None, skipna: bool = True, *args, **kwargs): return self._na_value if not self._is_multi and not isinstance(self._values, np.ndarray): - # "ExtensionArray" has no attribute "max" - return self._values.max(skipna=skipna) # type: ignore[attr-defined] + return self._values._reduce(name="max", skipna=skipna) return super().max(skipna=skipna) diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 788d03d5b7212..07ebe6fa04beb 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -158,10 +158,6 @@ def test_numpy_ufuncs_reductions(index, func, request): if len(index) == 0: return - if repr(index.dtype) == "string[pyarrow]": - mark = pytest.mark.xfail(reason="ArrowStringArray has no min/max") - request.node.add_marker(mark) - if isinstance(index, CategoricalIndex) and index.dtype.ordered is False: with pytest.raises(TypeError, match="is not ordered for"): func.reduce(index)
- [x] closes #51397 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51401
2023-02-15T11:23:04Z
2023-02-15T18:00:02Z
2023-02-15T18:00:01Z
2023-02-15T18:02:20Z
BUG: groupby.agg doesn't include grouping columns in result when selected
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index a8d6f3fce5bb7..2fba47d41f539 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1377,6 +1377,7 @@ Groupby/resample/rolling - Bug in :meth:`.DataFrameGroupBy.agg` with ``engine="numba"`` failing to respect ``as_index=False`` (:issue:`51228`) - Bug in :meth:`.DataFrameGroupBy.agg`, :meth:`.SeriesGroupBy.agg`, and :meth:`.Resampler.agg` would ignore arguments when passed a list of functions (:issue:`50863`) - Bug in :meth:`.DataFrameGroupBy.ohlc` ignoring ``as_index=False`` (:issue:`51413`) +- Bug in :meth:`DataFrameGroupBy.agg` after subsetting columns (e.g. ``.groupby(...)[["a", "b"]]``) would not include groupings in the result (:issue:`51186`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 67188d91bca70..499bef2b61046 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1359,21 +1359,15 @@ def _python_agg_general(self, func, *args, **kwargs): return self._wrap_aggregated_output(res) def _iterate_slices(self) -> Iterable[Series]: - obj = self._selected_obj + obj = self._obj_with_exclusions if self.axis == 1: obj = obj.T - if isinstance(obj, Series) and obj.name not in self.exclusions: + if isinstance(obj, Series): # Occurs when doing DataFrameGroupBy(...)["X"] yield obj else: for label, values in obj.items(): - if label in self.exclusions: - # Note: if we tried to just iterate over _obj_with_exclusions, - # we would break test_wrap_agg_out by yielding a column - # that is skipped here but not dropped from obj_with_exclusions - continue - yield values def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame: diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 6c591616e8469..d658de4a7d7c3 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -321,8 +321,8 @@ def func(ser): with pytest.raises(TypeError, match="Test error message"): grouped.aggregate(func) - result = grouped[[c for c in three_group if c != "C"]].aggregate(func) - exp_grouped = three_group.loc[:, three_group.columns != "C"] + result = grouped[["D", "E", "F"]].aggregate(func) + exp_grouped = three_group.loc[:, ["A", "B", "D", "E", "F"]] expected = exp_grouped.groupby(["A", "B"]).aggregate(func) tm.assert_frame_equal(result, expected) @@ -1521,3 +1521,16 @@ def foo2(x, b=2, c=0): [[8, 8], [9, 9], [10, 10]], index=Index([1, 2, 3]), columns=["foo1", "foo2"] ) tm.assert_frame_equal(result, expected) + + +def test_agg_groupings_selection(): + # GH#51186 - a selected grouping should be in the output of agg + df = DataFrame({"a": [1, 1, 2], "b": [3, 3, 4], "c": [5, 6, 7]}) + gb = df.groupby(["a", "b"]) + selected_gb = gb[["b", "c"]] + result = selected_gb.agg(lambda x: x.sum()) + index = MultiIndex( + levels=[[1, 2], [3, 4]], codes=[[0, 1], [0, 1]], names=["a", "b"] + ) + expected = DataFrame({"b": [6, 4], "c": [11, 7]}, index=index) + tm.assert_frame_equal(result, expected)
- [x] closes #51186 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51398
2023-02-15T03:08:30Z
2023-02-24T18:11:03Z
2023-02-24T18:11:03Z
2023-02-24T18:11:11Z
CLN: Simplify agg_list_like
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 2601271e27a69..da049218d5187 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -358,7 +358,7 @@ def agg_list_like(self) -> DataFrame | Series: keys = selected_obj.columns.take(indices) try: - concatenated = concat(results, keys=keys, axis=1, sort=False) + return concat(results, keys=keys, axis=1, sort=False) except TypeError as err: # we are concatting non-NDFrame objects, # e.g. a list of scalars @@ -370,16 +370,6 @@ def agg_list_like(self) -> DataFrame | Series: "cannot combine transform and aggregation operations" ) from err return result - else: - # Concat uses the first index to determine the final indexing order. - # The union of a shorter first index with the other indices causes - # the index sorting to be different from the order of the aggregating - # functions. Reindex if this is the case. - index_size = concatenated.index.size - full_ordered_index = next( - result.index for result in results if result.index.size == index_size - ) - return concatenated.reindex(full_ordered_index, copy=False) def agg_dict_like(self) -> DataFrame | Series: """
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This logic was added in #41017 to deal with partial failure that can no longer occur.
https://api.github.com/repos/pandas-dev/pandas/pulls/51396
2023-02-15T02:06:38Z
2023-02-15T19:52:20Z
2023-02-15T19:52:20Z
2023-02-15T20:00:22Z
DEPR: DataFrame.groupby(axis=1)
diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst index 1bd20b54242e6..0b2224fe9bb32 100644 --- a/doc/source/user_guide/categorical.rst +++ b/doc/source/user_guide/categorical.rst @@ -617,8 +617,8 @@ even if some categories are not present in the data: df = pd.DataFrame( data=[[1, 2, 3], [4, 5, 6]], columns=pd.MultiIndex.from_arrays([["A", "B", "B"], columns]), - ) - df.groupby(axis=1, level=1).sum() + ).T + df.groupby(level=1).sum() Groupby will also show "unused" categories: diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst index 15baedbac31ba..b5bf7ee25a50f 100644 --- a/doc/source/user_guide/groupby.rst +++ b/doc/source/user_guide/groupby.rst @@ -94,15 +94,13 @@ object (more on what the GroupBy object is later), you may do the following: ) speeds - # default is axis=0 grouped = speeds.groupby("class") - grouped = speeds.groupby("order", axis="columns") grouped = speeds.groupby(["class", "order"]) The mapping can be specified many different ways: * A Python function, to be called on each of the axis labels. -* A list or NumPy array of the same length as the selected axis. +* A list or NumPy array of the same length as the index. * A dict or ``Series``, providing a ``label -> group name`` mapping. * For ``DataFrame`` objects, a string indicating either a column name or an index level name to be used to group. @@ -147,8 +145,8 @@ but the specified columns grouped = df2.groupby(level=df2.index.names.difference(["B"])) grouped.sum() -These will split the DataFrame on its index (rows). We could also split by the -columns: +These will split the DataFrame on its index (rows). To split by columns, first do +a tranpose: .. ipython:: @@ -159,7 +157,7 @@ columns: ...: return 'consonant' ...: - In [5]: grouped = df.groupby(get_letter_type, axis=1) + In [5]: grouped = df.T.groupby(get_letter_type) pandas :class:`~pandas.Index` objects support duplicate values. If a non-unique index is used as the group key in a groupby operation, all values @@ -254,7 +252,7 @@ above example we have: .. ipython:: python df.groupby("A").groups - df.groupby(get_letter_type, axis=1).groups + df.T.groupby(get_letter_type).groups Calling the standard Python ``len`` function on the GroupBy object just returns the length of the ``groups`` dict, so it is largely just a convenience: @@ -496,7 +494,7 @@ An obvious one is aggregation via the grouped.aggregate(np.sum) As you can see, the result of the aggregation will have the group names as the -new index along the grouped axis. In the case of multiple keys, the result is a +new index. In the case of multiple keys, the result is a :ref:`MultiIndex <advanced.hierarchical>` by default, though this can be changed by using the ``as_index`` option: @@ -1556,7 +1554,8 @@ Regroup columns of a DataFrame according to their sum, and sum the aggregated on df = pd.DataFrame({"a": [1, 0, 0], "b": [0, 1, 0], "c": [1, 0, 0], "d": [2, 3, 4]}) df - df.groupby(df.sum(), axis=1).sum() + dft = df.T + dft.groupby(dft.sum()).sum() .. _groupby.multicolumn_factorization: diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst index 1b8fdc75d5e88..6a34998ccd0a6 100644 --- a/doc/source/user_guide/reshaping.rst +++ b/doc/source/user_guide/reshaping.rst @@ -350,7 +350,7 @@ some very expressive and fast data manipulations. df.stack().mean(1).unstack() # same result, another way - df.groupby(level=1, axis=1).mean() + df.T.groupby(level=1).mean() df.stack().groupby(level=1).mean() diff --git a/doc/source/whatsnew/v2.1.0.rst b/doc/source/whatsnew/v2.1.0.rst index 2ac20e97409e7..475ca7551f049 100644 --- a/doc/source/whatsnew/v2.1.0.rst +++ b/doc/source/whatsnew/v2.1.0.rst @@ -93,6 +93,7 @@ Other API changes Deprecations ~~~~~~~~~~~~ - Deprecating pinning ``group.name`` to each group in :meth:`SeriesGroupBy.aggregate` aggregations; if your operation requires utilizing the groupby keys, iterate over the groupby object instead (:issue:`41090`) +- Deprecated ``axis=1`` in :meth:`DataFrame.groupby` and in :class:`Grouper` constructor, do ``frame.T.groupby(...)`` instead (:issue:`51203`) - Deprecated passing a :class:`DataFrame` to :meth:`DataFrame.from_records`, use :meth:`DataFrame.set_index` or :meth:`DataFrame.drop` instead (:issue:`51353`) - Deprecated accepting slices in :meth:`DataFrame.take`, call ``obj[slicer]`` or pass a sequence of integers instead (:issue:`51539`) - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index aa3b10df742a2..8cd0ffadcc17c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8247,7 +8247,7 @@ def update( def groupby( self, by=None, - axis: Axis = 0, + axis: Axis | lib.NoDefault = no_default, level: IndexLabel | None = None, as_index: bool = True, sort: bool = True, @@ -8255,11 +8255,29 @@ def groupby( observed: bool = False, dropna: bool = True, ) -> DataFrameGroupBy: + if axis is not lib.no_default: + axis = self._get_axis_number(axis) + if axis == 1: + warnings.warn( + "DataFrame.groupby with axis=1 is deprecated. Do " + "`frame.T.groupby(...)` without axis instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + warnings.warn( + "The 'axis' keyword in DataFrame.groupby is deprecated and " + "will be removed in a future version.", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + axis = 0 + from pandas.core.groupby.generic import DataFrameGroupBy if level is None and by is None: raise TypeError("You have to supply one of 'by' and 'level'") - axis = self._get_axis_number(axis) return DataFrameGroupBy( obj=self, diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index dca2d5676f71d..1b8f08da07ea5 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -2238,6 +2238,10 @@ def fillna( the same results as :meth:`.DataFrame.fillna`. When the :class:`DataFrameGroupBy` ``axis`` argument is ``1``, using ``axis=0`` or ``axis=1`` here will produce the same results. + + .. deprecated:: 2.0.0 + Use frame.T.groupby(...) instead. + inplace : bool, default False Broken. Do not set to True. limit : int, default None @@ -2300,7 +2304,7 @@ def fillna( Propagate non-null values forward or backward within each group along rows. - >>> df.groupby([0, 0, 1, 1], axis=1).fillna(method="ffill") + >>> df.T.groupby(np.array([0, 0, 1, 1])).fillna(method="ffill").T key A B C 0 0.0 0.0 2.0 2.0 1 0.0 2.0 3.0 3.0 @@ -2308,7 +2312,7 @@ def fillna( 3 1.0 3.0 NaN NaN 4 1.0 1.0 NaN NaN - >>> df.groupby([0, 0, 1, 1], axis=1).fillna(method="bfill") + >>> df.T.groupby(np.array([0, 0, 1, 1])).fillna(method="bfill").T key A B C 0 0.0 NaN 2.0 NaN 1 0.0 2.0 3.0 NaN diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 55e14bc11246b..457352564f255 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3071,9 +3071,10 @@ def _nth( sort=self.sort, ) - grb = dropped.groupby( - grouper, as_index=self.as_index, sort=self.sort, axis=self.axis - ) + if self.axis == 1: + grb = dropped.T.groupby(grouper, as_index=self.as_index, sort=self.sort) + else: + grb = dropped.groupby(grouper, as_index=self.as_index, sort=self.sort) return grb.nth(n) @final @@ -3882,10 +3883,13 @@ def pct_change( fill_method = "ffill" limit = 0 filled = getattr(self, fill_method)(limit=limit) - fill_grp = filled.groupby( - self.grouper.codes, axis=self.axis, group_keys=self.group_keys - ) - shifted = fill_grp.shift(periods=periods, freq=freq, axis=self.axis) + if self.axis == 0: + fill_grp = filled.groupby(self.grouper.codes, group_keys=self.group_keys) + else: + fill_grp = filled.T.groupby(self.grouper.codes, group_keys=self.group_keys) + shifted = fill_grp.shift(periods=periods, freq=freq) + if self.axis == 1: + shifted = shifted.T return (filled / shifted) - 1 @final diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index f735ce682fc83..47d34e39bda6b 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -16,6 +16,7 @@ from pandas._config import using_copy_on_write +from pandas._libs import lib from pandas._typing import ( ArrayLike, Axis, @@ -258,10 +259,25 @@ def __init__( key=None, level=None, freq=None, - axis: Axis = 0, + axis: Axis | lib.NoDefault = lib.no_default, sort: bool = False, dropna: bool = True, ) -> None: + if type(self) is Grouper: + # i.e. not TimeGrouper + if axis is not lib.no_default: + warnings.warn( + "Grouper axis keyword is deprecated and will be removed in a " + "future version. To group on axis=1, use obj.T.groupby(...) " + "instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + axis = 0 + if axis is lib.no_default: + axis = 0 + self.key = key self.level = level self.freq = freq diff --git a/pandas/core/resample.py b/pandas/core/resample.py index f23256c64db2d..665e32829a57e 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1294,7 +1294,11 @@ def _downsample(self, how, **kwargs): # we are downsampling # we want to call the actual grouper method here - result = obj.groupby(self.grouper, axis=self.axis).aggregate(how, **kwargs) + if self.axis == 0: + result = obj.groupby(self.grouper).aggregate(how, **kwargs) + else: + # test_resample_axis1 + result = obj.T.groupby(self.grouper).aggregate(how, **kwargs).T return self._wrap_result(result) diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index a919f72c7d220..5dd95d78c7b79 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -377,7 +377,8 @@ def _all_key(key): margin = data[rows + values].groupby(rows, observed=observed).agg(aggfunc) cat_axis = 1 - for key, piece in table.groupby(level=0, axis=cat_axis, observed=observed): + for key, piece in table.T.groupby(level=0, observed=observed): + piece = piece.T all_key = _all_key(key) # we are going to mutate this, so need to copy! @@ -390,7 +391,7 @@ def _all_key(key): from pandas import DataFrame cat_axis = 0 - for key, piece in table.groupby(level=0, axis=cat_axis, observed=observed): + for key, piece in table.groupby(level=0, observed=observed): if len(cols) > 1: all_key = _all_key(key) else: diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py index 64f93e48b255c..64189fae5f578 100644 --- a/pandas/tests/apply/test_str.py +++ b/pandas/tests/apply/test_str.py @@ -268,9 +268,14 @@ def test_transform_groupby_kernel_frame(request, axis, float_frame, op): args = [0.0] if op == "fillna" else [] if axis in (0, "index"): ones = np.ones(float_frame.shape[0]) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" else: ones = np.ones(float_frame.shape[1]) - expected = float_frame.groupby(ones, axis=axis).transform(op, *args) + msg = "DataFrame.groupby with axis=1 is deprecated" + + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = float_frame.groupby(ones, axis=axis) + expected = gb.transform(op, *args) result = float_frame.transform(op, axis, *args) tm.assert_frame_equal(result, expected) @@ -283,7 +288,9 @@ def test_transform_groupby_kernel_frame(request, axis, float_frame, op): ones = np.ones(float_frame.shape[0]) else: ones = np.ones(float_frame.shape[1]) - expected2 = float_frame.groupby(ones, axis=axis).transform(op, *args) + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = float_frame.groupby(ones, axis=axis) + expected2 = gb2.transform(op, *args) result2 = float_frame.transform(op, axis, *args) tm.assert_frame_equal(result2, expected2) diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index d658de4a7d7c3..14bd466b052bf 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -124,7 +124,9 @@ def test_groupby_aggregation_multi_level_column(): columns=MultiIndex.from_tuples([("A", 0), ("A", 1), ("B", 0), ("B", 1)]), ) - gb = df.groupby(level=1, axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=1, axis=1) result = gb.sum(numeric_only=False) expected = DataFrame({0: [2.0, True, True, True], 1: [1, 0, 1, 1]}) @@ -253,7 +255,11 @@ def test_multiindex_groupby_mixed_cols_axis1(func, expected, dtype, result_dtype [[1, 2, 3, 4, 5, 6]] * 3, columns=MultiIndex.from_product([["a", "b"], ["i", "j", "k"]]), ).astype({("a", "j"): dtype, ("b", "j"): dtype}) - result = df.groupby(level=1, axis=1).agg(func) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=1, axis=1) + result = gb.agg(func) expected = DataFrame([expected] * 3, columns=["i", "j", "k"]).astype( result_dtype_dict ) @@ -278,7 +284,11 @@ def test_groupby_mixed_cols_axis1(func, expected_data, result_dtype_dict): columns=Index([10, 20, 10, 20], name="x"), dtype="int64", ).astype({10: "Int64"}) - result = df.groupby("x", axis=1).agg(func) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("x", axis=1) + result = gb.agg(func) expected = DataFrame( data=expected_data, index=Index([0, 1, 0], name="y"), @@ -1447,7 +1457,9 @@ def test_groupby_complex_raises(func): def test_multi_axis_1_raises(func): # GH#46995 df = DataFrame({"a": [1, 1, 2], "b": [3, 4, 5], "c": [6, 7, 8]}) - gb = df.groupby("a", axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("a", axis=1) with pytest.raises(NotImplementedError, match="axis other than 0 is not supported"): gb.agg(func) diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index 487daddd3d214..2fb7c8eb03bb0 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -122,10 +122,15 @@ def test_cython_agg_frame_columns(): # #2113 df = DataFrame({"x": [1, 2, 3], "y": [3, 4, 5]}) - df.groupby(level=0, axis="columns").mean() - df.groupby(level=0, axis="columns").mean() - df.groupby(level=0, axis="columns").mean() - df.groupby(level=0, axis="columns").mean() + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby(level=0, axis="columns").mean() + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby(level=0, axis="columns").mean() + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby(level=0, axis="columns").mean() + with tm.assert_produces_warning(FutureWarning, match=msg): + df.groupby(level=0, axis="columns").mean() def test_cython_agg_return_dict(): diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index c7657d3e8eea5..bc9388075218e 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -76,11 +76,15 @@ def test_regression_allowlist_methods(raw_frame, op, axis, skipna, sort): # explicitly test the allowlist methods if axis == 0: frame = raw_frame + msg = "The 'axis' keyword in DataFrame.groupby is deprecated and will be" else: frame = raw_frame.T + msg = "DataFrame.groupby with axis=1 is deprecated" - if op in AGG_FUNCTIONS_WITH_SKIPNA: + with tm.assert_produces_warning(FutureWarning, match=msg): grouped = frame.groupby(level=0, axis=axis, sort=sort) + + if op in AGG_FUNCTIONS_WITH_SKIPNA: result = getattr(grouped, op)(skipna=skipna) expected = frame.groupby(level=0).apply( lambda h: getattr(h, op)(axis=axis, skipna=skipna) @@ -89,7 +93,6 @@ def test_regression_allowlist_methods(raw_frame, op, axis, skipna, sort): expected = expected.sort_index(axis=axis) tm.assert_frame_equal(result, expected) else: - grouped = frame.groupby(level=0, axis=axis, sort=sort) result = getattr(grouped, op)() expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(axis=axis)) if sort: diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 5fa7ed15a01d4..a7ba1e8e81848 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -68,9 +68,11 @@ def test_apply_trivial(): columns=["key", "data"], ) expected = pd.concat([df.iloc[1:], df.iloc[1:]], axis=1, keys=["float64", "object"]) - result = df.groupby([str(x) for x in df.dtypes], axis=1).apply( - lambda x: df.iloc[1:] - ) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([str(x) for x in df.dtypes], axis=1) + result = gb.apply(lambda x: df.iloc[1:]) tm.assert_frame_equal(result, expected) @@ -82,9 +84,10 @@ def test_apply_trivial_fail(): columns=["key", "data"], ) expected = pd.concat([df, df], axis=1, keys=["float64", "object"]) - result = df.groupby([str(x) for x in df.dtypes], axis=1, group_keys=True).apply( - lambda x: df - ) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([str(x) for x in df.dtypes], axis=1, group_keys=True) + result = gb.apply(lambda x: df) tm.assert_frame_equal(result, expected) @@ -1102,10 +1105,15 @@ def test_apply_by_cols_equals_apply_by_rows_transposed(): columns=MultiIndex.from_product([["A", "B"], [1, 2]]), ) - by_rows = df.T.groupby(axis=0, level=0).apply( - lambda x: x.droplevel(axis=0, level=0) - ) - by_cols = df.groupby(axis=1, level=0).apply(lambda x: x.droplevel(axis=1, level=0)) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.T.groupby(axis=0, level=0) + by_rows = gb.apply(lambda x: x.droplevel(axis=0, level=0)) + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.groupby(axis=1, level=0) + by_cols = gb2.apply(lambda x: x.droplevel(axis=1, level=0)) tm.assert_frame_equal(by_cols, by_rows.T) tm.assert_frame_equal(by_cols, df) diff --git a/pandas/tests/groupby/test_apply_mutate.py b/pandas/tests/groupby/test_apply_mutate.py index 6823aeef258cb..1df55abdc038d 100644 --- a/pandas/tests/groupby/test_apply_mutate.py +++ b/pandas/tests/groupby/test_apply_mutate.py @@ -112,7 +112,10 @@ def add_column(grouped): grouped["sum", name] = grouped.sum(axis=1) return grouped - result = df.groupby(level=1, axis=1).apply(add_column) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=1, axis=1) + result = gb.apply(add_column) expected = pd.DataFrame( [ [1, 1, 1, 3, 1, 1, 1, 3], diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index fa8df166d56ac..dbbfab14d5c76 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1301,8 +1301,14 @@ def test_groupby_categorical_axis_1(code): # GH 13420 df = DataFrame({"a": [1, 2, 3, 4], "b": [-1, -2, -3, -4], "c": [5, 6, 7, 8]}) cat = Categorical.from_codes(code, categories=list("abc")) - result = df.groupby(cat, axis=1).mean() - expected = df.T.groupby(cat, axis=0).mean().T + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(cat, axis=1) + result = gb.mean() + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.T.groupby(cat, axis=0) + expected = gb2.mean().T tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py index f534a0c65fdbc..3f0150a2186a9 100644 --- a/pandas/tests/groupby/test_filters.py +++ b/pandas/tests/groupby/test_filters.py @@ -125,7 +125,11 @@ def test_filter_with_axis_in_groupby(): # issue 11041 index = pd.MultiIndex.from_product([range(10), [0, 1]]) data = DataFrame(np.arange(100).reshape(-1, 20), columns=index, dtype="int64") - result = data.groupby(level=0, axis=1).filter(lambda x: x.iloc[0, 0] > 10) + + msg = "DataFrame.groupby with axis=1" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = data.groupby(level=0, axis=1) + result = gb.filter(lambda x: x.iloc[0, 0] > 10) expected = data.iloc[:, 12:20] tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 535e8fa5b9354..e6709329f8f52 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1135,7 +1135,9 @@ def test_frame_describe_multikey(tsframe): expected = pd.concat(desc_groups, axis=1) tm.assert_frame_equal(result, expected) - groupedT = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + groupedT = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1) result = groupedT.describe() expected = tsframe.describe().T # reverting the change from https://github.com/pandas-dev/pandas/pull/35441/ diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 97e88a8545aa5..4682d262bf300 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -447,7 +447,9 @@ def test_frame_groupby(tsframe): def test_frame_groupby_columns(tsframe): mapping = {"A": 0, "B": 0, "C": 1, "D": 1} - grouped = tsframe.groupby(mapping, axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = tsframe.groupby(mapping, axis=1) # aggregate aggregated = grouped.aggregate(np.mean) @@ -456,7 +458,9 @@ def test_frame_groupby_columns(tsframe): # transform tf = lambda x: x - x.mean() - groupedT = tsframe.T.groupby(mapping, axis=0) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + groupedT = tsframe.T.groupby(mapping, axis=0) tm.assert_frame_equal(groupedT.transform(tf).T, grouped.transform(tf)) # iterate @@ -850,8 +854,10 @@ def test_groupby_as_index_corner(df, ts): ts.groupby(lambda x: x.weekday(), as_index=False) msg = "as_index=False only valid for axis=0" + depr_msg = "DataFrame.groupby with axis=1 is deprecated" with pytest.raises(ValueError, match=msg): - df.groupby(lambda x: x.lower(), as_index=False, axis=1) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(lambda x: x.lower(), as_index=False, axis=1) def test_groupby_multiple_key(): @@ -860,9 +866,11 @@ def test_groupby_multiple_key(): agged = grouped.sum() tm.assert_almost_equal(df.values, agged.values) - grouped = df.T.groupby( - [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1 - ) + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = df.T.groupby( + [lambda x: x.year, lambda x: x.month, lambda x: x.day], axis=1 + ) agged = grouped.agg(lambda x: x.sum()) tm.assert_index_equal(agged.index, df.columns) @@ -901,7 +909,9 @@ def test_raises_on_nuisance(df): grouped.sum() # won't work with axis = 1 - grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = df.groupby({"A": 0, "C": 0, "D": 1, "E": 1}, axis=1) msg = "does not support reduction 'sum'" with pytest.raises(TypeError, match=msg): grouped.agg(lambda x: x.sum(0, numeric_only=False)) @@ -1146,7 +1156,10 @@ def test_groupby_with_hier_columns(): result = df.groupby(level=0).mean() tm.assert_index_equal(result.columns, columns) - result = df.groupby(level=0, axis=1).mean() + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(level=0, axis=1) + result = gb.mean() tm.assert_index_equal(result.index, df.index) result = df.groupby(level=0).agg(np.mean) @@ -1155,7 +1168,9 @@ def test_groupby_with_hier_columns(): result = df.groupby(level=0).apply(lambda x: x.mean()) tm.assert_index_equal(result.columns, columns) - result = df.groupby(level=0, axis=1).agg(lambda x: x.mean(1)) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(level=0, axis=1) + result = gb.agg(lambda x: x.mean(1)) tm.assert_index_equal(result.columns, Index(["A", "B"])) tm.assert_index_equal(result.index, df.index) @@ -2127,7 +2142,11 @@ def test_groupby_axis_1(group_name): df.index.name = "y" df.columns.name = "x" - results = df.groupby(group_name, axis=1).sum() + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(group_name, axis=1) + + results = gb.sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) @@ -2135,7 +2154,9 @@ def test_groupby_axis_1(group_name): iterables = [["bar", "baz", "foo"], ["one", "two"]] mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) - results = df.groupby(group_name, axis=1).sum() + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(group_name, axis=1) + results = gb.sum() expected = df.T.groupby(group_name).sum().T tm.assert_frame_equal(results, expected) @@ -2288,8 +2309,12 @@ def test_groupby_crash_on_nunique(axis): axis_number = df._get_axis_number(axis) if not axis_number: df = df.T + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + else: + msg = "DataFrame.groupby with axis=1 is deprecated" - gb = df.groupby(axis=axis_number, level=0) + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(axis=axis_number, level=0) result = gb.nunique() expected = DataFrame({"A": [1, 2], "D": [1, 1]}, index=dti) @@ -2301,11 +2326,13 @@ def test_groupby_crash_on_nunique(axis): if axis_number == 0: # same thing, but empty columns - gb2 = df[[]].groupby(axis=axis_number, level=0) + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df[[]].groupby(axis=axis_number, level=0) exp = expected[[]] else: # same thing, but empty rows - gb2 = df.loc[[]].groupby(axis=axis_number, level=0) + with tm.assert_produces_warning(FutureWarning, match=msg): + gb2 = df.loc[[]].groupby(axis=axis_number, level=0) # default for empty when we can't infer a dtype is float64 exp = expected.loc[[]].astype(np.float64) @@ -2385,7 +2412,10 @@ def test_subsetting_columns_keeps_attrs(klass, attr, value): def test_subsetting_columns_axis_1(): # GH 37725 - g = DataFrame({"A": [1], "B": [2], "C": [3]}).groupby([0, 0, 1], axis=1) + df = DataFrame({"A": [1], "B": [2], "C": [3]}) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + g = df.groupby([0, 0, 1], axis=1) match = "Cannot subset columns when using axis=1" with pytest.raises(ValueError, match=match): g[["A", "B"]].sum() diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index f5bbfce560d33..c3081069d9330 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -210,7 +210,10 @@ def test_grouper_creation_bug(self): result = g.sum() tm.assert_frame_equal(result, expected) - g = df.groupby(Grouper(key="A", axis=0)) + msg = "Grouper axis keyword is deprecated and will be removed" + with tm.assert_produces_warning(FutureWarning, match=msg): + gpr = Grouper(key="A", axis=0) + g = df.groupby(gpr) result = g.sum() tm.assert_frame_equal(result, expected) @@ -338,7 +341,9 @@ def test_groupby_categorical_index_and_columns(self, observed): ) cat_columns = CategoricalIndex(columns, categories=categories, ordered=True) df = DataFrame(data=data, columns=cat_columns) - result = df.groupby(axis=1, level=0, observed=observed).sum() + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = df.groupby(axis=1, level=0, observed=observed).sum() expected_data = np.array([[4, 2], [4, 2], [4, 2], [4, 2], [4, 2]], int) expected_columns = CategoricalIndex( categories, categories=categories, ordered=True @@ -348,7 +353,9 @@ def test_groupby_categorical_index_and_columns(self, observed): # test transposed version df = DataFrame(data.T, index=cat_columns) - result = df.groupby(axis=0, level=0, observed=observed).sum() + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby(axis=0, level=0, observed=observed).sum() expected = DataFrame(data=expected_data.T, index=expected_columns) tm.assert_frame_equal(result, expected) @@ -453,7 +460,10 @@ def test_multiindex_passthru(self): df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) df.columns = MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)]) - result = df.groupby(axis=1, level=[0, 1]).first() + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + gb = df.groupby(axis=1, level=[0, 1]) + result = gb.first() tm.assert_frame_equal(result, df) def test_multiindex_negative_level(self, mframe): @@ -559,9 +569,10 @@ def test_groupby_level(self, sort, mframe, df): tm.assert_frame_equal(result1, expected1) # axis=1 - - result0 = frame.T.groupby(level=0, axis=1, sort=sort).sum() - result1 = frame.T.groupby(level=1, axis=1, sort=sort).sum() + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result0 = frame.T.groupby(level=0, axis=1, sort=sort).sum() + result1 = frame.T.groupby(level=1, axis=1, sort=sort).sum() tm.assert_frame_equal(result0, expected0.T) tm.assert_frame_equal(result1, expected1.T) @@ -577,10 +588,15 @@ def test_groupby_level_index_names(self, axis): ) if axis in (1, "columns"): df = df.T - df.groupby(level="exp", axis=axis) + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + else: + depr_msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(level="exp", axis=axis) msg = f"level name foo is not the name of the {df._get_axis_name(axis)}" with pytest.raises(ValueError, match=msg): - df.groupby(level="foo", axis=axis) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.groupby(level="foo", axis=axis) @pytest.mark.parametrize("sort", [True, False]) def test_groupby_level_with_nas(self, sort): @@ -958,7 +974,9 @@ def test_multi_iter_frame(self, three_group): # axis = 1 three_levels = three_group.groupby(["A", "B", "C"]).mean() - grouped = three_levels.T.groupby(axis=1, level=(1, 2)) + depr_msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + grouped = three_levels.T.groupby(axis=1, level=(1, 2)) for key, group in grouped: pass diff --git a/pandas/tests/groupby/test_indexing.py b/pandas/tests/groupby/test_indexing.py index 06b77c8f21e30..1c22da68499f8 100644 --- a/pandas/tests/groupby/test_indexing.py +++ b/pandas/tests/groupby/test_indexing.py @@ -281,7 +281,9 @@ def column_group_df(): def test_column_axis(column_group_df): - g = column_group_df.groupby(column_group_df.iloc[1], axis=1) + msg = "DataFrame.groupby with axis=1" + with tm.assert_produces_warning(FutureWarning, match=msg): + g = column_group_df.groupby(column_group_df.iloc[1], axis=1) result = g._positional_selector[1:-1] expected = column_group_df.iloc[:, [1, 3]] diff --git a/pandas/tests/groupby/test_missing.py b/pandas/tests/groupby/test_missing.py index 63772c24ca34b..d2939573fb994 100644 --- a/pandas/tests/groupby/test_missing.py +++ b/pandas/tests/groupby/test_missing.py @@ -94,8 +94,13 @@ def test_fill_consistency(): np.nan, ] - expected = df.groupby(level=0, axis=0).fillna(method="ffill") - result = df.T.groupby(level=0, axis=1).fillna(method="ffill").T + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby(level=0, axis=0).fillna(method="ffill") + + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.T.groupby(level=0, axis=1).fillna(method="ffill").T tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index 874b37120cc23..61b20077cdcd0 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -534,7 +534,9 @@ def test_groupby_head_tail_axis_1(op, n, expected_cols): df = DataFrame( [[1, 2, 3], [1, 4, 5], [2, 6, 7], [3, 8, 9]], columns=["A", "B", "C"] ) - g = df.groupby([0, 0, 1], axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + g = df.groupby([0, 0, 1], axis=1) expected = df.iloc[:, expected_cols] result = getattr(g, op)(n) tm.assert_frame_equal(result, expected) @@ -757,7 +759,10 @@ def test_groupby_nth_with_column_axis(): index=["z", "y"], columns=["C", "B", "A"], ) - result = df.groupby(df.iloc[1], axis=1).nth(0) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(df.iloc[1], axis=1) + result = gb.nth(0) expected = df.iloc[:, [0, 2]] tm.assert_frame_equal(result, expected) @@ -780,7 +785,9 @@ def test_nth_slices_with_column_axis( start, stop, expected_values, expected_columns, method ): df = DataFrame([range(5)], columns=[list("ABCDE")]) - gb = df.groupby([5, 5, 5, 6, 6], axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([5, 5, 5, 6, 6], axis=1) result = { "call": lambda start, stop: gb.nth(slice(start, stop)), "index": lambda start, stop: gb.nth[start:stop], diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py index 79354e550d3f6..bc0422d41e74a 100644 --- a/pandas/tests/groupby/test_quantile.py +++ b/pandas/tests/groupby/test_quantile.py @@ -396,7 +396,10 @@ def test_columns_groupby_quantile(): index=list("XYZ"), columns=pd.Series(list("ABAB"), name="col"), ) - result = df.groupby("col", axis=1).quantile(q=[0.8, 0.2]) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("col", axis=1) + result = gb.quantile(q=[0.8, 0.2]) expected = DataFrame( [ [1.6, 0.4, 2.6, 1.4], diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py index 0dd845bc35482..f29e2545cde14 100644 --- a/pandas/tests/groupby/test_raises.py +++ b/pandas/tests/groupby/test_raises.py @@ -13,6 +13,7 @@ Grouper, Series, ) +import pandas._testing as tm from pandas.tests.groupby import get_groupby_method_args @@ -628,6 +629,8 @@ def test_groupby_raises_category_on_category( def test_subsetting_columns_axis_1_raises(): # GH 35443 df = DataFrame({"a": [1], "b": [2], "c": [3]}) - gb = df.groupby("a", axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby("a", axis=1) with pytest.raises(ValueError, match="Cannot subset columns when using axis=1"): gb["b"] diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index d0b848a567346..9f42f6ad72591 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -619,7 +619,9 @@ def test_rank_multiindex(): axis=1, ) - gb = df.groupby(level=0, axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=0, axis=1) result = gb.rank(axis=1) expected = concat( @@ -639,7 +641,9 @@ def test_groupby_axis0_rank_axis1(): {0: [1, 3, 5, 7], 1: [2, 4, 6, 8], 2: [1.5, 3.5, 5.5, 7.5]}, index=["a", "a", "b", "b"], ) - gb = df.groupby(level=0, axis=0) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=0, axis=0) res = gb.rank(axis=1) @@ -661,7 +665,9 @@ def test_groupby_axis0_cummax_axis1(): {0: [1, 3, 5, 7], 1: [2, 4, 6, 8], 2: [1.5, 3.5, 5.5, 7.5]}, index=["a", "a", "b", "b"], ) - gb = df.groupby(level=0, axis=0) + msg = "The 'axis' keyword in DataFrame.groupby is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(level=0, axis=0) cmax = gb.cummax(axis=1) expected = df[[0, 1]].astype(np.float64) diff --git a/pandas/tests/groupby/test_size.py b/pandas/tests/groupby/test_size.py index c0c98562eda68..e29f87992f8a1 100644 --- a/pandas/tests/groupby/test_size.py +++ b/pandas/tests/groupby/test_size.py @@ -39,7 +39,9 @@ def test_size_axis_1(df, axis_1, by, sort, dropna): if tm.is_integer_dtype(expected.index) and not any(x is None for x in by): expected.index = expected.index.astype(np.int_) - grouped = df.groupby(by=by, axis=axis_1, sort=sort, dropna=dropna) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = df.groupby(by=by, axis=axis_1, sort=sort, dropna=dropna) result = grouped.size() tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index 2c3c2277ed627..5477ad75a56f7 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -233,7 +233,9 @@ def education_df(): def test_axis(education_df): - gp = education_df.groupby("country", axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gp = education_df.groupby("country", axis=1) with pytest.raises(NotImplementedError, match="axis"): gp.value_counts() diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 8abcc52db0500..27ffeb9247556 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -149,7 +149,9 @@ def test_transform_broadcast(tsframe, ts): assert_fp_equal(res[col], agged[col]) # group columns - grouped = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = tsframe.groupby({"A": 0, "B": 0, "C": 1, "D": 1}, axis=1) result = grouped.transform(np.mean) tm.assert_index_equal(result.index, tsframe.index) tm.assert_index_equal(result.columns, tsframe.columns) @@ -165,7 +167,10 @@ def test_transform_axis_1(request, transformation_func): df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"]) args = get_groupby_method_args(transformation_func, df) - result = df.groupby([0, 0, 1], axis=1).transform(transformation_func, *args) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([0, 0, 1], axis=1) + result = gb.transform(transformation_func, *args) expected = df.T.groupby([0, 0, 1]).transform(transformation_func, *args).T if transformation_func in ["diff", "shift"]: @@ -187,7 +192,11 @@ def test_transform_axis_1_reducer(request, reduction_func): request.node.add_marker(marker) df = DataFrame({"a": [1, 2], "b": [3, 4], "c": [5, 6]}, index=["x", "y"]) - result = df.groupby([0, 0, 1], axis=1).transform(reduction_func) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby([0, 0, 1], axis=1) + + result = gb.transform(reduction_func) expected = df.T.groupby([0, 0, 1]).transform(reduction_func).T tm.assert_equal(result, expected) @@ -212,7 +221,9 @@ def test_transform_axis_ts(tsframe): tm.assert_frame_equal(result, expected) ts = ts.T - grouped = ts.groupby(lambda x: x.weekday(), axis=1, group_keys=False) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = ts.groupby(lambda x: x.weekday(), axis=1, group_keys=False) result = ts - grouped.transform("mean") expected = grouped.apply(lambda x: (x.T - x.mean(1)).T) tm.assert_frame_equal(result, expected) @@ -225,7 +236,9 @@ def test_transform_axis_ts(tsframe): tm.assert_frame_equal(result, expected) ts = ts.T - grouped = ts.groupby(lambda x: x.weekday(), axis=1, group_keys=False) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = ts.groupby(lambda x: x.weekday(), axis=1, group_keys=False) result = ts - grouped.transform("mean") expected = grouped.apply(lambda x: (x.T - x.mean(1)).T) tm.assert_frame_equal(result, expected) @@ -770,9 +783,12 @@ def test_transform_with_non_scalar_group(): np.random.randint(1, 10, (4, 12)), columns=cols, index=["A", "C", "G", "T"] ) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = df.groupby(axis=1, level=1) msg = "transform must return a scalar value for each group.*" with pytest.raises(ValueError, match=msg): - df.groupby(axis=1, level=1).transform(lambda z: z.div(z.sum(axis=1), axis=0)) + gb.transform(lambda z: z.div(z.sum(axis=1), axis=0)) @pytest.mark.parametrize( diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index 29276eba09346..c47a5a55dfcf6 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -351,7 +351,9 @@ def test_boxplot_legacy2(self): def test_boxplot_legacy3(self): tuples = zip(string.ascii_letters[:10], range(10)) df = DataFrame(np.random.rand(10, 3), index=MultiIndex.from_tuples(tuples)) - grouped = df.unstack(level=1).groupby(level=0, axis=1) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = df.unstack(level=1).groupby(level=0, axis=1) with tm.assert_produces_warning(UserWarning, check_stacklevel=False): axes = _check_plot_works(grouped.boxplot, return_type="axes") self._check_axes_shape(list(axes.values), axes_num=3, layout=(2, 2)) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index d7ee7744ebcd4..ac262495ede3c 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -642,7 +642,9 @@ def test_resample_dup_index(): ) df.iloc[3, :] = np.nan result = df.resample("Q", axis=1).mean() - expected = df.groupby(lambda x: int((x.month - 1) / 3), axis=1).mean() + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.groupby(lambda x: int((x.month - 1) / 3), axis=1).mean() expected.columns = [Period(year=2000, quarter=i + 1, freq="Q") for i in range(4)] tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 023411f486c6a..f8e1128042dbb 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -27,7 +27,11 @@ def test_reindex_level(self, multiindex_year_month_day_dataframe_random_data): tm.assert_series_equal(result, expected, check_names=False) # axis=1 - month_sums = ymd.T.groupby("month", axis=1).sum() + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + gb = ymd.T.groupby("month", axis=1) + + month_sums = gb.sum() result = month_sums.reindex(columns=ymd.index, level=1) expected = ymd.groupby(level="month").transform(np.sum).T tm.assert_frame_equal(result, expected) @@ -96,7 +100,9 @@ def test_groupby_level_no_obs(self): df = DataFrame([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], columns=midx) df1 = df.loc(axis=1)[df.columns.map(lambda u: u[0] in ["f2", "f3"])] - grouped = df1.groupby(axis=1, level=0) + msg = "DataFrame.groupby with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = df1.groupby(axis=1, level=0) result = grouped.sum() assert (result.columns == ["f2", "f3"]).all()
- [x] closes #51203 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51395
2023-02-14T23:45:44Z
2023-03-04T02:21:37Z
2023-03-04T02:21:37Z
2023-08-30T19:27:57Z
CI: Pin matplotlib to < 3.7.0
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index 28ff56d8619b9..e8d67a47c88ff 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -33,7 +33,7 @@ dependencies: - gcsfs - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 - numba - numexpr - openpyxl diff --git a/ci/deps/actions-311.yaml b/ci/deps/actions-311.yaml index 32e3fe740b431..7898462eb9327 100644 --- a/ci/deps/actions-311.yaml +++ b/ci/deps/actions-311.yaml @@ -33,7 +33,7 @@ dependencies: - gcsfs - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 # - numba not compatible with 3.11 - numexpr - openpyxl diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml index a2f22de43fb23..00827a5e1b73c 100644 --- a/ci/deps/actions-38-downstream_compat.yaml +++ b/ci/deps/actions-38-downstream_compat.yaml @@ -34,7 +34,7 @@ dependencies: - gcsfs - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 - numba - numexpr - openpyxl diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml index e17941f93ecf1..36a3c401f69c6 100644 --- a/ci/deps/actions-38.yaml +++ b/ci/deps/actions-38.yaml @@ -33,7 +33,7 @@ dependencies: - gcsfs - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 - numba - numexpr - openpyxl diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index ed8dc6f760254..31342d00be386 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -33,7 +33,7 @@ dependencies: - gcsfs - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 - numba - numexpr - openpyxl diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml index 4d406460eab70..c024fca544e61 100644 --- a/ci/deps/circle-38-arm64.yaml +++ b/ci/deps/circle-38-arm64.yaml @@ -33,7 +33,7 @@ dependencies: - gcsfs - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 - numba - numexpr - openpyxl diff --git a/environment.yml b/environment.yml index aad0c1ca8588f..b28cbfe168606 100644 --- a/environment.yml +++ b/environment.yml @@ -36,7 +36,7 @@ dependencies: - ipython - jinja2 - lxml - - matplotlib>=3.6.1 + - matplotlib>=3.6.1, <3.7.0 - numba>=0.53.1 - numexpr>=2.8.0 # pin for "Run checks on imported code" job - openpyxl diff --git a/requirements-dev.txt b/requirements-dev.txt index a06cff7cd2ccd..8979b9b14d05c 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -25,7 +25,7 @@ gcsfs ipython jinja2 lxml -matplotlib>=3.6.1 +matplotlib>=3.6.1, <3.7.0 numba>=0.53.1 numexpr>=2.8.0 openpyxl
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51393
2023-02-14T22:06:15Z
2023-02-15T10:00:45Z
2023-02-15T10:00:44Z
2023-03-15T15:49:33Z
CI: Pin openpyxl to < 3.1.1
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index 28ff56d8619b9..84766a2f85f0e 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -36,7 +36,7 @@ dependencies: - matplotlib>=3.6.1 - numba - numexpr - - openpyxl + - openpyxl<3.1.1 - odfpy - pandas-gbq - psycopg2 diff --git a/ci/deps/actions-311.yaml b/ci/deps/actions-311.yaml index 32e3fe740b431..9e5ab8016d0d0 100644 --- a/ci/deps/actions-311.yaml +++ b/ci/deps/actions-311.yaml @@ -36,7 +36,7 @@ dependencies: - matplotlib>=3.6.1 # - numba not compatible with 3.11 - numexpr - - openpyxl + - openpyxl<3.1.1 - odfpy - pandas-gbq - psycopg2 diff --git a/ci/deps/actions-38-downstream_compat.yaml b/ci/deps/actions-38-downstream_compat.yaml index a2f22de43fb23..b5bcfcf04dc3e 100644 --- a/ci/deps/actions-38-downstream_compat.yaml +++ b/ci/deps/actions-38-downstream_compat.yaml @@ -37,7 +37,7 @@ dependencies: - matplotlib>=3.6.1 - numba - numexpr - - openpyxl + - openpyxl<3.1.1 - odfpy - psycopg2 - pyarrow diff --git a/ci/deps/actions-38.yaml b/ci/deps/actions-38.yaml index e17941f93ecf1..907fd9692eaec 100644 --- a/ci/deps/actions-38.yaml +++ b/ci/deps/actions-38.yaml @@ -36,7 +36,7 @@ dependencies: - matplotlib>=3.6.1 - numba - numexpr - - openpyxl + - openpyxl<3.1.1 - odfpy - pandas-gbq - psycopg2 diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index ed8dc6f760254..d68ddbb1fdcf4 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -36,7 +36,7 @@ dependencies: - matplotlib>=3.6.1 - numba - numexpr - - openpyxl + - openpyxl<3.1.1 - odfpy - pandas-gbq - psycopg2 diff --git a/ci/deps/circle-38-arm64.yaml b/ci/deps/circle-38-arm64.yaml index 4d406460eab70..3cd1cec079f99 100644 --- a/ci/deps/circle-38-arm64.yaml +++ b/ci/deps/circle-38-arm64.yaml @@ -36,7 +36,7 @@ dependencies: - matplotlib>=3.6.1 - numba - numexpr - - openpyxl + - openpyxl<3.1.1 - odfpy - pandas-gbq - psycopg2 diff --git a/environment.yml b/environment.yml index aad0c1ca8588f..da184249932c0 100644 --- a/environment.yml +++ b/environment.yml @@ -39,7 +39,7 @@ dependencies: - matplotlib>=3.6.1 - numba>=0.53.1 - numexpr>=2.8.0 # pin for "Run checks on imported code" job - - openpyxl + - openpyxl<3.1.1 - odfpy - py - psycopg2 diff --git a/requirements-dev.txt b/requirements-dev.txt index a06cff7cd2ccd..e9c652d6f6f0f 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -28,7 +28,7 @@ lxml matplotlib>=3.6.1 numba>=0.53.1 numexpr>=2.8.0 -openpyxl +openpyxl<3.1.1 odfpy py psycopg2-binary
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51391
2023-02-14T21:47:52Z
2023-02-15T11:00:40Z
2023-02-15T11:00:40Z
2023-02-15T20:08:52Z
PERF: Fix performance regression due to CoW ref tracking
diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index b5ff69d92492f..fe2a33918cfce 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -874,10 +874,10 @@ cdef class BlockValuesRefs: data. """ cdef: - public object referenced_blocks + public list referenced_blocks def __cinit__(self, blk: SharedBlock) -> None: - self.referenced_blocks = weakref.WeakSet([blk]) + self.referenced_blocks = [weakref.ref(blk)] def add_reference(self, blk: SharedBlock) -> None: """Adds a new reference to our reference collection. @@ -887,7 +887,7 @@ cdef class BlockValuesRefs: blk: SharedBlock The block that the new references should point to. """ - self.referenced_blocks.add(blk) + self.referenced_blocks.append(weakref.ref(blk)) def has_reference(self) -> bool: """Checks if block has foreign references. @@ -899,5 +899,8 @@ cdef class BlockValuesRefs: ------- bool """ + self.referenced_blocks = [ + ref for ref in self.referenced_blocks if ref() is not None + ] # Checking for more references than block pointing to itself return len(self.referenced_blocks) > 1
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. ``` before after ratio [74d5c195] [ef1734f1] - 3.53±0.6ms 2.36±0.06ms 0.67 frame_ctor.FromArrays.time_frame_from_arrays_sparse - 3.22±2ms 2.03±0.01ms 0.63 frame_ctor.FromArrays.time_frame_from_arrays_int ``` WeakSet caused a slowdown in these two benchmarks. Switching to a list for now, we will try to opimize this
https://api.github.com/repos/pandas-dev/pandas/pulls/51390
2023-02-14T21:41:16Z
2023-02-15T21:24:15Z
2023-02-15T21:24:14Z
2023-09-05T07:09:45Z
DOC: Set value for undefined variables in examples
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index da049218d5187..4790d00a071cb 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -1323,17 +1323,23 @@ def relabel_result( columns: New columns name for relabelling order: New order for relabelling - Examples: - --------- - >>> result = DataFrame({"A": [np.nan, 2, np.nan], - ... "C": [6, np.nan, np.nan], "B": [np.nan, 4, 2.5]}) # doctest: +SKIP + Examples + -------- + >>> from pandas.core.apply import relabel_result + >>> result = pd.DataFrame( + ... {"A": [np.nan, 2, np.nan], "C": [6, np.nan, np.nan], "B": [np.nan, 4, 2.5]}, + ... index=["max", "mean", "min"] + ... ) >>> funcs = {"A": ["max"], "C": ["max"], "B": ["mean", "min"]} >>> columns = ("foo", "aab", "bar", "dat") >>> order = [0, 1, 2, 3] - >>> _relabel_result(result, func, columns, order) # doctest: +SKIP - dict(A=Series([2.0, NaN, NaN, NaN], index=["foo", "aab", "bar", "dat"]), - C=Series([NaN, 6.0, NaN, NaN], index=["foo", "aab", "bar", "dat"]), - B=Series([NaN, NaN, 2.5, 4.0], index=["foo", "aab", "bar", "dat"])) + >>> result_in_dict = relabel_result(result, funcs, columns, order) + >>> pd.DataFrame(result_in_dict, index=columns) + A C B + foo 2.0 NaN NaN + aab NaN 6.0 NaN + bar NaN NaN 4.0 + dat NaN NaN 2.5 """ from pandas.core.indexes.base import Index diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index b8fca76115446..1e9b5641aa5e0 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -258,8 +258,9 @@ def _unbox_scalar( Examples -------- - >>> self._unbox_scalar(Timedelta("10s")) # doctest: +SKIP - 10000000000 + >>> arr = pd.arrays.DatetimeArray(np.array(['1970-01-01'], 'datetime64[ns]')) + >>> arr._unbox_scalar(arr[0]) + numpy.datetime64('1970-01-01T00:00:00.000000000') """ raise AbstractMethodError(self) diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index bce2a82f057f3..65a47452b1fe8 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -261,6 +261,7 @@ def construct_from_string( For extension dtypes with arguments the following may be an adequate implementation. + >>> import re >>> @classmethod ... def construct_from_string(cls, string): ... pattern = re.compile(r"^my_type\[(?P<arg_name>.+)\]$") diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 98dc3a6b45c7b..821e41db6b065 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2204,7 +2204,7 @@ def to_excel( >>> with pd.ExcelWriter('output.xlsx', ... mode='a') as writer: # doctest: +SKIP - ... df.to_excel(writer, sheet_name='Sheet_name_3') + ... df1.to_excel(writer, sheet_name='Sheet_name_3') To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is @@ -5864,9 +5864,9 @@ def pipe( Alternatively a ``(callable, data_keyword)`` tuple where ``data_keyword`` is a string indicating the keyword of ``callable`` that expects the {klass}. - args : iterable, optional + *args : iterable, optional Positional arguments passed into ``func``. - kwargs : mapping, optional + **kwargs : mapping, optional A dictionary of keyword arguments passed into ``func``. Returns @@ -5883,25 +5883,70 @@ def pipe( Notes ----- Use ``.pipe`` when chaining together functions that expect - Series, DataFrames or GroupBy objects. Instead of writing + Series, DataFrames or GroupBy objects. - >>> func(g(h(df), arg1=a), arg2=b, arg3=c) # doctest: +SKIP + Examples + -------- + Constructing a income DataFrame from a dictionary. + + >>> data = [[8000, 1000], [9500, np.nan], [5000, 2000]] + >>> df = pd.DataFrame(data, columns=['Salary', 'Others']) + >>> df + Salary Others + 0 8000 1000.0 + 1 9500 NaN + 2 5000 2000.0 + + Functions that perform tax reductions on an income DataFrame. + + >>> def subtract_federal_tax(df): + ... return df * 0.9 + >>> def subtract_state_tax(df, rate): + ... return df * (1 - rate) + >>> def subtract_national_insurance(df, rate, rate_increase): + ... new_rate = rate + rate_increase + ... return df * (1 - new_rate) + + Instead of writing + + >>> subtract_national_insurance( + ... subtract_state_tax(subtract_federal_tax(df), rate=0.12), + ... rate=0.05, + ... rate_increase=0.02) # doctest: +SKIP You can write - >>> (df.pipe(h) - ... .pipe(g, arg1=a) - ... .pipe(func, arg2=b, arg3=c) - ... ) # doctest: +SKIP + >>> ( + ... df.pipe(subtract_federal_tax) + ... .pipe(subtract_state_tax, rate=0.12) + ... .pipe(subtract_national_insurance, rate=0.05, rate_increase=0.02) + ... ) + Salary Others + 0 5892.48 736.56 + 1 6997.32 NaN + 2 3682.80 1473.12 If you have a function that takes the data as (say) the second argument, pass a tuple indicating which keyword expects the - data. For example, suppose ``func`` takes its data as ``arg2``: - - >>> (df.pipe(h) - ... .pipe(g, arg1=a) - ... .pipe((func, 'arg2'), arg1=a, arg3=c) - ... ) # doctest: +SKIP + data. For example, suppose ``national_insurance`` takes its data as ``df`` + in the second argument: + + >>> def subtract_national_insurance(rate, df, rate_increase): + ... new_rate = rate + rate_increase + ... return df * (1 - new_rate) + >>> ( + ... df.pipe(subtract_federal_tax) + ... .pipe(subtract_state_tax, rate=0.12) + ... .pipe( + ... (subtract_national_insurance, 'df'), + ... rate=0.05, + ... rate_increase=0.02 + ... ) + ... ) + Salary Others + 0 5892.48 736.56 + 1 6997.32 NaN + 2 3682.80 1473.12 """ if using_copy_on_write(): return common.pipe(self.copy(deep=None), func, *args, **kwargs) diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 3482e29fb1a70..c5262b9f52fc7 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -1272,7 +1272,7 @@ def format_index( >>> df = pd.DataFrame([[1, 2, 3]], ... columns=pd.MultiIndex.from_arrays([["a", "a", "b"],[2, np.nan, 4]])) - >>> df.style.format_index({0: lambda v: upper(v)}, axis=1, precision=1) + >>> df.style.format_index({0: lambda v: v.upper()}, axis=1, precision=1) ... # doctest: +SKIP A B 2.0 nan 4.0
- [x] closes #51342 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51389
2023-02-14T18:25:10Z
2023-02-28T13:33:40Z
2023-02-28T13:33:40Z
2023-02-28T13:33:40Z
DOC: add instructions for updating environment
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index c0e8aa6ba903e..d779e31253e09 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -331,6 +331,26 @@ To automatically fix formatting errors on each commit you make, you can set up pre-commit yourself. First, create a Python :ref:`environment <contributing_environment>` and then set up :ref:`pre-commit <contributing.pre-commit>`. +.. _contributing.update-dev: + +Updating the development environment +------------------------------------ + +After updating your branch to merge in main from upstream, you may need to update +your development environment to reflect any changes to the various packages that +are used during development. + +If using :ref:`mamba <contributing.mamba>`, do:: + + mamba deactivate + mamba env update -f environment.yml + mamba activate pandas-dev + +If using :ref:`pip <contributing.pip>` , do:: + + # activate the virtual environment based on your platform + pythom -m pip install --upgrade -r requirements-dev.txt + Tips for a successful pull request ================================== diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 63554447f295e..2fcc18007a1b7 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -89,6 +89,12 @@ without needing to have done ``pre-commit install`` beforehand. you may run into issues if you're using conda. To solve this, you can downgrade ``virtualenv`` to version ``20.0.33``. +.. note:: + + If you have recently merged in main from the upstream branch, some of the + dependencies used by ``pre-commit`` may have changed. Make sure to + :ref:`update your development environment <contributing.update-dev>`. + Optional dependencies --------------------- diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst index f934671f1e0b4..a648b18a554ee 100644 --- a/doc/source/development/contributing_environment.rst +++ b/doc/source/development/contributing_environment.rst @@ -95,6 +95,8 @@ Option 1: using mamba (recommended) mamba env create --file environment.yml mamba activate pandas-dev +.. _contributing.pip: + Option 2: using pip ~~~~~~~~~~~~~~~~~~~
I have found that when I merge in `upstream/main`, the devtools and pre-commit hooks often change, and then I need to update the environment. So I've documented that here. Not 100% sure that the instructions using `pip` are correct, so suggestions are welcome.
https://api.github.com/repos/pandas-dev/pandas/pulls/51388
2023-02-14T17:41:29Z
2023-02-16T16:44:32Z
2023-02-16T16:44:32Z
2023-02-16T16:44:40Z
DOC: Fix EX01 issues in docstrings
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 567ae6da92ae2..ae452a8c07ac8 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -86,14 +86,11 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then MSG='Partially validate docstrings (EX01)' ; echo $MSG $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01 --ignore_functions \ pandas.Series.index \ - pandas.Series.dtype \ pandas.Series.nbytes \ pandas.Series.ndim \ pandas.Series.size \ pandas.Series.T \ pandas.Series.hasnans \ - pandas.Series.dtypes \ - pandas.Series.to_period \ pandas.Series.to_timestamp \ pandas.Series.to_list \ pandas.Series.__iter__ \ diff --git a/pandas/core/series.py b/pandas/core/series.py index 7af68a118889e..e4c7c4d3b3d73 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -580,6 +580,12 @@ def _can_hold_na(self) -> bool: def dtype(self) -> DtypeObj: """ Return the dtype object of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.dtype + dtype('int64') """ return self._mgr.dtype @@ -587,6 +593,12 @@ def dtype(self) -> DtypeObj: def dtypes(self) -> DtypeObj: """ Return the dtype object of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.dtypes + dtype('int64') """ # DataFrame compatibility return self.dtype @@ -5722,6 +5734,22 @@ def to_period(self, freq: str | None = None, copy: bool | None = None) -> Series ------- Series Series with index converted to PeriodIndex. + + Examples + -------- + >>> idx = pd.DatetimeIndex(['2023', '2024', '2025']) + >>> s = pd.Series([1, 2, 3], index=idx) + >>> s = s.to_period() + >>> s + 2023 1 + 2024 2 + 2025 3 + Freq: A-DEC, dtype: int64 + + Viewing the index + + >>> s.index + PeriodIndex(['2023', '2024', '2025'], dtype='period[A-DEC]') """ if not isinstance(self.index, DatetimeIndex): raise TypeError(f"unsupported Type {type(self.index).__name__}")
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Towards #37875
https://api.github.com/repos/pandas-dev/pandas/pulls/51387
2023-02-14T17:39:05Z
2023-02-15T16:51:11Z
2023-02-15T16:51:11Z
2023-02-16T08:06:57Z
TEST: cut() with nullable Int64 dtype
diff --git a/pandas/tests/reshape/test_cut.py b/pandas/tests/reshape/test_cut.py index 3b9ab6a83a575..e47e36ab55f10 100644 --- a/pandas/tests/reshape/test_cut.py +++ b/pandas/tests/reshape/test_cut.py @@ -744,3 +744,18 @@ def test_cut_bins_datetime_intervalindex(): result = cut(Series([Timestamp("2022-02-26")]), bins=bins) expected = Categorical.from_codes([0], bins, ordered=True) tm.assert_categorical_equal(result.array, expected) + + +def test_cut_with_nullable_int64(): + # GH 30787 + series = Series([0, 1, 2, 3, 4, pd.NA, 6, 7], dtype="Int64") + bins = [0, 2, 4, 6, 8] + intervals = IntervalIndex.from_breaks(bins) + + expected = Series( + Categorical.from_codes([-1, 0, 0, 1, 1, -1, 2, 3], intervals, ordered=True) + ) + + result = cut(series, bins=bins) + + tm.assert_series_equal(result, expected)
- [x] closes #30787 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51384
2023-02-14T16:58:29Z
2023-02-16T14:18:54Z
2023-02-16T14:18:54Z
2023-02-16T14:18:59Z
DOC: clarify pitfalls of NA vs NaN in nullable floats
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5d2a0fe66cc1d..4c962da3c8d1e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7873,6 +7873,12 @@ def isna(self: NDFrameT) -> NDFrameT: strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). + Note: For nullable float extension dtypes, i.e. + ``Float<...>`` and ``float<...>[pyarrow]``, the behavior is different - + missing data is designated by ``pandas.NA`` values while NaN may also be + stored but will **not** get mapped to True (these values can be detected + by :func:`numpy.isnan`). + Returns ------- {klass}
- [x] stopgap solution addressing #49818 and such until the discussion in #32265 is resolved - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Following up on my [comment](https://github.com/pandas-dev/pandas/issues/32265#issuecomment-1405543022): since the current behavior easily leads to mistakes when trying to detect missing/NaN data and does not match the docs' described semantics, this PR is trying to update the docs to clarify this edge case so users can avoid the pitfalls. Notes/questions on PR work: * There may be other places to update, but I figure once the language is approved it's easy to add it elsewhere * Should we link to the issue #32265 discussing what the behavior should be? That would enable users to weigh in with their preferences but might be too detailed/confusing. * Should the docstring describe this scenario in terms of Arrays or the corresponding dtypes? Thanks!
https://api.github.com/repos/pandas-dev/pandas/pulls/51383
2023-02-14T16:16:53Z
2023-08-01T17:10:51Z
null
2023-08-01T17:10:52Z
CI fixup pylint
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index b3d2a366bf58a..15c278bdc3859 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -801,7 +801,7 @@ def test_pivot_columns_none_raise_error(self): df = DataFrame({"col1": ["a", "b", "c"], "col2": [1, 2, 3], "col3": [1, 2, 3]}) msg = r"pivot\(\) missing 1 required keyword-only argument: 'columns'" with pytest.raises(TypeError, match=msg): - df.pivot(index="col1", values="col3") + df.pivot(index="col1", values="col3") # pylint: disable=missing-kwoa @pytest.mark.xfail( reason="MultiIndexed unstack with tuple names fails with KeyError GH#19966" @@ -2514,7 +2514,7 @@ def test_pivot_columns_not_given(self): # GH#48293 df = DataFrame({"a": [1], "b": 1}) with pytest.raises(TypeError, match="missing 1 required keyword-only argument"): - df.pivot() + df.pivot() # pylint: disable=missing-kwoa def test_pivot_columns_is_none(self): # GH#48293
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. I missed this one in https://github.com/pandas-dev/pandas/pull/51367
https://api.github.com/repos/pandas-dev/pandas/pulls/51381
2023-02-14T15:40:30Z
2023-02-14T16:34:10Z
2023-02-14T16:34:10Z
2023-02-14T16:34:11Z
WARN unnecessary "can't infer datetime format" for out-of-bounds datetimes
diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 445683968c58f..69009fe2a30b1 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -73,7 +73,7 @@ from pandas._libs.tslibs.np_datetime cimport ( string_to_dts, ) -from pandas._libs.tslibs.strptime import array_strptime +from pandas._libs.tslibs.strptime import TimeRE from pandas._libs.tslibs.util cimport ( get_c_string_buf_and_size, @@ -992,9 +992,7 @@ def guess_datetime_format(dt_str: str, bint dayfirst=False) -> str | None: guessed_format = "".join(output_format) - try: - array_strptime(np.asarray([dt_str], dtype=object), guessed_format) - except ValueError: + if TimeRE().compile(guessed_format).match(dt_str) is None: # Doesn't parse, so this can't be the correct format. return None # rebuild string, capturing any inferred padding diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 71f2cae49fe41..b21698590433d 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1372,12 +1372,10 @@ def test_datetime_invalid_scalar(self, value, format, warning): ) def test_datetime_outofbounds_scalar(self, value, format, warning): # GH24763 - with tm.assert_produces_warning(warning, match="Could not infer format"): - res = to_datetime(value, errors="ignore", format=format) + res = to_datetime(value, errors="ignore", format=format) assert res == value - with tm.assert_produces_warning(warning, match="Could not infer format"): - res = to_datetime(value, errors="coerce", format=format) + res = to_datetime(value, errors="coerce", format=format) assert res is NaT if format is not None: @@ -1385,10 +1383,8 @@ def test_datetime_outofbounds_scalar(self, value, format, warning): with pytest.raises(ValueError, match=msg): to_datetime(value, errors="raise", format=format) else: - msg = "^Out of bounds .*, at position 0$" - with pytest.raises( - OutOfBoundsDatetime, match=msg - ), tm.assert_produces_warning(warning, match="Could not infer format"): + msg = f"^Out of bounds .*, at position 0. {PARSING_ERR_MSG}" + with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(value, errors="raise", format=format) @pytest.mark.parametrize("values", [["a"], ["00:01:99"], ["a", "b", "99:00:00"]]) @@ -2217,10 +2213,7 @@ def test_to_datetime_barely_out_of_bounds(self): msg = "^Out of bounds nanosecond timestamp: .*, at position 0" with pytest.raises(OutOfBoundsDatetime, match=msg): - with tm.assert_produces_warning( - UserWarning, match="Could not infer format" - ): - to_datetime(arr) + to_datetime(arr) @pytest.mark.parametrize( "arg, exp_str", @@ -3335,8 +3328,7 @@ def test_to_datetime_out_of_bounds_with_format_arg(self, format, warning): # see gh-23830 msg = r"^Out of bounds nanosecond timestamp: 2417-10-10 00:00:00, at position 0" with pytest.raises(OutOfBoundsDatetime, match=msg): - with tm.assert_produces_warning(warning, match="Could not infer format"): - to_datetime("2417-10-10 00:00:00", format=format) + to_datetime("2417-10-10 00:00:00", format=format) @pytest.mark.parametrize( "arg, origin, expected_str",
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51380
2023-02-14T15:36:38Z
2023-02-15T16:45:43Z
null
2023-02-15T16:45:44Z
WIP: dtype._is_valid_na_for_dtype
diff --git a/pandas/core/arrays/arrow/dtype.py b/pandas/core/arrays/arrow/dtype.py index 90c86cd6d55ef..437cd975b6bb2 100644 --- a/pandas/core/arrays/arrow/dtype.py +++ b/pandas/core/arrays/arrow/dtype.py @@ -4,6 +4,7 @@ import numpy as np +from pandas._libs import missing as libmissing from pandas._typing import ( TYPE_CHECKING, DtypeObj, @@ -209,6 +210,9 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: except NotImplementedError: return None + def _is_valid_na_for_dtype(self, value) -> bool: + return value is None or value is libmissing.NA + def __from_arrow__(self, array: pa.Array | pa.ChunkedArray): """ Construct IntegerArray/FloatingArray from pyarrow Array/ChunkedArray. diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index c261a41e1e77e..6d0ff112ad235 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -425,7 +425,7 @@ def __contains__(self, item: object) -> bool | np.bool_: if is_scalar(item) and isna(item): if not self._can_hold_na: return False - elif item is self.dtype.na_value or isinstance(item, self.dtype.type): + elif self.dtype._is_valid_na_for_dtype(item): return self._hasna else: return False diff --git a/pandas/core/dtypes/base.py b/pandas/core/dtypes/base.py index bce2a82f057f3..b8f117b8ef547 100644 --- a/pandas/core/dtypes/base.py +++ b/pandas/core/dtypes/base.py @@ -61,9 +61,11 @@ class ExtensionDtype: * _is_numeric * _is_boolean * _get_common_dtype + * _is_valid_na_for_dtype The `na_value` class attribute can be used to set the default NA value - for this type. :attr:`numpy.nan` is used by default. + for this type. :attr:`numpy.nan` is used by default. What other NA values + are accepted can be fine-tuned by overriding ``_is_valid_na_for_dtype``. ExtensionDtypes are required to be hashable. The base class provides a default implementation, which relies on the ``_metadata`` class @@ -390,6 +392,26 @@ def _can_hold_na(self) -> bool: """ return True + def _is_valid_na_for_dtype(self, value) -> bool: + """ + Should we treat this value as interchangeable with self.na_value? + + Use cases include: + + - series[key] = value + - series.replace(other, value) + - value in index + + If ``value`` is a valid na for this dtype, ``self.na_value`` will be used + in its place for the purpose of this operations. + + Notes + ----- + The base class implementation considers any scalar recognized by pd.isna + to be equivalent. + """ + return libmissing.checknull(value) + class StorageExtensionDtype(ExtensionDtype): """ExtensionDtype that may be backed by more than one implementation.""" diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 33ff6d1eee686..1d3221f23fd4a 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -3,6 +3,7 @@ """ from __future__ import annotations +from decimal import Decimal import re from typing import ( TYPE_CHECKING, @@ -14,7 +15,10 @@ import numpy as np import pytz -from pandas._libs import missing as libmissing +from pandas._libs import ( + lib, + missing as libmissing, +) from pandas._libs.interval import Interval from pandas._libs.properties import cache_readonly from pandas._libs.tslibs import ( @@ -629,6 +633,11 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: return find_common_type(non_cat_dtypes) + def _is_valid_na_for_dtype(self, value) -> bool: + from pandas.core.dtypes.missing import is_valid_na_for_dtype + + return is_valid_na_for_dtype(value, self.categories.dtype) + @register_extension_dtype class DatetimeTZDtype(PandasExtensionDtype): @@ -819,6 +828,10 @@ def __setstate__(self, state) -> None: self._tz = state["tz"] self._unit = state["unit"] + def _is_valid_na_for_dtype(self, value) -> bool: + # we have to rule out tznaive dt64("NaT") + return not isinstance(value, (np.timedelta64, np.datetime64, Decimal)) + @register_extension_dtype class PeriodDtype(PeriodDtypeBase, PandasExtensionDtype): @@ -1036,6 +1049,9 @@ def __from_arrow__( return PeriodArray(np.array([], dtype="int64"), freq=self.freq, copy=False) return PeriodArray._concat_same_type(results) + def _is_valid_na_for_dtype(self, value) -> bool: + return not isinstance(value, (np.datetime64, np.timedelta64, Decimal)) + @register_extension_dtype class IntervalDtype(PandasExtensionDtype): @@ -1304,6 +1320,9 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: return np.dtype(object) return IntervalDtype(common, closed=closed) + def _is_valid_na_for_dtype(self, value) -> bool: + return lib.is_float(value) or value is None or value is libmissing.NA + class PandasDtype(ExtensionDtype): """ @@ -1479,3 +1498,6 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: return type(self).from_numpy_dtype(new_dtype) except (KeyError, NotImplementedError): return None + + def _is_valid_na_for_dtype(self, value) -> bool: + return value is None or value is libmissing.NA diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 211b67d3590ed..f111bd97a00de 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -38,10 +38,8 @@ needs_i8_conversion, ) from pandas.core.dtypes.dtypes import ( - CategoricalDtype, DatetimeTZDtype, ExtensionDtype, - IntervalDtype, PeriodDtype, ) from pandas.core.dtypes.generic import ( @@ -692,40 +690,33 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool: """ if not lib.is_scalar(obj) or not isna(obj): return False - elif dtype.kind == "M": - if isinstance(dtype, np.dtype): + + elif isinstance(dtype, np.dtype): + if dtype.kind == "M": # i.e. not tzaware return not isinstance(obj, (np.timedelta64, Decimal)) - # we have to rule out tznaive dt64("NaT") - return not isinstance(obj, (np.timedelta64, np.datetime64, Decimal)) - elif dtype.kind == "m": - return not isinstance(obj, (np.datetime64, Decimal)) - elif dtype.kind in ["i", "u", "f", "c"]: - # Numeric - return obj is not NaT and not isinstance(obj, (np.datetime64, np.timedelta64)) - elif dtype.kind == "b": - # We allow pd.NA, None, np.nan in BooleanArray (same as IntervalDtype) - return lib.is_float(obj) or obj is None or obj is libmissing.NA - - elif dtype == _dtype_str: - # numpy string dtypes to avoid float np.nan - return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal, float)) - - elif dtype == _dtype_object: - # This is needed for Categorical, but is kind of weird - return True - - elif isinstance(dtype, PeriodDtype): - return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal)) - - elif isinstance(dtype, IntervalDtype): - return lib.is_float(obj) or obj is None or obj is libmissing.NA + elif dtype.kind == "m": + return not isinstance(obj, (np.datetime64, Decimal)) + elif dtype.kind in ["i", "u", "f", "c"]: + # Numeric + return obj is not NaT and not isinstance( + obj, (np.datetime64, np.timedelta64) + ) + elif dtype == _dtype_str: + # numpy string dtypes to avoid float np.nan + return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal, float)) + elif dtype == _dtype_object: + # This is needed for Categorical, but is kind of weird + return True + elif dtype.kind == "b": + # We allow pd.NA, None, np.nan in BooleanArray (same as IntervalDtype) + return lib.is_float(obj) or obj is None or obj is libmissing.NA - elif isinstance(dtype, CategoricalDtype): - return is_valid_na_for_dtype(obj, dtype.categories.dtype) + # fallback, default to allowing NaN, None, NA, NaT + return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal)) - # fallback, default to allowing NaN, None, NA, NaT - return not isinstance(obj, (np.datetime64, np.timedelta64, Decimal)) + else: + return dtype._is_valid_na_for_dtype(obj) def isna_all(arr: ArrayLike) -> bool: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index cb321f0584294..7807f0a170bd1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -35,7 +35,10 @@ using_copy_on_write, ) -from pandas._libs import lib +from pandas._libs import ( + lib, + missing as libmissing, +) from pandas._libs.lib import is_range_indexer from pandas._libs.tslibs import ( Period, @@ -8012,7 +8015,7 @@ def _clip_with_scalar(self, lower, upper, inplace: bool_t = False): result = result.where(subset, lower, axis=None, inplace=False) if np.any(mask): - result[mask] = np.nan + result[mask] = libmissing.NA if inplace: return self._update_inplace(result) diff --git a/pandas/tests/extension/test_integer.py b/pandas/tests/extension/test_integer.py index 936764c3627d0..65543cd6bbf1c 100644 --- a/pandas/tests/extension/test_integer.py +++ b/pandas/tests/extension/test_integer.py @@ -135,7 +135,7 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError): expected = self._combine(s, other, op) if op_name in ("__rtruediv__", "__truediv__", "__div__"): - expected = expected.fillna(np.nan).astype("Float64") + expected = expected.fillna(pd.NA).astype("Float64") else: # combine method result in 'biggest' (int64) dtype expected = expected.astype(sdtype) diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py index d91cd6a43daea..2d12ccab6f95c 100644 --- a/pandas/tests/series/methods/test_convert_dtypes.py +++ b/pandas/tests/series/methods/test_convert_dtypes.py @@ -193,7 +193,7 @@ def test_convert_dtypes( # Test that it is a copy copy = series.copy(deep=True) - result[result.notna()] = np.nan + result[result.notna()] = None # Make sure original not changed tm.assert_series_equal(series, copy)
Some dtypes (pyarrow/nullable mostly) need to treat NaN (and maybe None) differently from pd.NA. Motivating bug (which this PR does not address): ``` arr = pd.array(range(5)) / 0 >>> np.nan in arr # <- wrong False ``` What this does fix is `arr[2] = np.nan` now sets NaN instead of pd.NA. Setting np.nan into an IntegerArray/BooleanArray raises. (None still casts to pd.NA). This breaks a bunch of tests. I'd like feedback before I go track those down. cc @jorisvandenbossche Tangentially related #27825
https://api.github.com/repos/pandas-dev/pandas/pulls/51378
2023-02-14T15:26:39Z
2023-04-21T22:15:55Z
null
2023-04-21T22:16:26Z
BUG: GroupBy.quantile with datetimelike and NaT
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index d1b965e64e43b..bd6e2608f97ae 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1186,6 +1186,8 @@ Datetimelike - Bug in :func:`DataFrame.from_records` when given a :class:`DataFrame` input with timezone-aware datetime64 columns incorrectly dropping the timezone-awareness (:issue:`51162`) - Bug in :func:`to_datetime` was raising ``decimal.InvalidOperation`` when parsing date strings with ``errors='coerce'`` (:issue:`51084`) - Bug in :func:`to_datetime` with both ``unit`` and ``origin`` specified returning incorrect results (:issue:`42624`) +- Bug in :meth:`GroupBy.quantile` with datetime or timedelta dtypes giving incorrect results for groups containing ``NaT`` (:issue:`51373`) +- Bug in :meth:`Groupby.quantile` incorrectly raising with :class:`PeriodDtype` or :class:`DatetimeTZDtype` (:issue:`51373`) - Timedelta diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 763494666d870..b25c767db42ff 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -73,7 +73,6 @@ class providing the base-class of operations. from pandas.core.dtypes.cast import ensure_dtype_can_hold_na from pandas.core.dtypes.common import ( is_bool_dtype, - is_datetime64_dtype, is_float_dtype, is_hashable, is_integer, @@ -81,7 +80,7 @@ class providing the base-class of operations. is_numeric_dtype, is_object_dtype, is_scalar, - is_timedelta64_dtype, + needs_i8_conversion, ) from pandas.core.dtypes.missing import ( isna, @@ -3192,12 +3191,15 @@ def pre_processor(vals: ArrayLike) -> tuple[np.ndarray, DtypeObj | None]: inference = np.dtype(np.int64) elif is_bool_dtype(vals.dtype) and isinstance(vals, ExtensionArray): out = vals.to_numpy(dtype=float, na_value=np.nan) - elif is_datetime64_dtype(vals.dtype): + elif needs_i8_conversion(vals.dtype): inference = vals.dtype - out = np.asarray(vals).astype(float) - elif is_timedelta64_dtype(vals.dtype): - inference = vals.dtype - out = np.asarray(vals).astype(float) + # In this case we need to delay the casting until after the + # np.lexsort below. + # error: Incompatible return value type (got + # "Tuple[Union[ExtensionArray, ndarray[Any, Any]], Union[Any, + # ExtensionDtype]]", expected "Tuple[ndarray[Any, Any], + # Optional[Union[dtype[Any], ExtensionDtype]]]") + return vals, inference # type: ignore[return-value] elif isinstance(vals, ExtensionArray) and is_float_dtype(vals): inference = np.dtype(np.float64) out = vals.to_numpy(dtype=float, na_value=np.nan) @@ -3236,6 +3238,18 @@ def post_processor( is_integer_dtype(inference) and interpolation in {"linear", "midpoint"} ): + if needs_i8_conversion(inference): + # error: Item "ExtensionArray" of "Union[ExtensionArray, + # ndarray[Any, Any]]" has no attribute "_ndarray" + vals = vals.astype("i8").view( + orig_vals._ndarray.dtype # type: ignore[union-attr] + ) + # error: Item "ExtensionArray" of "Union[ExtensionArray, + # ndarray[Any, Any]]" has no attribute "_from_backing_data" + return orig_vals._from_backing_data( # type: ignore[union-attr] + vals + ) + assert isinstance(inference, np.dtype) # for mypy return vals.astype(inference) @@ -3272,6 +3286,8 @@ def blk_func(values: ArrayLike) -> ArrayLike: mask = isna(values) result_mask = None + is_datetimelike = needs_i8_conversion(values.dtype) + vals, inference = pre_processor(values) ncols = 1 @@ -3289,6 +3305,11 @@ def blk_func(values: ArrayLike) -> ArrayLike: order = (vals, shaped_labels) sort_arr = np.lexsort(order).astype(np.intp, copy=False) + if is_datetimelike: + # This casting needs to happen after the lexsort in order + # to ensure that NaTs are placed at the end and not the front + vals = vals.view("i8").astype(np.float64) + if vals.ndim == 1: # Ea is always 1d func( diff --git a/pandas/tests/groupby/test_quantile.py b/pandas/tests/groupby/test_quantile.py index 8cba3a8afdfae..79354e550d3f6 100644 --- a/pandas/tests/groupby/test_quantile.py +++ b/pandas/tests/groupby/test_quantile.py @@ -445,3 +445,26 @@ def test_timestamp_groupby_quantile(): ) tm.assert_frame_equal(result, expected) + + +def test_groupby_quantile_dt64tz_period(): + # GH#51373 + dti = pd.date_range("2016-01-01", periods=1000) + ser = pd.Series(dti) + df = ser.to_frame() + df[1] = dti.tz_localize("US/Pacific") + df[2] = dti.to_period("D") + df[3] = dti - dti[0] + df.iloc[-1] = pd.NaT + + by = np.tile(np.arange(5), 200) + gb = df.groupby(by) + + result = gb.quantile(0.5) + + # Check that we match the group-by-group result + exp = {i: df.iloc[i::5].quantile(0.5) for i in range(5)} + expected = DataFrame(exp).T + expected.index = expected.index.astype(np.int_) + + tm.assert_frame_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51373
2023-02-14T03:04:32Z
2023-02-14T18:53:13Z
2023-02-14T18:53:13Z
2023-02-14T22:35:04Z
DOC: Add PyArrow user guide
diff --git a/doc/source/reference/arrays.rst b/doc/source/reference/arrays.rst index 457edb46a7ec0..edcd3d2a40b1a 100644 --- a/doc/source/reference/arrays.rst +++ b/doc/source/reference/arrays.rst @@ -113,6 +113,8 @@ values. ArrowDtype +For more information, please see the :ref:`PyArrow user guide <pyarrow>` + .. _api.arrays.datetime: Datetimes diff --git a/doc/source/user_guide/index.rst b/doc/source/user_guide/index.rst index a6392706eb7a3..e23396c9e5fd4 100644 --- a/doc/source/user_guide/index.rst +++ b/doc/source/user_guide/index.rst @@ -64,6 +64,7 @@ Guides dsintro basics io + pyarrow indexing advanced merging diff --git a/doc/source/user_guide/pyarrow.rst b/doc/source/user_guide/pyarrow.rst new file mode 100644 index 0000000000000..94b2c724cd229 --- /dev/null +++ b/doc/source/user_guide/pyarrow.rst @@ -0,0 +1,163 @@ +.. _pyarrow: + +{{ header }} + +********************* +PyArrow Functionality +********************* + +pandas can utilize `PyArrow <https://arrow.apache.org/docs/python/index.html>`__ to extend functionality and improve the performance +of various APIs. This includes: + +* More extensive `data types <https://arrow.apache.org/docs/python/api/datatypes.html>`__ compared to NumPy +* Missing data support (NA) for all data types +* Performant IO reader integration +* Facilitate interoperability with other dataframe libraries based on the Apache Arrow specification (e.g. polars, cuDF) + +To use this functionality, please ensure you have :ref:`installed the minimum supported PyArrow version. <install.optional_dependencies>` + + +Data Structure Integration +-------------------------- + +A :class:`Series`, :class:`Index`, or the columns of a :class:`DataFrame` can be directly backed by a :external+pyarrow:py:class:`pyarrow.ChunkedArray` +which is similar to a NumPy array. To construct these from the main pandas data structures, you can pass in a string of the type followed by +``[pyarrow]``, e.g. ``"int64[pyarrow]""`` into the ``dtype`` parameter + +.. ipython:: python + + ser = pd.Series([-1.5, 0.2, None], dtype="float32[pyarrow]") + ser + + idx = pd.Index([True, None], dtype="bool[pyarrow]") + idx + + df = pd.DataFrame([[1, 2], [3, 4]], dtype="uint64[pyarrow]") + df + +For PyArrow types that accept parameters, you can pass in a PyArrow type with those parameters +into :class:`ArrowDtype` to use in the ``dtype`` parameter. + +.. ipython:: python + + import pyarrow as pa + list_str_type = pa.list_(pa.string()) + ser = pd.Series([["hello"], ["there"]], dtype=pd.ArrowDtype(list_str_type)) + ser + + from datetime import time + idx = pd.Index([time(12, 30), None], dtype=pd.ArrowDtype(pa.time64("us"))) + idx + + from decimal import Decimal + decimal_type = pd.ArrowDtype(pa.decimal128(3, scale=2)) + data = [[Decimal("3.19"), None], [None, Decimal("-1.23")]] + df = pd.DataFrame(data, dtype=decimal_type) + df + +If you already have an :external+pyarrow:py:class:`pyarrow.Array` or :external+pyarrow:py:class:`pyarrow.ChunkedArray`, +you can pass it into :class:`.arrays.ArrowExtensionArray` to construct the associated :class:`Series`, :class:`Index` +or :class:`DataFrame` object. + +.. ipython:: python + + pa_array = pa.array([{"1": "2"}, {"10": "20"}, None]) + ser = pd.Series(pd.arrays.ArrowExtensionArray(pa_array)) + ser + +To retrieve a pyarrow :external+pyarrow:py:class:`pyarrow.ChunkedArray` from a :class:`Series` or :class:`Index`, you can call +the pyarrow array constructor on the :class:`Series` or :class:`Index`. + +.. ipython:: python + + ser = pd.Series([1, 2, None], dtype="uint8[pyarrow]") + pa.array(ser) + + idx = pd.Index(ser) + pa.array(idx) + +Operations +---------- + +PyArrow data structure integration is implemented through pandas' :class:`~pandas.api.extensions.ExtensionArray` :ref:`interface <extending.extension-types>`; +therefore, supported functionality exists where this interface is integrated within the pandas API. Additionally, this functionality +is accelerated with PyArrow `compute functions <https://arrow.apache.org/docs/python/api/compute.html>`__ where available. This includes: + +* Numeric aggregations +* Numeric arithmetic +* Numeric rounding +* Logical and comparison functions +* String functionality +* Datetime functionality + +The following are just some examples of operations that are accelerated by native PyArrow compute functions. + +.. ipython:: python + + ser = pd.Series([-1.545, 0.211, None], dtype="float32[pyarrow]") + ser.mean() + ser + ser + ser > (ser + 1) + + ser.dropna() + ser.isna() + ser.fillna(0) + + ser_str = pd.Series(["a", "b", None], dtype="string[pyarrow]") + ser_str.str.startswith("a") + + from datetime import datetime + pa_type = pd.ArrowDtype(pa.timestamp("ns")) + ser_dt = pd.Series([datetime(2022, 1, 1), None], dtype=pa_type) + ser_dt.dt.strftime("%Y-%m") + +I/O Reading +----------- + +PyArrow also provides IO reading functionality that has been integrated into several pandas IO readers. The following +functions provide an ``engine`` keyword that can dispatch to PyArrow to accelerate reading from an IO source. + +* :func:`read_csv` +* :func:`read_json` +* :func:`read_orc` +* :func:`read_feather` + +.. ipython:: python + + import io + data = io.StringIO("""a,b,c + 1,2.5,True + 3,4.5,False + """) + df = pd.read_csv(data, engine="pyarrow") + df + +By default, these functions and all other IO reader functions return NumPy-backed data. These readers can return +PyArrow-backed data by specifying the parameter ``use_nullable_dtypes=True`` **and** the global configuration option ``"mode.dtype_backend"`` +set to ``"pyarrow"``. A reader does not need to set ``engine="pyarrow"`` to necessarily return PyArrow-backed data. + +.. ipython:: python + + import io + data = io.StringIO("""a,b,c,d,e,f,g,h,i + 1,2.5,True,a,,,,, + 3,4.5,False,b,6,7.5,True,a, + """) + with pd.option_context("mode.dtype_backend", "pyarrow"): + df_pyarrow = pd.read_csv(data, use_nullable_dtypes=True) + df_pyarrow.dtypes + +To simplify specifying ``use_nullable_dtypes=True`` in several functions, you can set a global option ``nullable_dtypes`` +to ``True``. You will still need to set the global configuration option ``"mode.dtype_backend"`` to ``pyarrow``. + +.. code-block:: ipython + + In [1]: pd.set_option("mode.dtype_backend", "pyarrow") + + In [2]: pd.options.mode.nullable_dtypes = True + +Several non-IO reader functions can also use the ``"mode.dtype_backend"`` option to return PyArrow-backed data including: + +* :func:`to_numeric` +* :meth:`DataFrame.convert_dtypes` +* :meth:`Series.convert_dtypes`
null
https://api.github.com/repos/pandas-dev/pandas/pulls/51371
2023-02-14T00:22:21Z
2023-02-15T19:54:23Z
2023-02-15T19:54:23Z
2023-02-15T19:54:27Z
ENH: Add Index.filter() method
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index d1b965e64e43b..01aad7eae4d79 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -314,7 +314,7 @@ Other enhancements - Added new argument ``engine`` to :func:`read_json` to support parsing JSON with pyarrow by specifying ``engine="pyarrow"`` (:issue:`48893`) - Added support for SQLAlchemy 2.0 (:issue:`40686`) - :class:`Index` set operations :meth:`Index.union`, :meth:`Index.intersection`, :meth:`Index.difference`, and :meth:`Index.symmetric_difference` now support ``sort=True``, which will always return a sorted result, unlike the default ``sort=None`` which does not sort in some cases (:issue:`25151`) -- +- Added :meth:`Index.filter` that allows filtering on :class:`Index` to create a new :class:`Index` object .. --------------------------------------------------------------------------- .. _whatsnew_200.notable_bug_fixes: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d76648558bc6e..0938dcb97b7ff 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5473,6 +5473,8 @@ def filter( -------- DataFrame.loc : Access a group of rows and columns by label(s) or a boolean array. + Index.filter : Create a subset of the index according to the specified index + labels. Notes ----- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 8adb7cca45323..742c8952bd957 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4,6 +4,7 @@ import functools from itertools import zip_longest import operator +import re from typing import ( TYPE_CHECKING, Any, @@ -88,6 +89,7 @@ ensure_int64, ensure_object, ensure_platform_int, + ensure_str, is_any_real_numeric_dtype, is_bool_dtype, is_categorical_dtype, @@ -155,6 +157,7 @@ PandasObject, ) import pandas.core.common as com +from pandas.core.common import count_not_none from pandas.core.construction import ( ensure_wrapped_if_datetimelike, extract_array, @@ -6150,6 +6153,76 @@ def map(self, mapper, na_action=None): return Index._with_infer(new_values, dtype=dtype, copy=False, name=self.name) + def filter( + self: _IndexT, + items: Axes | None = None, + like: str_t | None = None, + regex: str_t | None = None, + ) -> _IndexT: + """ + Create a subset of the index according to the specified index labels. + + Parameters + ---------- + items : list-like + Keep labels from index which are in items. + like : str + Keep labels from index for which "like in label == True". + regex : str (regular expression) + Keep labels from index for which re.search(regex, label) == True. + + Returns + ------- + same type as input object + + See Also + -------- + DataFrame.filter : Subset the dataframe rows or columns according to the + specified index labels. + + Notes + ----- + The ``items``, ``like``, and ``regex`` parameters are + enforced to be mutually exclusive. + + Examples + -------- + >>> idx = pd.Index(["cat", "dog", "bat", "bird"]) + >>> idx + Index(['cat', 'dog', 'bat', 'bird'], dtype='object') + + >>> # select index values by name + >>> idx.filter(items=['cat', 'dog']) + Index(['cat', 'dog'], dtype='object') + + >>> # select index values by regular expression + >>> idx.filter(regex=r'b.*') + Index(['bat', 'bird'], dtype='object') + + >>> # select index values containing 'at' + >>> idx.filter(like='at') + Index(['cat', 'bat'], dtype='object') + """ + nkw = count_not_none(items, like, regex) + if nkw > 1: + raise TypeError( + "Keyword arguments `items`, `like`, or `regex` " + "are mutually exclusive" + ) + + if items is not None: + mask = [r in items for r in self] + elif like: + mask = [like in ensure_str(r) for r in self] + elif regex: + matcher = re.compile(regex) + mask = [matcher.search(ensure_str(r)) is not None for r in self] + else: + raise TypeError("Must pass either `items`, `like`, or `regex`") + boolmask = np.array(mask, dtype=np.bool_) + res_values = self._data[boolmask] + return type(self)._simple_new(res_values, name=self._name) + # TODO: De-duplicate with map, xref GH#32349 @final def _transform_index(self, func, *, level=None) -> Index: diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 783cf76403059..ae1f51efcf723 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1285,6 +1285,34 @@ def test_sortlevel(self): result = index.sortlevel(ascending=False) tm.assert_index_equal(result[0], expected) + @pytest.mark.parametrize( + "dtype", + ["object", pd.StringDtype()], + ) + def test_filter_string(self, dtype): + idx = Index(["cat", "dog", "bat", "bird"], dtype=dtype) + result = idx.filter(["cat", "dog"]) + expected = Index(["cat", "dog"], dtype=dtype) + tm.assert_index_equal(result, expected) + + result = idx.filter(like="at") + expected = Index(["cat", "bat"], dtype=dtype) + tm.assert_index_equal(result, expected) + + result = idx.filter(regex=r"b.*") + expected = Index(["bat", "bird"], dtype=dtype) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize( + "dtype", + ["int", pd.Int64Dtype()], + ) + def test_filter_int(self, dtype): + idx = Index([1, 2, 3, 4, 5], dtype=dtype) + result = idx.filter(range(2, 4)) + expected = Index([2, 3], dtype=dtype) + tm.assert_index_equal(result, expected) + class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - New feature - no issue - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - `pandas\pandas\tests\indexes\test_base.py:TestIndex.test_filter_string()` - `pandas\pandas\tests\indexes\test_base.py:TestIndex.test_filter_int()` - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. This is similar to `DataFrame.filter()`, except it returns an `Index` object, and avoids any under-the-hood things that might be happening with `DataFrame.filter()` in terms of views/copies of the `DataFrame`. Some examples where this would be useful (and helpful when doing type checking). - Instead of `df.columns = [x for x in otherdf.columns if "at" in x]`, you can do `df.columns = otherdf.columns.filter(like="at")` - Instead of `df.drop(columns=[x for x in df.columns if x.startswith("b")]`, you can do `df.drop(columns=df.columns.filter(regex=r"b.*")` - Instead of `df.set_index([x for x in df.columns if x.endswith("z")])`, you can do `df.set_index(df.columns.filter(r".*z$"))`
https://api.github.com/repos/pandas-dev/pandas/pulls/51370
2023-02-13T23:09:57Z
2023-08-01T17:19:46Z
null
2023-08-01T17:19:46Z
DOC: fix EX02 errors in docstrings
diff --git a/ci/code_checks.sh b/ci/code_checks.sh old mode 100755 new mode 100644 index 2c3cc29bd8c0c..280375aae9295 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -576,7 +576,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX02 --ignore_functions \ pandas.DataFrame.plot.line \ pandas.Series.plot.line \ - pandas.Timestamp.fromtimestamp \ pandas.api.types.infer_dtype \ pandas.api.types.is_datetime64_any_dtype \ pandas.api.types.is_datetime64_ns_dtype \ diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index d9d8ce3bb16d1..ff07f5d799339 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -570,7 +570,7 @@ class NaTType(_NaT): Examples -------- - >>> pd.Timestamp.fromtimestamp(1584199972) + >>> pd.Timestamp.fromtimestamp(1584199972) # doctest: +SKIP Timestamp('2020-03-14 15:32:52') Note that the output may change depending on your local time. diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 9e9dab155a5cf..33e8344c79d6c 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1451,7 +1451,7 @@ class Timestamp(_Timestamp): Examples -------- - >>> pd.Timestamp.fromtimestamp(1584199972) + >>> pd.Timestamp.fromtimestamp(1584199972) # doctest: +SKIP Timestamp('2020-03-14 15:32:52') Note that the output may change depending on your local time.
Related to the issue #51236 This PR enables functions: `pandas.core.groupby.DataFrameGroupBy.take` `pandas.Timestamp.fromtimestamp`
https://api.github.com/repos/pandas-dev/pandas/pulls/51369
2023-02-13T23:08:35Z
2023-02-24T20:01:44Z
null
2023-02-24T20:01:45Z
REF: use datetime C API instead of getattrs
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/tslibs/src/datetime/np_datetime.c index 2bac6c720c3b6..3a84adf083292 100644 --- a/pandas/_libs/tslibs/src/datetime/np_datetime.c +++ b/pandas/_libs/tslibs/src/datetime/np_datetime.c @@ -27,6 +27,7 @@ This file is derived from NumPy 1.7. See NUMPY_LICENSE.txt #include <numpy/ndarraytypes.h> #include "np_datetime.h" +#include "datetime.h" const npy_datetimestruct _AS_MIN_DTS = { 1969, 12, 31, 23, 59, 50, 776627, 963145, 224193}; @@ -374,35 +375,33 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, npy_datetimestruct *out) { // Assumes that obj is a valid datetime object PyObject *tmp; - PyObject *obj = (PyObject*)dtobj; /* Initialize the output to all zeros */ memset(out, 0, sizeof(npy_datetimestruct)); out->month = 1; out->day = 1; - out->year = PyLong_AsLong(PyObject_GetAttrString(obj, "year")); - out->month = PyLong_AsLong(PyObject_GetAttrString(obj, "month")); - out->day = PyLong_AsLong(PyObject_GetAttrString(obj, "day")); + PyDateTime_IMPORT; - // TODO(anyone): If we can get PyDateTime_IMPORT to work, we could use - // PyDateTime_Check here, and less verbose attribute lookups. - - /* Check for time attributes (if not there, return success as a date) */ - if (!PyObject_HasAttrString(obj, "hour") || - !PyObject_HasAttrString(obj, "minute") || - !PyObject_HasAttrString(obj, "second") || - !PyObject_HasAttrString(obj, "microsecond")) { - return 0; + if (!PyDate_Check(dtobj)) { + PyErr_SetString(PyExc_TypeError, "Expected date object"); + return NULL; } + PyDateTime_Date *dateobj = (PyDateTime_Date*)dtobj; + + out->year = PyDateTime_GET_YEAR(dateobj); + out->month = PyDateTime_GET_MONTH(dateobj); + out->day = PyDateTime_GET_DAY(dateobj); + out->hour = PyDateTime_DATE_GET_HOUR(dateobj); - out->hour = PyLong_AsLong(PyObject_GetAttrString(obj, "hour")); - out->min = PyLong_AsLong(PyObject_GetAttrString(obj, "minute")); - out->sec = PyLong_AsLong(PyObject_GetAttrString(obj, "second")); - out->us = PyLong_AsLong(PyObject_GetAttrString(obj, "microsecond")); + if (PyDateTime_Check(dateobj)) { + PyDateTime_DateTime* obj = (PyDateTime_DateTime*)dateobj; + out->min = PyDateTime_DATE_GET_MINUTE(obj); + out->sec = PyDateTime_DATE_GET_SECOND(obj); + out->us = PyDateTime_DATE_GET_MICROSECOND(obj); - if (PyObject_HasAttrString(obj, "tzinfo")) { - PyObject *offset = extract_utc_offset(obj); + // TODO(py3.10): in py3.10 we can use PyDateTime_DATE_GET_TZINFO + PyObject *offset = extract_utc_offset((PyObject*)obj); /* Apply the time zone offset if datetime obj is tz-aware */ if (offset != NULL) { if (offset == Py_None) {
@WillAyd i think there are a couple of paths that must not be reached, since it looks like they pass np.datetime64 objects to these pydatetime-requiring functions. in python/cython id check that with an `assert False`. have a favorite way of doing that in c code?
https://api.github.com/repos/pandas-dev/pandas/pulls/51368
2023-02-13T22:34:40Z
2023-02-16T23:21:24Z
null
2023-02-16T23:21:30Z
CLN: Remove default for columns in pivot
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2650090a3f61a..a5edd121ad21f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8250,6 +8250,12 @@ def groupby( Parameters ----------%s + columns : str or object or a list of str + Column to use to make new frame's columns. + + .. versionchanged:: 1.1.0 + Also accept list of columns names. + index : str or object or a list of str, optional Column to use to make new frame's index. If None, uses existing index. @@ -8257,12 +8263,6 @@ def groupby( .. versionchanged:: 1.1.0 Also accept list of index names. - columns : str or object or a list of str - Column to use to make new frame's columns. - - .. versionchanged:: 1.1.0 - Also accept list of columns names. - values : str, object or a list of the previous, optional Column(s) to use for populating new frame's values. If not specified, all remaining columns will be used and the result will @@ -8385,9 +8385,7 @@ def groupby( @Substitution("") @Appender(_shared_docs["pivot"]) - def pivot( - self, *, index=lib.NoDefault, columns=lib.NoDefault, values=lib.NoDefault - ) -> DataFrame: + def pivot(self, *, columns, index=lib.NoDefault, values=lib.NoDefault) -> DataFrame: from pandas.core.reshape.pivot import pivot return pivot(self, index=index, columns=columns, values=values) diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index eb95bb2484ebf..91a97f743efeb 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -500,12 +500,10 @@ def _convert_by(by): def pivot( data: DataFrame, *, + columns: IndexLabel, index: IndexLabel | lib.NoDefault = lib.NoDefault, - columns: IndexLabel | lib.NoDefault = lib.NoDefault, values: IndexLabel | lib.NoDefault = lib.NoDefault, ) -> DataFrame: - if columns is lib.NoDefault: - raise TypeError("pivot() missing 1 required argument: 'columns'") columns_listlike = com.convert_to_list_like(columns) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 2406379892834..b3d2a366bf58a 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -799,7 +799,7 @@ def test_pivot_with_list_like_values_nans(self, values, method): def test_pivot_columns_none_raise_error(self): # GH 30924 df = DataFrame({"col1": ["a", "b", "c"], "col2": [1, 2, 3], "col3": [1, 2, 3]}) - msg = r"pivot\(\) missing 1 required argument: 'columns'" + msg = r"pivot\(\) missing 1 required keyword-only argument: 'columns'" with pytest.raises(TypeError, match=msg): df.pivot(index="col1", values="col3") @@ -2513,7 +2513,7 @@ def test_pivot_index_list_values_none_immutable_args(self): def test_pivot_columns_not_given(self): # GH#48293 df = DataFrame({"a": [1], "b": 1}) - with pytest.raises(TypeError, match="missing 1 required argument"): + with pytest.raises(TypeError, match="missing 1 required keyword-only argument"): df.pivot() def test_pivot_columns_is_none(self):
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51367
2023-02-13T21:08:10Z
2023-02-14T11:17:30Z
2023-02-14T11:17:30Z
2023-02-14T21:21:16Z
Extensiondoc
diff --git a/doc/source/development/extending.rst b/doc/source/development/extending.rst index 5347aab2c731a..c7286616672b9 100644 --- a/doc/source/development/extending.rst +++ b/doc/source/development/extending.rst @@ -74,10 +74,11 @@ applies only to certain dtypes. Extension types --------------- -.. warning:: +.. note:: - The :class:`pandas.api.extensions.ExtensionDtype` and :class:`pandas.api.extensions.ExtensionArray` APIs are new and - experimental. They may change between versions without warning. + The :class:`pandas.api.extensions.ExtensionDtype` and :class:`pandas.api.extensions.ExtensionArray` APIs were + experimental prior to pandas 1.5. Starting with version 1.5, future changes will follow + the :ref:`pandas deprecation policy <policies.version>`. pandas defines an interface for implementing data types and arrays that *extend* NumPy's type system. pandas itself uses the extension system for some types
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51366
2023-02-13T21:04:25Z
2023-02-13T21:04:33Z
null
2023-02-13T21:05:55Z
ENH: Improve performance for arrow dtypes in monotonic join
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 29f360e050548..08ba7d80f6880 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1089,7 +1089,7 @@ Performance improvements - Performance improvement in :meth:`Series.rank` for pyarrow-backed dtypes (:issue:`50264`) - Performance improvement in :meth:`Series.searchsorted` for pyarrow-backed dtypes (:issue:`50447`) - Performance improvement in :meth:`Series.fillna` for extension array dtypes (:issue:`49722`, :issue:`50078`) -- Performance improvement in :meth:`Index.join`, :meth:`Index.intersection` and :meth:`Index.union` for masked dtypes when :class:`Index` is monotonic (:issue:`50310`) +- Performance improvement in :meth:`Index.join`, :meth:`Index.intersection` and :meth:`Index.union` for masked and arrow dtypes when :class:`Index` is monotonic (:issue:`50310`, :issue:`51365`) - Performance improvement for :meth:`Series.value_counts` with nullable dtype (:issue:`48338`) - Performance improvement for :class:`Series` constructor passing integer numpy array with nullable dtype (:issue:`48338`) - Performance improvement for :class:`DatetimeIndex` constructor passing a list (:issue:`48609`) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 363bfe76d40fb..9d4a4ca8a5140 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -145,6 +145,7 @@ validate_putmask, ) from pandas.core.arrays import ( + ArrowExtensionArray, BaseMaskedArray, Categorical, ExtensionArray, @@ -4847,8 +4848,10 @@ def _can_use_libjoin(self) -> bool: if type(self) is Index: # excludes EAs, but include masks, we get here with monotonic # values only, meaning no NA - return isinstance(self.dtype, np.dtype) or isinstance( - self.values, BaseMaskedArray + return ( + isinstance(self.dtype, np.dtype) + or isinstance(self.values, BaseMaskedArray) + or isinstance(self._values, ArrowExtensionArray) ) return not is_interval_dtype(self.dtype) @@ -4939,6 +4942,10 @@ def _get_join_target(self) -> ArrayLike: if isinstance(self._values, BaseMaskedArray): # This is only used if our array is monotonic, so no NAs present return self._values._data + elif isinstance(self._values, ArrowExtensionArray): + # This is only used if our array is monotonic, so no missing values + # present + return self._values.to_numpy() return self._get_engine_target() def _from_join_target(self, result: np.ndarray) -> ArrayLike: @@ -4948,6 +4955,8 @@ def _from_join_target(self, result: np.ndarray) -> ArrayLike: """ if isinstance(self.values, BaseMaskedArray): return type(self.values)(result, np.zeros(result.shape, dtype=np.bool_)) + elif isinstance(self.values, ArrowExtensionArray): + return type(self.values)._from_sequence(result) return result @doc(IndexOpsMixin._memory_usage) diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 001efe07b5d2b..708de02518b73 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -886,3 +886,11 @@ def test_symmetric_difference_non_index(self, sort): result = index1.symmetric_difference(index2, result_name="new_name", sort=sort) assert tm.equalContents(result, expected) assert result.name == "new_name" + + def test_union_ea_dtypes(self, any_numeric_ea_and_arrow_dtype): + # GH#51365 + idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype) + idx2 = Index([3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype) + result = idx.union(idx2) + expected = Index([1, 2, 3, 4, 5], dtype=any_numeric_ea_and_arrow_dtype) + tm.assert_index_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. ``` idx = Index(list(range(1, 1_000_000)), dtype="int64[pyarrow]") idx2 = Index(list(range(100_000, 1_100_000)), dtype="int64[pyarrow]") idx.union(idx2) # main # %timeit idx.union(idx2) # 327 ms ± 72.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # pr # %timeit idx.union(idx2) # 2.79 ms ± 27.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/51365
2023-02-13T20:56:40Z
2023-02-16T10:47:49Z
2023-02-16T10:47:49Z
2023-02-16T10:47:53Z
CLN: idiomatic indexing checks
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 363bfe76d40fb..2b55e0c8c1d0e 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3732,10 +3732,11 @@ def get_indexer( # Only call equals if we have same dtype to avoid inference/casting return np.arange(len(target), dtype=np.intp) - if not is_dtype_equal(self.dtype, target.dtype) and not is_interval_dtype( - self.dtype - ): - # IntervalIndex gets special treatment for partial-indexing + if not is_dtype_equal( + self.dtype, target.dtype + ) and not self._should_partial_index(target): + # _should_partial_index e.g. IntervalIndex with numeric scalars + # that can be matched to Interval scalars. dtype = self._find_common_type_compat(target) this = self.astype(dtype, copy=False) @@ -5739,9 +5740,9 @@ def get_indexer_non_unique( target = ensure_index(target) target = self._maybe_cast_listlike_indexer(target) - if not self._should_compare(target) and not is_interval_dtype(self.dtype): - # IntervalIndex get special treatment bc numeric scalars can be - # matched to Interval scalars + if not self._should_compare(target) and not self._should_partial_index(target): + # _should_partial_index e.g. IntervalIndex with numeric scalars + # that can be matched to Interval scalars. return self._get_indexer_non_comparable(target, method=None, unique=False) pself, ptarget = self._maybe_promote(target) diff --git a/pandas/core/series.py b/pandas/core/series.py index 8934b7c65130b..78c6cc9f94ed2 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1111,7 +1111,7 @@ def __setitem__(self, key, value) -> None: except KeyError: # We have a scalar (or for MultiIndex or object-dtype, scalar-like) # key that is not present in self.index. - if is_integer(key) and self.index.inferred_type != "integer": + if is_integer(key): if not self.index._should_fallback_to_positional: # GH#33469 self.loc[key] = value
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51360
2023-02-13T15:18:15Z
2023-02-13T18:22:22Z
2023-02-13T18:22:22Z
2023-02-13T18:44:02Z
BLD: Fix uploading of aarch64 wheels
diff --git a/.circleci/config.yml b/.circleci/config.yml index 5f25c891acf8a..ac28728685ce4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -26,18 +26,18 @@ jobs: image: ubuntu-2004:202101-01 resource_class: arm.large environment: - TAG = << pipeline.git.tag >> - TRIGGER_SOURCE = << pipeline.trigger_source >> + ENV_FILE: ci/deps/circle-38-arm64.yaml + TRIGGER_SOURCE: << pipeline.trigger_source >> steps: - checkout - run: name: Check if build is necessary command: | # Check if tag is defined or TRIGGER_SOURCE is scheduled - if [[ -n ${TAG} ]]; then - export IS_PUSH="true" + if [[ -n "$CIRCLE_TAG" ]]; then + echo 'export IS_PUSH="true"' >> "$BASH_ENV" elif [[ $TRIGGER_SOURCE == "scheduled_pipeline" ]]; then - export IS_SCHEDULE_DISPATCH="true" + echo 'export IS_SCHEDULE_DISPATCH="true"' >> "$BASH_ENV" # Look for the build label/[wheel build] in commit # grep takes a regex, so need to escape brackets elif (git log --format=oneline -n 1 $CIRCLE_SHA1) | grep -q '\[wheel build\]'; then @@ -52,15 +52,24 @@ jobs: cibuildwheel --output-dir wheelhouse environment: CIBW_BUILD: << parameters.cibw-build >> + - run: - name: Upload wheels + name: Install Anaconda Client & Upload Wheels command: | - if [[ -n ${TAG} ]]; then - export IS_PUSH="true" - fi - if [[ $TRIGGER_SOURCE == "scheduled_pipeline" ]]; then - export IS_SCHEDULE_DISPATCH="true" - fi + echo "Install Mambaforge" + MAMBA_URL="https://github.com/conda-forge/miniforge/releases/download/4.14.0-0/Mambaforge-4.14.0-0-Linux-aarch64.sh" + echo "Downloading $MAMBA_URL" + wget -q $MAMBA_URL -O minimamba.sh + chmod +x minimamba.sh + + MAMBA_DIR="$HOME/miniconda3" + rm -rf $MAMBA_DIR + ./minimamba.sh -b -p $MAMBA_DIR + + export PATH=$MAMBA_DIR/bin:$PATH + + mamba install -y -c conda-forge anaconda-client + source ci/upload_wheels.sh set_upload_vars upload_wheels
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51358
2023-02-13T12:41:28Z
2023-02-14T21:15:05Z
2023-02-14T21:15:05Z
2023-02-14T21:17:18Z
STYLE: Fix errors in doctests
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 96abd98bbdd75..0369de8db1339 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3329,7 +3329,7 @@ def to_latex( >>> print(df.to_latex(index=False, ... formatters={"name": str.upper}, ... float_format="{:.1f}".format, - ... ) # doctest: +SKIP + ... )) # doctest: +SKIP \begin{tabular}{lrr} \toprule name & age & height \\ diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index bb1905ccd4740..3ecee50ffbaa7 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -455,11 +455,11 @@ class CSSWarning(UserWarning): Examples -------- >>> df = pd.DataFrame({'A': [1, 1, 1]}) - >>> df.style.applymap(lambda x: 'background-color: blueGreenRed;') - ... .to_excel('styled.xlsx') # doctest: +SKIP + >>> (df.style.applymap(lambda x: 'background-color: blueGreenRed;') + ... .to_excel('styled.xlsx')) # doctest: +SKIP ... # CSSWarning: Unhandled color format: 'blueGreenRed' - >>> df.style.applymap(lambda x: 'border: 1px solid red red;') - ... .to_excel('styled.xlsx') # doctest: +SKIP + >>> (df.style.applymap(lambda x: 'border: 1px solid red red;') + ... .to_excel('styled.xlsx')) # doctest: +SKIP ... # CSSWarning: Too many tokens provided to "border" (expected 1-3) """ @@ -569,7 +569,7 @@ class CategoricalConversionWarning(Warning): >>> from pandas.io.stata import StataReader >>> with StataReader('dta_file', chunksize=2) as reader: # doctest: +SKIP ... for i, block in enumerate(reader): - ... print(i, block)) + ... print(i, block) ... # CategoricalConversionWarning: One or more series with value labels... """ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 13aa035e34374..25ba4b697d97b 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -961,12 +961,12 @@ def to_latex( Second we will format the display and, since our table is quite wide, will hide the repeated level-0 of the index: - >>> styler.format(subset="Equity", precision=2) + >>> (styler.format(subset="Equity", precision=2) ... .format(subset="Stats", precision=1, thousands=",") ... .format(subset="Rating", formatter=str.upper) ... .format_index(escape="latex", axis=1) ... .format_index(escape="latex", axis=0) - ... .hide(level=0, axis=0) # doctest: +SKIP + ... .hide(level=0, axis=0)) # doctest: +SKIP Note that one of the string entries of the index and column headers is "H&M". Without applying the `escape="latex"` option to the `format_index` method the @@ -982,8 +982,8 @@ def to_latex( ... elif v == "Sell": color = "#ff5933" ... else: color = "#ffdd33" ... return f"color: {color}; font-weight: bold;" - >>> styler.background_gradient(cmap="inferno", subset="Equity", vmin=0, vmax=1) - ... .applymap(rating_color, subset="Rating") # doctest: +SKIP + >>> (styler.background_gradient(cmap="inferno", subset="Equity", vmin=0, vmax=1) + ... .applymap(rating_color, subset="Rating")) # doctest: +SKIP All the above styles will work with HTML (see below) and LaTeX upon conversion: @@ -3503,9 +3503,9 @@ def pipe(self, func: Callable, *args, **kwargs): Since the method returns a ``Styler`` object it can be chained with other methods as if applying the underlying highlighters directly. - >>> df.style.format("{:.1f}") + >>> (df.style.format("{:.1f}") ... .pipe(some_highlights, min_color="green") - ... .highlight_between(left=2, right=5) # doctest: +SKIP + ... .highlight_between(left=2, right=5)) # doctest: +SKIP .. figure:: ../../_static/style/df_pipe_hl2.png diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 6ae9c528e4772..41d66ad297da4 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -1076,8 +1076,8 @@ def format( Multiple ``na_rep`` or ``precision`` specifications under the default ``formatter``. - >>> df.style.format(na_rep='MISS', precision=1, subset=[0]) - ... .format(na_rep='PASS', precision=2, subset=[1, 2]) # doctest: +SKIP + >>> (df.style.format(na_rep='MISS', precision=1, subset=[0]) + ... .format(na_rep='PASS', precision=2, subset=[1, 2])) # doctest: +SKIP 0 1 2 0 MISS 1.00 A 1 2.0 PASS 3.00
- [x] closes #51341 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51356
2023-02-13T08:47:31Z
2023-02-16T11:20:38Z
2023-02-16T11:20:38Z
2023-02-16T11:20:38Z
BUG: iterparse on `read_xml` ignores repeated elements
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 778169b0dbeb4..b76655bc134b5 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1304,6 +1304,7 @@ I/O - Bug in :meth:`DataFrame.to_dict` not converting ``NA`` to ``None`` (:issue:`50795`) - Bug in :meth:`DataFrame.to_json` where it would segfault when failing to encode a string (:issue:`50307`) - Bug in :func:`read_xml` where file-like objects failed when iterparse is used (:issue:`50641`) +- Bug in :func:`read_xml` ignored repeated elements when iterparse is used (:issue:`51183`) Period ^^^^^^ diff --git a/pandas/io/xml.py b/pandas/io/xml.py index 64fda2fdb0299..3ee4e64faf75c 100644 --- a/pandas/io/xml.py +++ b/pandas/io/xml.py @@ -337,6 +337,10 @@ def _iterparse_nodes(self, iterparse: Callable) -> list[dict[str, str | None]]: "local disk and not as compressed files or online sources." ) + iterparse_repeats = len(self.iterparse[row_node]) != len( + set(self.iterparse[row_node]) + ) + for event, elem in iterparse(self.path_or_buffer, events=("start", "end")): curr_elem = elem.tag.split("}")[1] if "}" in elem.tag else elem.tag @@ -345,12 +349,13 @@ def _iterparse_nodes(self, iterparse: Callable) -> list[dict[str, str | None]]: row = {} if row is not None: - if self.names: + if self.names and iterparse_repeats: for col, nm in zip(self.iterparse[row_node], self.names): if curr_elem == col: elem_val = elem.text.strip() if elem.text else None - if row.get(nm) != elem_val and nm not in row: + if elem_val not in row.values() and nm not in row: row[nm] = elem_val + if col in elem.attrib: if elem.attrib[col] not in row.values() and nm not in row: row[nm] = elem.attrib[col] diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index dfa251788ddc3..b73116519178e 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -948,6 +948,55 @@ def test_repeat_values_new_names(parser): tm.assert_frame_equal(df_iter, df_expected) +def test_repeat_elements(parser): + xml = """\ +<shapes> + <shape> + <value item="name">circle</value> + <value item="family">ellipse</value> + <value item="degrees">360</value> + <value item="sides">0</value> + </shape> + <shape> + <value item="name">triangle</value> + <value item="family">polygon</value> + <value item="degrees">180</value> + <value item="sides">3</value> + </shape> + <shape> + <value item="name">square</value> + <value item="family">polygon</value> + <value item="degrees">360</value> + <value item="sides">4</value> + </shape> +</shapes>""" + df_xpath = read_xml( + xml, + xpath=".//shape", + parser=parser, + names=["name", "family", "degrees", "sides"], + ) + + df_iter = read_xml_iterparse( + xml, + parser=parser, + iterparse={"shape": ["value", "value", "value", "value"]}, + names=["name", "family", "degrees", "sides"], + ) + + df_expected = DataFrame( + { + "name": ["circle", "triangle", "square"], + "family": ["ellipse", "polygon", "polygon"], + "degrees": [360, 180, 360], + "sides": [0, 3, 4], + } + ) + + tm.assert_frame_equal(df_xpath, df_expected) + tm.assert_frame_equal(df_iter, df_expected) + + def test_names_option_wrong_length(datapath, parser): filename = datapath("io", "data", "xml", "books.xml")
- [X] closes #51183 - [X] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [X] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51355
2023-02-13T01:12:08Z
2023-02-13T17:45:50Z
2023-02-13T17:45:50Z
2023-02-13T17:45:58Z
TST: xfail flaky test
diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py index e4cd0f1d19a79..b08ec8c1172bc 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -13,6 +13,7 @@ import pytest +from pandas.compat import is_ci_environment from pandas.errors import ( EmptyDataError, ParserError, @@ -404,8 +405,13 @@ def test_context_manageri_user_provided(all_parsers, datapath): assert not reader.handles.handle.closed -def test_file_descriptor_leak(all_parsers): +def test_file_descriptor_leak(all_parsers, using_copy_on_write, request): # GH 31488 + if using_copy_on_write and is_ci_environment(): + mark = pytest.mark.xfail( + reason="2023-02-12 frequent-but-flaky failures", strict=False + ) + request.node.add_marker(mark) parser = all_parsers with tm.ensure_clean() as path:
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51354
2023-02-12T22:56:52Z
2023-02-13T17:48:14Z
2023-02-13T17:48:14Z
2023-02-13T17:56:36Z
DOC: run typing checks
diff --git a/doc/source/development/contributing_codebase.rst b/doc/source/development/contributing_codebase.rst index 63554447f295e..c6b2cd10519ae 100644 --- a/doc/source/development/contributing_codebase.rst +++ b/doc/source/development/contributing_codebase.rst @@ -266,17 +266,21 @@ This module will ultimately house types for repeatedly used concepts like "path- Validating type hints ~~~~~~~~~~~~~~~~~~~~~ -pandas uses `mypy <http://mypy-lang.org>`_ and `pyright <https://github.com/microsoft/pyright>`_ to statically analyze the code base and type hints. After making any change you can ensure your type hints are correct by running +pandas uses `mypy <http://mypy-lang.org>`_ and `pyright <https://github.com/microsoft/pyright>`_ to statically analyze the code base and type hints. After making any change you can ensure your type hints are consistent by running .. code-block:: shell + pre-commit run --hook-stage manual --all-files mypy + pre-commit run --hook-stage manual --all-files pyright + pre-commit run --hook-stage manual --all-files pyright_reportGeneralTypeIssues # the following might fail if the installed pandas version does not correspond to your local git version - pre-commit run --hook-stage manual --all-files + pre-commit run --hook-stage manual --all-files stubtest - # if the above fails due to stubtest - SKIP=stubtest pre-commit run --hook-stage manual --all-files +in your python environment. -in your activated python environment. A recent version of ``numpy`` (>=1.22.0) is required for type validation. +.. warning:: + + * Please be aware that the above commands will use the current python environment. If your python packages are older/newer than those installed by the pandas CI, the above commands might fail. This is often the case when the ``mypy`` or ``numpy`` versions do not match. Please see :ref:`how to setup the python environment <contributing.mamba>` or select a `recently succeeded workflow <https://github.com/pandas-dev/pandas/actions/workflows/code-checks.yml?query=branch%3Amain+is%3Asuccess>`_, select the "Docstring validation, typing, and other manual pre-commit hooks" job, then click on "Set up Conda" and "Environment info" to see which versions the pandas CI installs. .. _contributing.ci:
- [ ] closes #51313 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51352
2023-02-12T22:33:31Z
2023-02-17T04:33:58Z
2023-02-17T04:33:58Z
2023-08-09T15:08:40Z
BUG: Period('') raising
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 29f360e050548..1d123453e60d2 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1312,6 +1312,7 @@ Period - Bug in :class:`Period` where passing a string with finer resolution than nanosecond would result in a ``KeyError`` instead of dropping the extra precision (:issue:`50417`) - Bug in parsing strings representing Week-periods e.g. "2017-01-23/2017-01-29" as minute-frequency instead of week-frequency (:issue:`50803`) - Bug in :meth:`.GroupBy.sum`, :meth:`.GroupBy.cumsum`, :meth:`.GroupBy.prod`, :meth:`.GroupBy.cumprod` with :class:`PeriodDtype` failing to raise ``TypeError`` (:issue:`51040`) +- Bug in parsing empty string with :class:`Period` incorrectly raising ``ValueError`` instead of returning ``NaT`` (:issue:`51349`) - Plotting diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index b8cb20467a3c0..77c8be6be07e4 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2580,7 +2580,7 @@ class Period(_Period): ordinal = converted.ordinal elif checknull_with_nat(value) or (isinstance(value, str) and - value in nat_strings): + (value in nat_strings or len(value) == 0)): # explicit str check is necessary to avoid raising incorrectly # if we have a non-hashable value. ordinal = NPY_NAT diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 3192baacb4ef4..562f57c898582 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -97,22 +97,13 @@ def test_nat_vector_field_access(): @pytest.mark.parametrize("klass", [Timestamp, Timedelta, Period]) -@pytest.mark.parametrize("value", [None, np.nan, iNaT, float("nan"), NaT, "NaT", "nat"]) +@pytest.mark.parametrize( + "value", [None, np.nan, iNaT, float("nan"), NaT, "NaT", "nat", "", "NAT"] +) def test_identity(klass, value): assert klass(value) is NaT -@pytest.mark.parametrize("klass", [Timestamp, Timedelta, Period]) -@pytest.mark.parametrize("value", ["", "nat", "NAT", None, np.nan]) -def test_equality(klass, value, request): - if klass is Period and value == "": - request.node.add_marker( - pytest.mark.xfail(reason="Period cannot parse empty string") - ) - - assert klass(value)._value == iNaT - - @pytest.mark.parametrize("klass", [Timestamp, Timedelta]) @pytest.mark.parametrize("method", ["round", "floor", "ceil"]) @pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"])
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51349
2023-02-12T19:40:29Z
2023-02-13T17:51:20Z
2023-02-13T17:51:19Z
2023-02-13T17:56:15Z
STYLE upgrade black formatter
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7bd662308afa8..2f13ac4c73fa0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -125,7 +125,7 @@ repos: language: python require_serial: true types_or: [python, pyi] - additional_dependencies: [black==22.10.0] + additional_dependencies: [black==23.1.0] - id: pyright # note: assumes python env is setup and activated name: pyright diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index e669eee84b354..eef81242abc7c 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -15,7 +15,6 @@ class Factorize: - params = [ [True, False], [True, False], @@ -65,7 +64,6 @@ def time_factorize(self, unique, sort, dtype): class Duplicated: - params = [ [True, False], ["first", "last", False], @@ -96,7 +94,6 @@ def time_duplicated(self, unique, keep, dtype): class DuplicatedMaskedArray: - params = [ [True, False], ["first", "last", False], diff --git a/asv_bench/benchmarks/algos/isin.py b/asv_bench/benchmarks/algos/isin.py index 16d90b9d23741..ac79ab65cea81 100644 --- a/asv_bench/benchmarks/algos/isin.py +++ b/asv_bench/benchmarks/algos/isin.py @@ -12,7 +12,6 @@ class IsIn: - params = [ "int64", "uint64", @@ -183,7 +182,6 @@ def time_isin(self, dtype, M, offset_factor): class IsInFloat64: - params = [ [np.float64, "Float64"], ["many_different_values", "few_different_values", "only_nans_values"], diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index 4f84e0a562687..ab3b38fee1b06 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -173,7 +173,6 @@ def time_op_same_blocks(self, op, shape): class Ops: - params = [[True, False], ["default", 1]] param_names = ["use_numexpr", "threads"] @@ -257,7 +256,6 @@ def time_frame_series_dot(self): class Timeseries: - params = [None, "US/Eastern"] param_names = ["tz"] @@ -316,7 +314,6 @@ def time_categorical_op(self, op): class IndexArithmetic: - params = ["float", "int"] param_names = ["dtype"] @@ -387,7 +384,6 @@ def time_add_timedeltas(self, df): class AddOverflowScalar: - params = [1, -1, 0] param_names = ["scalar"] @@ -455,7 +451,6 @@ def time_add_overflow_both_arg_nan(self): class OffsetArrayArithmetic: - params = offsets param_names = ["offset"] diff --git a/asv_bench/benchmarks/array.py b/asv_bench/benchmarks/array.py index 3ffaaf706d636..ecd8c26ba6ca5 100644 --- a/asv_bench/benchmarks/array.py +++ b/asv_bench/benchmarks/array.py @@ -72,7 +72,6 @@ def time_from_list(self): class ArrowStringArray: - params = [False, True] param_names = ["multiple_chunks"] @@ -107,7 +106,6 @@ def time_tolist(self, multiple_chunks): class ArrowExtensionArray: - params = [ [ "boolean[pyarrow]", diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py index d515743ea4431..2a004113d1b91 100644 --- a/asv_bench/benchmarks/attrs_caching.py +++ b/asv_bench/benchmarks/attrs_caching.py @@ -22,7 +22,6 @@ def time_set_index(self): class SeriesArrayAttribute: - params = [["numeric", "object", "category", "datetime64", "datetime64tz"]] param_names = ["dtype"] diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index ff0b3b2fb651d..02747911d2226 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -143,7 +143,6 @@ def time_concat_non_overlapping_index(self): class ValueCounts: - params = [True, False] param_names = ["dropna"] @@ -254,7 +253,6 @@ def time_categorical_contains(self): class CategoricalSlicing: - params = ["monotonic_incr", "monotonic_decr", "non_monotonic"] param_names = ["index"] diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py index d1a9da158728c..2db00cc7f2ad9 100644 --- a/asv_bench/benchmarks/ctors.py +++ b/asv_bench/benchmarks/ctors.py @@ -49,7 +49,6 @@ def list_of_lists_with_none(arr): class SeriesConstructors: - param_names = ["data_fmt", "with_index", "dtype"] params = [ [ @@ -124,7 +123,6 @@ def time_multiindex_from_iterables(self): class DatetimeIndexConstructor: def setup(self): - N = 20_000 dti = date_range("1900-01-01", periods=N) diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py index 55f6be848aa13..52c87455b12b3 100644 --- a/asv_bench/benchmarks/dtypes.py +++ b/asv_bench/benchmarks/dtypes.py @@ -49,7 +49,6 @@ def time_pandas_dtype_invalid(self, dtype): class SelectDtypes: - try: params = [ tm.ALL_INT_NUMPY_DTYPES diff --git a/asv_bench/benchmarks/eval.py b/asv_bench/benchmarks/eval.py index b5442531e748a..8a3d224c59a09 100644 --- a/asv_bench/benchmarks/eval.py +++ b/asv_bench/benchmarks/eval.py @@ -9,7 +9,6 @@ class Eval: - params = [["numexpr", "python"], [1, "all"]] param_names = ["engine", "threads"] diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index 6fe346fd7283d..7092a679b8cf0 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -74,7 +74,6 @@ def time_mi_series(self): class FromDictwithTimestamp: - params = [Nano(1), Hour(1)] param_names = ["offset"] @@ -89,7 +88,6 @@ def time_dict_with_timestamp_offsets(self, offset): class FromRecords: - params = [None, 1000] param_names = ["nrows"] @@ -116,7 +114,6 @@ def time_frame_from_ndarray(self): class FromLists: - goal_time = 0.2 def setup(self): @@ -129,7 +126,6 @@ def time_frame_from_lists(self): class FromRange: - goal_time = 0.2 def setup(self): @@ -162,7 +158,6 @@ def time_frame_from_scalar_ea_float64_na(self): class FromArrays: - goal_time = 0.2 def setup(self): diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 9a5fc1c607f6a..11b30ce601be6 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -371,7 +371,6 @@ def time_isnull_obj(self): class Fillna: - params = ( [True, False], ["pad", "bfill"], @@ -412,7 +411,6 @@ def time_frame_fillna(self, inplace, method, dtype): class Dropna: - params = (["all", "any"], [0, 1]) param_names = ["how", "axis"] @@ -432,7 +430,6 @@ def time_dropna_axis_mixed_dtypes(self, how, axis): class Count: - params = [0, 1] param_names = ["axis"] @@ -531,7 +528,6 @@ def time_frame_object_unequal(self): class Interpolate: - params = [None, "infer"] param_names = ["downcast"] @@ -616,7 +612,6 @@ def time_frame_duplicated_subset(self): class XS: - params = [0, 1] param_names = ["axis"] @@ -629,7 +624,6 @@ def time_frame_xs(self, axis): class SortValues: - params = [True, False] param_names = ["ascending"] @@ -657,7 +651,6 @@ def time_frame_sort_values_by_columns(self): class Quantile: - params = [0, 1] param_names = ["axis"] @@ -697,7 +690,6 @@ def time_info(self): class NSort: - params = ["first", "last", "all"] param_names = ["keep"] diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index 31654a5c75617..4d5c31d2dddf8 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -87,12 +87,10 @@ def inner(*args, **kwargs): class ParallelGroupbyMethods: - params = ([2, 4, 8], ["count", "last", "max", "mean", "min", "prod", "sum", "var"]) param_names = ["threads", "method"] def setup(self, threads, method): - N = 10**6 ngroups = 10**3 df = DataFrame( @@ -119,12 +117,10 @@ def time_loop(self, threads, method): class ParallelGroups: - params = [2, 4, 8] param_names = ["threads"] def setup(self, threads): - size = 2**22 ngroups = 10**3 data = Series(np.random.randint(0, ngroups, size=size)) @@ -140,12 +136,10 @@ def time_get_groups(self, threads): class ParallelTake1D: - params = ["int64", "float64"] param_names = ["dtype"] def setup(self, dtype): - N = 10**6 df = DataFrame({"col": np.arange(N, dtype=dtype)}) indexer = np.arange(100, len(df) - 100) @@ -167,7 +161,6 @@ class ParallelKth: repeat = 5 def setup(self): - N = 10**7 k = 5 * 10**5 kwargs_list = [{"arr": np.random.randn(N)}, {"arr": np.random.randn(N)}] @@ -184,7 +177,6 @@ def time_kth_smallest(self): class ParallelDatetimeFields: def setup(self): - N = 10**6 self.dti = date_range("1900-01-01", periods=N, freq="T") self.period = self.dti.to_period("D") @@ -233,12 +225,10 @@ def run(period): class ParallelRolling: - params = ["median", "mean", "min", "max", "var", "skew", "kurt", "std"] param_names = ["method"] def setup(self, method): - win = 100 arr = np.random.rand(100000) if hasattr(DataFrame, "rolling"): @@ -274,14 +264,12 @@ def time_rolling(self, method): class ParallelReadCSV(BaseIO): - number = 1 repeat = 5 params = ["float", "object", "datetime"] param_names = ["dtype"] def setup(self, dtype): - rows = 10000 cols = 50 data = { @@ -309,14 +297,12 @@ def time_read_csv(self, dtype): class ParallelFactorize: - number = 1 repeat = 5 params = [2, 4, 8] param_names = ["threads"] def setup(self, threads): - strings = tm.makeStringIndex(100000) @test_parallel(num_threads=threads) diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 58d8ec39120e6..4c0f3ddd826b7 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -70,7 +70,6 @@ def time_groupby_apply_dict_return(self): class Apply: - param_names = ["factor"] params = [4, 5] @@ -125,7 +124,6 @@ def time_groupby_apply_non_unique_unsorted_index(self): class Groups: - param_names = ["key"] params = ["int64_small", "int64_large", "object_small", "object_large"] @@ -154,7 +152,6 @@ def time_series_indices(self, data, key): class GroupManyLabels: - params = [1, 1000] param_names = ["ncols"] @@ -169,7 +166,6 @@ def time_sum(self, ncols): class Nth: - param_names = ["dtype"] params = ["float32", "float64", "datetime", "object"] @@ -416,7 +412,6 @@ def time_srs_bfill(self): class GroupByMethods: - param_names = ["dtype", "method", "application", "ncols"] params = [ ["int", "int16", "float", "object", "datetime", "uint"], @@ -865,7 +860,6 @@ def time_first(self): class TransformEngine: - param_names = ["parallel"] params = [[True, False]] @@ -908,7 +902,6 @@ def function(values): class AggEngine: - param_names = ["parallel"] params = [[True, False]] diff --git a/asv_bench/benchmarks/hash_functions.py b/asv_bench/benchmarks/hash_functions.py index c6e73e28f4a27..d2c5b4dfbef70 100644 --- a/asv_bench/benchmarks/hash_functions.py +++ b/asv_bench/benchmarks/hash_functions.py @@ -55,7 +55,6 @@ def time_unique(self, exponent): class NumericSeriesIndexing: - params = [ (np.int64, np.uint64, np.float64), (10**4, 10**5, 5 * 10**5, 10**6, 5 * 10**6), @@ -73,7 +72,6 @@ def time_loc_slice(self, index, N): class NumericSeriesIndexingShuffled: - params = [ (np.int64, np.uint64, np.float64), (10**4, 10**5, 5 * 10**5, 10**6, 5 * 10**6), diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py index 9b72483745169..bdc8a6a7aa1df 100644 --- a/asv_bench/benchmarks/index_object.py +++ b/asv_bench/benchmarks/index_object.py @@ -16,7 +16,6 @@ class SetOperations: - params = ( ["monotonic", "non_monotonic"], ["datetime", "date_string", "int", "strings", "ea_int"], @@ -125,7 +124,6 @@ def time_non_object_equals_multiindex(self): class IndexAppend: def setup(self): - N = 10_000 self.range_idx = RangeIndex(0, 100) self.int_idx = self.range_idx.astype(int) @@ -152,7 +150,6 @@ def time_append_obj_list(self): class Indexing: - params = ["String", "Float", "Int"] param_names = ["dtype"] diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 19ef536a636ea..53827cfcf64fb 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -25,7 +25,6 @@ class NumericSeriesIndexing: - params = [ (np.int64, np.uint64, np.float64), ("unique_monotonic_inc", "nonunique_monotonic_inc"), @@ -97,7 +96,6 @@ class NumericMaskedIndexing: param_names = ["dtype", "monotonic"] def setup(self, dtype, monotonic): - indices = { True: Index(self.monotonic_list, dtype=dtype), False: Index(self.non_monotonic_list, dtype=dtype).append( @@ -116,7 +114,6 @@ def time_get_indexer_dups(self, dtype, monotonic): class NonNumericSeriesIndexing: - params = [ ("string", "datetime", "period"), ("unique_monotonic_inc", "nonunique_monotonic_inc", "non_monotonic"), @@ -191,7 +188,6 @@ def time_boolean_rows_boolean(self): class DataFrameNumericIndexing: - params = [ (np.int64, np.uint64, np.float64), ("unique_monotonic_inc", "nonunique_monotonic_inc"), @@ -228,7 +224,6 @@ def time_bool_indexer(self, index, index_structure): class Take: - params = ["int", "datetime"] param_names = ["index"] @@ -247,7 +242,6 @@ def time_take(self, index): class MultiIndexing: - params = [True, False] param_names = ["unique_levels"] @@ -376,7 +370,6 @@ def time_loc_sorted(self): class CategoricalIndexIndexing: - params = ["monotonic_incr", "monotonic_decr", "non_monotonic"] param_names = ["index"] @@ -522,7 +515,6 @@ def time_setitem_list(self): class ChainIndexing: - params = [None, "warn"] param_names = ["mode"] diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py index ce208761638c5..6585a4be78dc6 100644 --- a/asv_bench/benchmarks/indexing_engines.py +++ b/asv_bench/benchmarks/indexing_engines.py @@ -56,7 +56,6 @@ def _get_masked_engines(): class NumericEngineIndexing: - params = [ _get_numeric_engines(), ["monotonic_incr", "monotonic_decr", "non_monotonic"], @@ -106,7 +105,6 @@ def time_get_loc_near_middle(self, engine_and_dtype, index_type, unique, N): class MaskedNumericEngineIndexing: - params = [ _get_masked_engines(), ["monotonic_incr", "monotonic_decr", "non_monotonic"], @@ -161,7 +159,6 @@ def time_get_loc_near_middle(self, engine_and_dtype, index_type, unique, N): class ObjectEngineIndexing: - params = [("monotonic_incr", "monotonic_decr", "non_monotonic")] param_names = ["index_type"] diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py index 5de3bcda46424..476ff14dcc92a 100644 --- a/asv_bench/benchmarks/inference.py +++ b/asv_bench/benchmarks/inference.py @@ -24,7 +24,6 @@ class ToNumeric: - params = ["ignore", "coerce"] param_names = ["errors"] @@ -45,7 +44,6 @@ def time_from_str(self, errors): class ToNumericDowncast: - param_names = ["dtype", "downcast"] params = [ [ @@ -153,7 +151,6 @@ def time_format_YYYYMMDD(self): class ToDatetimeCacheSmallCount: - params = ([True, False], [50, 500, 5000, 100000]) param_names = ["cache", "count"] @@ -250,7 +247,6 @@ def time_different_offset_to_utc(self): class ToDatetimeCache: - params = [True, False] param_names = ["cache"] @@ -307,7 +303,6 @@ def time_convert_string_seconds(self): class ToTimedeltaErrors: - params = ["coerce", "ignore"] param_names = ["errors"] diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py index 10aef954a3475..f5aa421951a1d 100644 --- a/asv_bench/benchmarks/io/csv.py +++ b/asv_bench/benchmarks/io/csv.py @@ -23,7 +23,6 @@ class ToCSV(BaseIO): - fname = "__test__.csv" params = ["wide", "long", "mixed"] param_names = ["kind"] @@ -56,7 +55,6 @@ def time_frame(self, kind): class ToCSVMultiIndexUnusedLevels(BaseIO): - fname = "__test__.csv" def setup(self): @@ -76,7 +74,6 @@ def time_single_index_frame(self): class ToCSVDatetime(BaseIO): - fname = "__test__.csv" def setup(self): @@ -88,7 +85,6 @@ def time_frame_date_formatting(self): class ToCSVDatetimeIndex(BaseIO): - fname = "__test__.csv" def setup(self): @@ -103,7 +99,6 @@ def time_frame_date_no_format_index(self): class ToCSVDatetimeBig(BaseIO): - fname = "__test__.csv" timeout = 1500 params = [1000, 10000, 100000] @@ -125,7 +120,6 @@ def time_frame(self, obs): class ToCSVIndexes(BaseIO): - fname = "__test__.csv" @staticmethod @@ -179,7 +173,6 @@ def data(self, stringio_object): class ReadCSVDInferDatetimeFormat(StringIORewind): - params = ([True, False], ["custom", "iso8601", "ymd"]) param_names = ["infer_datetime_format", "format"] @@ -204,7 +197,6 @@ def time_read_csv(self, infer_datetime_format, format): class ReadCSVConcatDatetime(StringIORewind): - iso8601 = "%Y-%m-%d %H:%M:%S" def setup(self): @@ -222,7 +214,6 @@ def time_read_csv(self): class ReadCSVConcatDatetimeBadDateValue(StringIORewind): - params = (["nan", "0", ""],) param_names = ["bad_date_value"] @@ -240,7 +231,6 @@ def time_read_csv(self, bad_date_value): class ReadCSVSkipRows(BaseIO): - fname = "__test__.csv" params = ([None, 10000], ["c", "python", "pyarrow"]) param_names = ["skiprows", "engine"] @@ -286,7 +276,6 @@ def time_read_uint64_na_values(self): class ReadCSVThousands(BaseIO): - fname = "__test__.csv" params = ([",", "|"], [None, ","], ["c", "python"]) param_names = ["sep", "thousands", "engine"] @@ -321,7 +310,6 @@ def time_comment(self, engine): class ReadCSVFloatPrecision(StringIORewind): - params = ([",", ";"], [".", "_"], [None, "high", "round_trip"]) param_names = ["sep", "decimal", "float_precision"] @@ -373,7 +361,6 @@ def time_read_bytescsv(self, engine): class ReadCSVCategorical(BaseIO): - fname = "__test__.csv" params = ["c", "python"] param_names = ["engine"] @@ -450,7 +437,6 @@ def time_read_csv_cached(self, do_cache, engine): class ReadCSVMemoryGrowth(BaseIO): - chunksize = 20 num_rows = 1000 fname = "__test__.csv" @@ -496,7 +482,6 @@ def time_read_special_date(self, value, engine): class ReadCSVMemMapUTF8: - fname = "__test__.csv" number = 5 diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index 3cc443f6cfbed..093a35a20dc5a 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -32,7 +32,6 @@ def _generate_dataframe(): class WriteExcel: - params = ["openpyxl", "xlsxwriter"] param_names = ["engine"] @@ -65,7 +64,6 @@ def time_write_excel_style(self, engine): class ReadExcel: - params = ["openpyxl", "odf"] param_names = ["engine"] fname_excel = "spreadsheet.xlsx" diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py index e44a59114b30d..f3e417e717609 100644 --- a/asv_bench/benchmarks/io/hdf.py +++ b/asv_bench/benchmarks/io/hdf.py @@ -112,7 +112,6 @@ def time_store_info(self): class HDF(BaseIO): - params = ["table", "fixed"] param_names = ["format"] diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py index 39f234c6fa816..9eaffddd8b87f 100644 --- a/asv_bench/benchmarks/io/json.py +++ b/asv_bench/benchmarks/io/json.py @@ -18,7 +18,6 @@ class ReadJSON(BaseIO): - fname = "__test__.json" params = (["split", "index", "records"], ["int", "datetime"]) param_names = ["orient", "index"] @@ -41,7 +40,6 @@ def time_read_json(self, orient, index): class ReadJSONLines(BaseIO): - fname = "__test_lines__.json" params = ["int", "datetime"] param_names = ["index"] @@ -100,7 +98,6 @@ def time_normalize_json(self, orient, frame): class ToJSON(BaseIO): - fname = "__test__.json" params = [ ["split", "columns", "index", "values", "records"], @@ -212,7 +209,6 @@ def time_iso_format(self, orient): class ToJSONLines(BaseIO): - fname = "__test__.json" def setup(self): diff --git a/asv_bench/benchmarks/io/parsers.py b/asv_bench/benchmarks/io/parsers.py index 5390056ba36f2..1078837a8e395 100644 --- a/asv_bench/benchmarks/io/parsers.py +++ b/asv_bench/benchmarks/io/parsers.py @@ -11,7 +11,6 @@ class DoesStringLookLikeDatetime: - params = (["2Q2005", "0.0", "10000"],) param_names = ["value"] @@ -24,7 +23,6 @@ def time_check_datetimes(self, value): class ConcatDateCols: - params = ([1234567890, "AAAA"], [1, 2]) param_names = ["value", "dim"] diff --git a/asv_bench/benchmarks/io/sql.py b/asv_bench/benchmarks/io/sql.py index c1f378e8075e9..6f893ee72d918 100644 --- a/asv_bench/benchmarks/io/sql.py +++ b/asv_bench/benchmarks/io/sql.py @@ -14,7 +14,6 @@ class SQL: - params = ["sqlalchemy", "sqlite"] param_names = ["connection"] @@ -52,7 +51,6 @@ def time_read_sql_query(self, connection): class WriteSQLDtypes: - params = ( ["sqlalchemy", "sqlite"], [ @@ -136,7 +134,6 @@ def time_read_sql_table_parse_dates(self): class ReadSQLTableDtypes: - params = [ "float", "float_with_nan", diff --git a/asv_bench/benchmarks/io/stata.py b/asv_bench/benchmarks/io/stata.py index 1ff929d6dbdea..300b9c778f1f8 100644 --- a/asv_bench/benchmarks/io/stata.py +++ b/asv_bench/benchmarks/io/stata.py @@ -13,7 +13,6 @@ class Stata(BaseIO): - params = ["tc", "td", "tm", "tw", "th", "tq", "ty"] param_names = ["convert_dates"] diff --git a/asv_bench/benchmarks/io/style.py b/asv_bench/benchmarks/io/style.py index 1ebdb08e8c727..e7d274b8bd631 100644 --- a/asv_bench/benchmarks/io/style.py +++ b/asv_bench/benchmarks/io/style.py @@ -7,7 +7,6 @@ class Render: - params = [[12, 24, 36], [12, 120]] param_names = ["cols", "rows"] diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py index fdbf325dcf997..eaa51730477cc 100644 --- a/asv_bench/benchmarks/join_merge.py +++ b/asv_bench/benchmarks/join_merge.py @@ -23,7 +23,6 @@ class Concat: - params = [0, 1] param_names = ["axis"] @@ -56,7 +55,6 @@ def time_concat_mixed_ndims(self, axis): class ConcatDataFrames: - params = ([0, 1], [True, False]) param_names = ["axis", "ignore_index"] @@ -74,7 +72,6 @@ def time_f_ordered(self, axis, ignore_index): class ConcatIndexDtype: - params = ( ["datetime64[ns]", "int64", "Int64", "string[python]", "string[pyarrow]"], ["monotonic", "non_monotonic", "has_na"], @@ -114,7 +111,6 @@ def time_concat_series(self, dtype, structure, axis, sort): class Join: - params = [True, False] param_names = ["sort"] @@ -223,7 +219,6 @@ def time_join_non_unique_equal(self): class Merge: - params = [True, False] param_names = ["sort"] @@ -274,7 +269,6 @@ def time_merge_dataframes_cross(self, sort): class MergeEA: - params = [ "Int64", "Int32", @@ -306,7 +300,6 @@ def time_merge(self, dtype): class I8Merge: - params = ["inner", "outer", "left", "right"] param_names = ["how"] diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py index de55268e0407b..9c997b5386eaa 100644 --- a/asv_bench/benchmarks/multiindex_object.py +++ b/asv_bench/benchmarks/multiindex_object.py @@ -178,7 +178,6 @@ def time_sortlevel_one(self): class SortValues: - params = ["int64", "Int64"] param_names = ["dtype"] @@ -193,7 +192,6 @@ def time_sort_values(self, dtype): class Values: def setup_cache(self): - level1 = range(1000) level2 = date_range(start="1/1/2012", periods=100) mi = MultiIndex.from_product([level1, level2]) @@ -208,7 +206,6 @@ def time_datetime_level_values_sliced(self, mi): class CategoricalLevel: def setup(self): - self.df = DataFrame( { "a": np.arange(1_000_000, dtype=np.int32), @@ -234,7 +231,6 @@ def time_equals_non_object_index(self): class SetOperations: - params = [ ("monotonic", "non_monotonic"), ("datetime", "int", "string", "ea_int"), @@ -278,7 +274,6 @@ def time_operation(self, index_structure, dtype, method, sort): class Difference: - params = [ ("datetime", "int", "string", "ea_int"), ] diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py index 4f81aee62c202..501fe198d41d8 100644 --- a/asv_bench/benchmarks/period.py +++ b/asv_bench/benchmarks/period.py @@ -15,7 +15,6 @@ class PeriodIndexConstructor: - params = [["D"], [True, False]] param_names = ["freq", "is_offset"] @@ -59,7 +58,6 @@ def time_set_index(self): class Algorithms: - params = ["index", "series"] param_names = ["typ"] diff --git a/asv_bench/benchmarks/reindex.py b/asv_bench/benchmarks/reindex.py index 29d2831be1522..eac4bb38eb18f 100644 --- a/asv_bench/benchmarks/reindex.py +++ b/asv_bench/benchmarks/reindex.py @@ -54,7 +54,6 @@ def time_reindex_multiindex_no_cache_dates(self): class ReindexMethod: - params = [["pad", "backfill"], [date_range, period_range]] param_names = ["method", "constructor"] @@ -68,7 +67,6 @@ def time_reindex_method(self, method, constructor): class Fillna: - params = ["pad", "backfill"] param_names = ["method"] @@ -107,7 +105,6 @@ def time_reindex_level(self): class DropDuplicates: - params = [True, False] param_names = ["inplace"] diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py index 8d4fc0240f2cc..36b5b54e4440b 100644 --- a/asv_bench/benchmarks/replace.py +++ b/asv_bench/benchmarks/replace.py @@ -4,7 +4,6 @@ class FillNa: - params = [True, False] param_names = ["inplace"] @@ -23,7 +22,6 @@ def time_replace(self, inplace): class ReplaceDict: - params = [True, False] param_names = ["inplace"] @@ -55,7 +53,6 @@ def time_replace_list_one_match(self, inplace): class Convert: - params = (["DataFrame", "Series"], ["Timestamp", "Timedelta"]) param_names = ["constructor", "replace_data"] diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py index 66067d25d133b..551af7ccb40bc 100644 --- a/asv_bench/benchmarks/reshape.py +++ b/asv_bench/benchmarks/reshape.py @@ -59,7 +59,6 @@ def time_unstack(self): class ReshapeExtensionDtype: - params = ["datetime64[ns, US/Pacific]", "Period[s]"] param_names = ["dtype"] @@ -95,7 +94,6 @@ def time_transpose(self, dtype): class Unstack: - params = ["int", "category"] def setup(self, dtype): @@ -311,7 +309,6 @@ class Explode: params = [[100, 1000, 10000], [3, 5, 10]] def setup(self, n_rows, max_list_length): - data = [np.arange(np.random.randint(max_list_length)) for _ in range(n_rows)] self.series = pd.Series(data) diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index 7e94763f3f293..bd4da00bfd2ad 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -6,7 +6,6 @@ class Methods: - params = ( ["DataFrame", "Series"], [("rolling", {"window": 10}), ("rolling", {"window": 1000}), ("expanding", {})], @@ -129,7 +128,6 @@ def test_method(self, constructor, dtype, window_kwargs, function, parallel, col class EWMMethods: - params = ( ["DataFrame", "Series"], [ @@ -177,7 +175,6 @@ def setup(self, constructor, window, dtype, method): class Pairwise: - params = ( [({"window": 10}, "rolling"), ({"window": 1000}, "rolling"), ({}, "expanding")], ["corr", "cov"], @@ -251,7 +248,6 @@ def time_rank(self, constructor, window, dtype, percentile, ascending, method): class PeakMemFixedWindowMinMax: - params = ["min", "max"] def setup(self, operation): @@ -287,7 +283,6 @@ def peakmem_rolling(self, constructor, window_size, dtype, method): class Groupby: - params = ( ["sum", "median", "mean", "max", "min", "kurt", "sum"], [ @@ -329,7 +324,6 @@ def time_rolling_multiindex_creation(self): class GroupbyEWM: - params = ["var", "std", "cov", "corr"] param_names = ["method"] @@ -342,7 +336,6 @@ def time_groupby_method(self, method): class GroupbyEWMEngine: - params = ["cython", "numba"] param_names = ["engine"] @@ -359,7 +352,6 @@ def table_method_func(x): class TableMethod: - params = ["single", "table"] param_names = ["method"] diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index a0dd52e9f17e4..06c4589297cda 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -46,7 +46,6 @@ def time_to_frame(self, dtype, name): class NSort: - params = ["first", "last", "all"] param_names = ["keep"] @@ -61,7 +60,6 @@ def time_nsmallest(self, keep): class Dropna: - params = ["int", "datetime"] param_names = ["dtype"] @@ -80,7 +78,6 @@ def time_dropna(self, dtype): class Fillna: - params = [ [ "datetime64[ns]", @@ -123,7 +120,6 @@ def time_fillna(self, dtype, method): class SearchSorted: - goal_time = 0.2 params = [ "int8", @@ -152,7 +148,6 @@ def time_searchsorted(self, dtype): class Map: - params = (["dict", "Series", "lambda"], ["object", "category", "int"]) param_names = "mapper" @@ -199,7 +194,6 @@ def time_clip(self): class ValueCounts: - params = [[10**3, 10**4, 10**5], ["int", "uint", "float", "object"]] param_names = ["N", "dtype"] @@ -211,7 +205,6 @@ def time_value_counts(self, N, dtype): class ValueCountsEA: - params = [[10**3, 10**4, 10**5], [True, False]] param_names = ["N", "dropna"] @@ -224,7 +217,6 @@ def time_value_counts(self, N, dropna): class ValueCountsObjectDropNAFalse: - params = [10**3, 10**4, 10**5] param_names = ["N"] @@ -236,7 +228,6 @@ def time_value_counts(self, N): class Mode: - params = [[10**3, 10**4, 10**5], ["int", "uint", "float", "object"]] param_names = ["N", "dtype"] @@ -248,7 +239,6 @@ def time_mode(self, N, dtype): class ModeObjectDropNAFalse: - params = [10**3, 10**4, 10**5] param_names = ["N"] @@ -277,7 +267,6 @@ def time_series_datetimeindex_repr(self): class All: - params = [[10**3, 10**6], ["fast", "slow"], ["bool", "boolean"]] param_names = ["N", "case", "dtype"] @@ -290,7 +279,6 @@ def time_all(self, N, case, dtype): class Any: - params = [[10**3, 10**6], ["fast", "slow"], ["bool", "boolean"]] param_names = ["N", "case", "dtype"] @@ -303,7 +291,6 @@ def time_any(self, N, case, dtype): class NanOps: - params = [ [ "var", @@ -336,7 +323,6 @@ def time_func(self, func, N, dtype): class Rank: - param_names = ["dtype"] params = [ ["int", "uint", "float", "object"], @@ -350,7 +336,6 @@ def time_rank(self, dtype): class Iter: - param_names = ["dtype"] params = [ "bool", diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py index 10390cb4493cd..c8a9a9e6e9176 100644 --- a/asv_bench/benchmarks/sparse.py +++ b/asv_bench/benchmarks/sparse.py @@ -35,7 +35,6 @@ def time_series_to_frame(self): class SparseArrayConstructor: - params = ([0.1, 0.01], [0, np.nan], [np.int64, np.float64, object]) param_names = ["dense_proportion", "fill_value", "dtype"] @@ -106,7 +105,6 @@ def time_to_coo(self): class Arithmetic: - params = ([0.1, 0.01], [0, np.nan]) param_names = ["dense_proportion", "fill_value"] @@ -131,7 +129,6 @@ def time_divide(self, dense_proportion, fill_value): class ArithmeticBlock: - params = [np.nan, 0] param_names = ["fill_value"] @@ -167,7 +164,6 @@ def time_division(self, fill_value): class MinMax: - params = (["min", "max"], [0.0, np.nan]) param_names = ["func", "fill_value"] @@ -181,7 +177,6 @@ def time_min_max(self, func, fill_value): class Take: - params = ([np.array([0]), np.arange(100_000), np.full(100_000, -1)], [True, False]) param_names = ["indices", "allow_fill"] @@ -210,7 +205,6 @@ def time_slice(self): class GetItemMask: - params = [True, False, np.nan] param_names = ["fill_value"] diff --git a/asv_bench/benchmarks/stat_ops.py b/asv_bench/benchmarks/stat_ops.py index 09244b31fbba7..65bcb3d55c4f1 100644 --- a/asv_bench/benchmarks/stat_ops.py +++ b/asv_bench/benchmarks/stat_ops.py @@ -6,7 +6,6 @@ class FrameOps: - params = [ops, ["float", "int", "Int64"], [0, 1]] param_names = ["op", "dtype", "axis"] @@ -22,7 +21,6 @@ def time_op(self, op, dtype, axis): class FrameMultiIndexOps: - params = [ops] param_names = ["op"] @@ -42,7 +40,6 @@ def time_op(self, op): class SeriesOps: - params = [ops, ["float", "int"]] param_names = ["op", "dtype"] @@ -55,7 +52,6 @@ def time_op(self, op, dtype): class SeriesMultiIndexOps: - params = [ops] param_names = ["op"] @@ -75,7 +71,6 @@ def time_op(self, op): class Rank: - params = [["DataFrame", "Series"], [True, False]] param_names = ["constructor", "pct"] @@ -91,7 +86,6 @@ def time_average_old(self, constructor, pct): class Correlation: - params = [["spearman", "kendall", "pearson"]] param_names = ["method"] @@ -126,7 +120,6 @@ def time_corrwith_rows(self, method): class Covariance: - params = [] param_names = [] diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py index eec722c9f167b..59b7cd2accf88 100644 --- a/asv_bench/benchmarks/strings.py +++ b/asv_bench/benchmarks/strings.py @@ -25,7 +25,6 @@ def setup(self, dtype): class Construction: - params = ["str", "string"] param_names = ["dtype"] @@ -177,7 +176,6 @@ def time_isupper(self, dtype): class Repeat: - params = ["int", "array"] param_names = ["repeats"] @@ -192,7 +190,6 @@ def time_repeat(self, repeats): class Cat: - params = ([0, 3], [None, ","], [None, "-"], [0.0, 0.001, 0.15]) param_names = ["other_cols", "sep", "na_rep", "na_frac"] @@ -217,7 +214,6 @@ def time_cat(self, other_cols, sep, na_rep, na_frac): class Contains(Dtypes): - params = (Dtypes.params, [True, False]) param_names = ["dtype", "regex"] @@ -229,7 +225,6 @@ def time_contains(self, dtype, regex): class Split(Dtypes): - params = (Dtypes.params, [True, False]) param_names = ["dtype", "expand"] @@ -245,7 +240,6 @@ def time_rsplit(self, dtype, expand): class Extract(Dtypes): - params = (Dtypes.params, [True, False]) param_names = ["dtype", "expand"] diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index 9373edadb8e90..1253fefde2d5f 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -20,7 +20,6 @@ class DatetimeIndex: - params = ["dst", "repeated", "tz_aware", "tz_local", "tz_naive"] param_names = ["index_type"] @@ -68,7 +67,6 @@ def time_is_dates_only(self, index_type): class TzLocalize: - params = [None, "US/Eastern", "UTC", dateutil.tz.tzutc()] param_names = "tz" @@ -88,7 +86,6 @@ def time_infer_dst(self, tz): class ResetIndex: - params = [None, "US/Eastern"] param_names = "tz" @@ -126,7 +123,6 @@ def time_convert(self): class Iteration: - params = [date_range, period_range, timedelta_range] param_names = ["time_index"] @@ -149,7 +145,6 @@ def time_iter_preexit(self, time_index): class ResampleDataFrame: - params = ["max", "mean", "min"] param_names = ["method"] @@ -163,7 +158,6 @@ def time_method(self, method): class ResampleSeries: - params = (["period", "datetime"], ["5min", "1D"], ["mean", "ohlc"]) param_names = ["index", "freq", "method"] @@ -193,7 +187,6 @@ def time_resample(self): class AsOf: - params = ["DataFrame", "Series"] param_names = ["constructor"] @@ -242,7 +235,6 @@ def time_asof_nan_single(self, constructor): class SortIndex: - params = [True, False] param_names = ["monotonic"] @@ -273,7 +265,6 @@ def time_lookup_and_cleanup(self): class DatetimeAccessor: - params = [None, "US/Eastern", "UTC", dateutil.tz.tzutc()] param_names = "tz" diff --git a/asv_bench/benchmarks/tslibs/offsets.py b/asv_bench/benchmarks/tslibs/offsets.py index a3fdaf8afdda1..1f48ec504acf1 100644 --- a/asv_bench/benchmarks/tslibs/offsets.py +++ b/asv_bench/benchmarks/tslibs/offsets.py @@ -45,7 +45,6 @@ class OnOffset: - params = offset_objs param_names = ["offset"] @@ -63,7 +62,6 @@ def time_on_offset(self, offset): class OffestDatetimeArithmetic: - params = offset_objs param_names = ["offset"] diff --git a/asv_bench/benchmarks/tslibs/period.py b/asv_bench/benchmarks/tslibs/period.py index af10102749627..2d192889c39f3 100644 --- a/asv_bench/benchmarks/tslibs/period.py +++ b/asv_bench/benchmarks/tslibs/period.py @@ -25,7 +25,6 @@ class PeriodProperties: - params = ( ["M", "min"], [ @@ -56,7 +55,6 @@ def time_property(self, freq, attr): class PeriodUnaryMethods: - params = ["M", "min"] param_names = ["freq"] diff --git a/environment.yml b/environment.yml index f0678abbfe211..aad0c1ca8588f 100644 --- a/environment.yml +++ b/environment.yml @@ -75,7 +75,7 @@ dependencies: - cxx-compiler # code checks - - black=22.10.0 + - black=23.1.0 - cpplint - flake8=6.0.0 - isort>=5.2.1 # check that imports are in the right order diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 4170bb7706bdd..5e7cb9f9091ad 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -172,7 +172,6 @@ def _set_option(*args, **kwargs) -> None: def _describe_option(pat: str = "", _print_desc: bool = True) -> str | None: - keys = _select_options(pat) if len(keys) == 0: raise OptionError("No such keys(s)") @@ -186,7 +185,6 @@ def _describe_option(pat: str = "", _print_desc: bool = True) -> str | None: def _reset_option(pat: str, silent: bool = False) -> None: - keys = _select_options(pat) if len(keys) == 0: @@ -842,13 +840,11 @@ def inner(x) -> None: def is_one_of_factory(legal_values) -> Callable[[Any], None]: - callables = [c for c in legal_values if callable(c)] legal_values = [c for c in legal_values if not callable(c)] def inner(x) -> None: if x not in legal_values: - if not any(c(x) for c in callables): uvals = [str(lval) for lval in legal_values] pp_values = "|".join(uvals) diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi index e9b78ad53380f..2bc6d74fe6aee 100644 --- a/pandas/_libs/hashtable.pyi +++ b/pandas/_libs/hashtable.pyi @@ -185,10 +185,13 @@ class HashTable: self, values: np.ndarray, # np.ndarray[subclass-specific] return_inverse: bool = ..., - ) -> tuple[ - np.ndarray, # np.ndarray[subclass-specific] - npt.NDArray[np.intp], - ] | np.ndarray: ... # np.ndarray[subclass-specific] + ) -> ( + tuple[ + np.ndarray, # np.ndarray[subclass-specific] + npt.NDArray[np.intp], + ] + | np.ndarray + ): ... # np.ndarray[subclass-specific] def factorize( self, values: np.ndarray, # np.ndarray[subclass-specific] diff --git a/pandas/_libs/properties.pyi b/pandas/_libs/properties.pyi index 595e3bd706f1d..aaa44a0cf47bf 100644 --- a/pandas/_libs/properties.pyi +++ b/pandas/_libs/properties.pyi @@ -16,7 +16,6 @@ from pandas._typing import ( cache_readonly = property class AxisProperty: - axis: int def __init__(self, axis: int = ..., doc: str = ...) -> None: ... @overload diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 818ea1e6ef9d0..98343148bdad1 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -170,7 +170,6 @@ def _check_isinstance(left, right, cls): def assert_dict_equal(left, right, compare_keys: bool = True) -> None: - _check_isinstance(left, right, dict) _testing.assert_dict_equal(left, right, compare_keys=compare_keys) @@ -315,7 +314,6 @@ def _get_ilevel_values(index, level): msg = f"{obj} values are different ({np.round(diff, 5)} %)" raise_assert_detail(obj, msg, left, right) else: - # if we have "equiv", this becomes True exact_bool = bool(exact) _testing.assert_almost_equal( diff --git a/pandas/_testing/contexts.py b/pandas/_testing/contexts.py index 6a1f5f83b6af2..bf625a086b9ad 100644 --- a/pandas/_testing/contexts.py +++ b/pandas/_testing/contexts.py @@ -203,7 +203,6 @@ def use_numexpr(use, min_elements=None) -> Generator[None, None, None]: def raises_chained_assignment_error(): - if PYPY: from contextlib import nullcontext diff --git a/pandas/compat/pickle_compat.py b/pandas/compat/pickle_compat.py index bfee616d52aac..9800c960f031b 100644 --- a/pandas/compat/pickle_compat.py +++ b/pandas/compat/pickle_compat.py @@ -32,7 +32,6 @@ def load_reduce(self): stack[-1] = func(*args) return except TypeError as err: - # If we have a deprecated function, # try to replace and try again. diff --git a/pandas/conftest.py b/pandas/conftest.py index 2c410bb98b506..50951532364d1 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -168,7 +168,7 @@ def pytest_collection_modifyitems(items, config) -> None: if "/frame/" in item.nodeid: item.add_marker(pytest.mark.arraymanager) - for (mark, kwd, skip_if_found, arg_name) in marks: + for mark, kwd, skip_if_found, arg_name in marks: if kwd in item.keywords: # If we're skipping, no need to actually add the marker or look for # other markers diff --git a/pandas/core/_numba/kernels/min_max_.py b/pandas/core/_numba/kernels/min_max_.py index 4f237fc1a0559..acba66a6e4f63 100644 --- a/pandas/core/_numba/kernels/min_max_.py +++ b/pandas/core/_numba/kernels/min_max_.py @@ -28,7 +28,6 @@ def sliding_min_max( Q: list = [] W: list = [] for i in range(N): - curr_win_size = end[i] - start[i] if i == 0: st = start[i] diff --git a/pandas/core/_numba/kernels/var_.py b/pandas/core/_numba/kernels/var_.py index b1c72832d249b..d3243f4928dca 100644 --- a/pandas/core/_numba/kernels/var_.py +++ b/pandas/core/_numba/kernels/var_.py @@ -25,7 +25,6 @@ def add_var( prev_value: float, ) -> tuple[int, float, float, float, int, float]: if not np.isnan(val): - if val == prev_value: num_consecutive_same_value += 1 else: @@ -92,7 +91,6 @@ def sliding_var( s = start[i] e = end[i] if i == 0 or not is_monotonic_increasing_bounds: - prev_value = values[s] num_consecutive_same_value = 0 diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index 64bb9407ea83b..58da2cd994777 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -117,7 +117,6 @@ def f(self, *args, **kwargs): return f for name in accessors: - if ( not raise_on_missing and getattr(delegate, accessor_mapping(name), None) is None diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 636273724b57c..1de7643cc96fc 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -90,7 +90,6 @@ from pandas.core.indexers import validate_indices if TYPE_CHECKING: - from pandas._typing import ( NumpySorter, NumpyValueArrayLike, @@ -295,7 +294,6 @@ def _check_object_for_strings(values: np.ndarray) -> str: """ ndtype = values.dtype.name if ndtype == "object": - # it's cheaper to use a String Hash Table than Object; we infer # including nulls because that is the only difference between # StringHashTable and ObjectHashtable @@ -874,9 +872,7 @@ def value_counts( counts = np.array([len(ii)]) else: - if is_extension_array_dtype(values): - # handle Categorical and sparse, result = Series(values)._values.value_counts(dropna=dropna) result.name = name @@ -1226,7 +1222,6 @@ class SelectNSeries(SelectN): """ def compute(self, method: str) -> Series: - from pandas.core.reshape.concat import concat n = self.n @@ -1700,6 +1695,7 @@ def diff(arr, n: int, axis: AxisInt = 0): # -------------------------------------------------------------------- # Helper functions + # Note: safe_sort is in algorithms.py instead of sorting.py because it is # low-dependency, is used in this module, and used private methods from # this module. diff --git a/pandas/core/apply.py b/pandas/core/apply.py index b10f5b5cf3aa7..2601271e27a69 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -329,7 +329,6 @@ def agg_list_like(self) -> DataFrame | Series: with context_manager: # degenerate case if selected_obj.ndim == 1: - for a in arg: colg = obj._gotitem(selected_obj.name, ndim=1, subset=selected_obj) if isinstance(colg, (ABCSeries, ABCDataFrame)): @@ -793,7 +792,6 @@ def apply_broadcast(self, target: DataFrame) -> DataFrame: if ares > 1: raise ValueError("too many dims to broadcast") if ares == 1: - # must match return dim if result_compare != len(res): raise ValueError("cannot broadcast result") @@ -946,7 +944,7 @@ def series_generator(self): yield obj._ixs(i, axis=0) else: - for (arr, name) in zip(values, self.index): + for arr, name in zip(values, self.index): # GH#35462 re-pin mgr in case setitem changed it ser._mgr = mgr mgr.set_values(arr) @@ -1199,7 +1197,6 @@ def reconstruct_func( if not relabeling: if isinstance(func, list) and len(func) > len(set(func)): - # GH 28426 will raise error if duplicated function names are used and # there is no reassigned name raise SpecificationError( diff --git a/pandas/core/array_algos/take.py b/pandas/core/array_algos/take.py index 00b1c898942b3..7282b0729f73f 100644 --- a/pandas/core/array_algos/take.py +++ b/pandas/core/array_algos/take.py @@ -62,7 +62,6 @@ def take_nd( fill_value=lib.no_default, allow_fill: bool = True, ) -> ArrayLike: - """ Specialized Cython take which sets NaN values in one pass @@ -125,7 +124,6 @@ def _take_nd_ndarray( fill_value, allow_fill: bool, ) -> np.ndarray: - if indexer is None: indexer = np.arange(arr.shape[axis], dtype=np.intp) dtype, fill_value = arr.dtype, arr.dtype.type() diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 0a4a550f5d8bc..5d1bb04cfacbd 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -239,7 +239,6 @@ def searchsorted( @doc(ExtensionArray.shift) def shift(self, periods: int = 1, fill_value=None, axis: AxisInt = 0): - fill_value = self._validate_scalar(fill_value) new_values = shift(self._ndarray, periods, axis, fill_value) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 3a3f0b8ce61be..16cfb6d7c396b 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -594,7 +594,6 @@ def fillna( method: FillnaOptions | None = None, limit: int | None = None, ) -> ArrowExtensionArrayT: - value, method = validate_fillna_kwargs(value, method) if limit is not None: diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index c261a41e1e77e..d6d5957cad8f9 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -89,7 +89,6 @@ ) if TYPE_CHECKING: - from pandas._typing import ( NumpySorter, NumpyValueArrayLike, diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 543e39d25f030..7fd6059697fc5 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -347,7 +347,6 @@ def _coerce_to_array( return coerce_to_array(value, copy=copy) def _logical_method(self, other, op): - assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"} other_is_scalar = lib.is_scalar(other) mask = None diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index dc3d6d2decc07..6b6037ce45daa 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -365,7 +365,6 @@ def __init__( fastpath: bool = False, copy: bool = True, ) -> None: - dtype = CategoricalDtype._from_values_or_dtype( values, categories, ordered, dtype ) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 437195bbcf7e9..b8fca76115446 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -148,7 +148,6 @@ from pandas.tseries import frequencies if TYPE_CHECKING: - from pandas.core.arrays import ( DatetimeArray, PeriodArray, @@ -1363,7 +1362,6 @@ def __radd__(self, other): @unpack_zerodim_and_defer("__sub__") def __sub__(self, other): - other_dtype = getattr(other, "dtype", None) other = ensure_wrapped_if_datetimelike(other) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index ab9e12dc5de81..1624870705b8f 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -87,7 +87,6 @@ ) if TYPE_CHECKING: - from pandas import DataFrame from pandas.core.arrays import PeriodArray @@ -387,7 +386,6 @@ def _generate_range( # type: ignore[override] *, unit: str | None = None, ) -> DatetimeArray: - periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): raise ValueError("Must provide freq argument if no data is supplied") @@ -455,7 +453,6 @@ def _generate_range( # type: ignore[override] endpoint_tz = start.tz if start is not None else end.tz if tz is not None and endpoint_tz is None: - if not timezones.is_utc(tz): # short-circuit tz_localize_to_utc which would make # an unnecessary copy with UTC but be a no-op. @@ -721,7 +718,6 @@ def _format_native_types( # Comparison Methods def _has_same_tz(self, other) -> bool: - # vzone shouldn't be None if value is non-datetime like if isinstance(other, np.datetime64): # convert to Timestamp as np.datetime64 doesn't have tz attr @@ -757,7 +753,6 @@ def _assert_tzawareness_compat(self, other) -> None: # Arithmetic Methods def _add_offset(self, offset) -> DatetimeArray: - assert not isinstance(offset, Tick) if self.tz is not None: @@ -2448,7 +2443,6 @@ def _infer_tz_from_endpoints( def _maybe_normalize_endpoints( start: Timestamp | None, end: Timestamp | None, normalize: bool ): - if normalize: if start is not None: start = start.normalize() diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 482909d195bd0..2d63af5dc8624 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -235,7 +235,6 @@ def __new__( copy: bool = False, verify_integrity: bool = True, ): - data = extract_array(data, extract_numpy=True) if isinstance(data, cls): @@ -244,7 +243,6 @@ def __new__( closed = closed or data.closed dtype = IntervalDtype(left.dtype, closed=closed) else: - # don't allow scalars if is_scalar(data): msg = ( @@ -1184,7 +1182,6 @@ def _validate_scalar(self, value): return left, right def _validate_setitem_value(self, value): - if is_valid_na_for_dtype(value, self.left.dtype): # na value: need special casing to set directly on numpy arrays value = self.left._na_value @@ -1231,7 +1228,6 @@ def value_counts(self, dropna: bool = True) -> Series: # Rendering Methods def _format_data(self) -> str: - # TODO: integrate with categorical and make generic # name argument is unused here; just for compat with base / categorical n = len(self) @@ -1249,7 +1245,6 @@ def _format_data(self) -> str: last = formatter(self[-1]) summary = f"[{first}, {last}]" else: - if n > max_seq_items: n = min(max_seq_items // 2, 10) head = [formatter(x) for x in self[:n]] diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index e9ffb9af98323..9b9cb3e29810d 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -878,7 +878,6 @@ def take( # error: Return type "BooleanArray" of "isin" incompatible with return type # "ndarray" in supertype "ExtensionArray" def isin(self, values) -> BooleanArray: # type: ignore[override] - from pandas.core.arrays import BooleanArray # algorithms.isin will eventually convert values to an ndarray, so no extra diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index da1c94101b785..f9404fbf57382 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -80,7 +80,6 @@ import pandas.core.common as com if TYPE_CHECKING: - from pandas._typing import ( NumpySorter, NumpyValueArrayLike, diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 7469e92436e1a..616ad53ddd0a9 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -375,7 +375,6 @@ def __init__( dtype: Dtype | None = None, copy: bool = False, ) -> None: - if fill_value is None and isinstance(dtype, SparseDtype): fill_value = dtype.fill_value @@ -770,7 +769,6 @@ def fillna( return self._simple_new(new_values, self._sparse_index, new_dtype) def shift(self: SparseArrayT, periods: int = 1, fill_value=None) -> SparseArrayT: - if not len(self) or periods == 0: return self.copy() @@ -909,7 +907,6 @@ def __getitem__( self: SparseArrayT, key: PositionalIndexer | tuple[int | ellipsis, ...], ) -> SparseArrayT | Any: - if isinstance(key, tuple): key = unpack_tuple_and_ellipses(key) if key is Ellipsis: @@ -929,7 +926,6 @@ def __getitem__( # _NestedSequence[Union[bool, int]]], ...]]" data_slice = self.to_dense()[key] # type: ignore[index] elif isinstance(key, slice): - # Avoid densifying when handling contiguous slices if key.step is None or key.step == 1: start = 0 if key.start is None else key.start @@ -1126,7 +1122,6 @@ def searchsorted( side: Literal["left", "right"] = "left", sorter: NumpySorter = None, ) -> npt.NDArray[np.intp] | np.intp: - msg = "searchsorted requires high memory usage." warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level()) if not is_scalar(v): @@ -1594,7 +1589,6 @@ def _min_max(self, kind: Literal["min", "max"], skipna: bool) -> Scalar: return na_value_for_dtype(self.dtype.subtype, compat=False) def _argmin_argmax(self, kind: Literal["argmin", "argmax"]) -> int: - values = self._sparse_values index = self._sparse_index.indices mask = np.asarray(isna(values)) diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 80d95d3358c4a..c7a44d3606fa6 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -82,7 +82,6 @@ class SparseDtype(ExtensionDtype): _metadata = ("_dtype", "_fill_value", "_is_na_fill_value") def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None: - if isinstance(dtype, type(self)): if fill_value is None: fill_value = dtype.fill_value diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index bef1ae0c04c4e..2248264cab42f 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -197,7 +197,6 @@ def __from_arrow__( return ArrowStringArray(array) else: - import pyarrow if isinstance(array, pyarrow.Array): diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 42a6bdd1aa811..e7a0ddba1fccc 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -267,7 +267,6 @@ def _from_sequence_not_strict( def _generate_range( # type: ignore[override] cls, start, end, periods, freq, closed=None, *, unit: str | None = None ): - periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): raise ValueError("Must provide freq argument if no data is supplied") diff --git a/pandas/core/base.py b/pandas/core/base.py index 8a1a2b8b99aa5..c9cfb31ac51e1 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -70,7 +70,6 @@ ) if TYPE_CHECKING: - from pandas._typing import ( DropKeep, NumpySorter, @@ -1159,7 +1158,6 @@ def factorize( sort: bool = False, use_na_sentinel: bool = True, ) -> tuple[npt.NDArray[np.intp], Index]: - codes, uniques = algorithms.factorize( self._values, sort=sort, use_na_sentinel=use_na_sentinel ) @@ -1307,7 +1305,6 @@ def searchsorted( side: Literal["left", "right"] = "left", sorter: NumpySorter = None, ) -> npt.NDArray[np.intp] | np.intp: - if isinstance(value, ABCDataFrame): msg = ( "Value must be 1-D array-like or scalar, " diff --git a/pandas/core/common.py b/pandas/core/common.py index 6713ccd417dd4..073af11b719cc 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -227,7 +227,6 @@ def asarray_tuplesafe(values: Iterable, dtype: NpDtype | None = ...) -> ArrayLik def asarray_tuplesafe(values: Iterable, dtype: NpDtype | None = None) -> ArrayLike: - if not (isinstance(values, (list, tuple)) or hasattr(values, "__array__")): values = list(values) elif isinstance(values, ABCIndex): diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 2e7a0f842ee6d..fff605eb7cf59 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -38,7 +38,6 @@ def _align_core_single_unary_op( term, ) -> tuple[partial | type[NDFrame], dict[str, Index] | None]: - typ: partial | type[NDFrame] axes: dict[str, Index] | None = None diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 0326760a1ff24..d19730a321b36 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -150,7 +150,6 @@ def _convert_expression(expr) -> str: def _check_for_locals(expr: str, stack_level: int, parser: str): - at_top_of_stack = stack_level == 0 not_pandas_parser = parser != "pandas" diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 5118b5d0478e8..75e8b30d2e1f5 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -430,7 +430,6 @@ def _rewrite_membership_op(self, node, left, right): # must be two terms and the comparison operator must be ==/!=/in/not in if is_term(left) and is_term(right) and op_type in self.rewrite_map: - left_list, right_list = map(_is_list, (left, right)) left_str, right_str = map(_is_str, (left, right)) @@ -656,7 +655,6 @@ def visit_Attribute(self, node, **kwargs): raise ValueError(f"Invalid Attribute context {type(ctx).__name__}") def visit_Call(self, node, side=None, **kwargs): - if isinstance(node.func, ast.Attribute) and node.func.attr != "__call__": res = self.visit_Attribute(node.func) elif not isinstance(node.func, ast.Name): @@ -681,7 +679,6 @@ def visit_Call(self, node, side=None, **kwargs): res = res.value if isinstance(res, FuncNode): - new_args = [self.visit(arg) for arg in node.args] if node.keywords: @@ -692,7 +689,6 @@ def visit_Call(self, node, side=None, **kwargs): return res(*new_args) else: - new_args = [self.visit(arg)(self.env) for arg in node.args] for key in node.keywords: diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 8689d9dff5330..2b34258982ab1 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -73,7 +73,6 @@ def _evaluate_standard(op, op_str, a, b): def _can_use_numexpr(op, op_str, a, b, dtype_check) -> bool: """return a boolean if we WILL be using numexpr""" if op_str is not None: - # required min elements (otherwise we are adding overhead) if a.size > _MIN_ELEMENTS: # check for dtype compatibility @@ -177,7 +176,6 @@ def _where_numexpr(cond, a, b): result = None if _can_use_numexpr(None, "where", a, b, "where"): - result = ne.evaluate( "where(cond_value, a_value, b_value)", local_dict={"cond_value": cond, "a_value": a, "b_value": b}, diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index ba3ff2e137857..5c8602c0291da 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -93,7 +93,6 @@ def _resolve_name(self): class BinOp(ops.BinOp): - _max_selectors = 31 op: str @@ -283,7 +282,6 @@ def format(self): return [self.filter] def evaluate(self): - if not self.is_valid: raise ValueError(f"query term is not valid [{self}]") @@ -291,10 +289,8 @@ def evaluate(self): values = list(rhs) if self.is_in_table: - # if too many values to create the expression, use a filter instead if self.op in ["==", "!="] and len(values) > self._max_selectors: - filter_op = self.generate_filter_op() self.filter = (self.lhs, filter_op, Index(values)) @@ -303,7 +299,6 @@ def evaluate(self): # equality conditions if self.op in ["==", "!="]: - filter_op = self.generate_filter_op() self.filter = (self.lhs, filter_op, Index(values)) @@ -347,7 +342,6 @@ def format(self): return self.condition def evaluate(self): - if not self.is_valid: raise ValueError(f"query term is not valid [{self}]") @@ -360,7 +354,6 @@ def evaluate(self): # equality conditions if self.op in ["==", "!="]: - # too many values to create the expression? if len(values) <= self._max_selectors: vs = [self.generate(v) for v in values] @@ -383,7 +376,6 @@ def evaluate(self): class UnaryOp(ops.UnaryOp): def prune(self, klass): - if self.op != "~": raise NotImplementedError("UnaryOp only support invert type ops") @@ -471,7 +463,6 @@ def visit_Attribute(self, node, **kwargs): try: return self.term_type(getattr(resolved, attr), self.env) except AttributeError: - # something like datetime.datetime where scope is overridden if isinstance(value, ast.Name) and value.id == attr: return resolved @@ -551,7 +542,6 @@ def __init__( encoding=None, scope_level: int = 0, ) -> None: - where = _validate_where(where) self.encoding = encoding diff --git a/pandas/core/dtypes/astype.py b/pandas/core/dtypes/astype.py index 70d3dc573dbe0..7ae5993c857e2 100644 --- a/pandas/core/dtypes/astype.py +++ b/pandas/core/dtypes/astype.py @@ -105,7 +105,6 @@ def _astype_nansafe( return _astype_float_to_int_nansafe(arr, dtype, copy) elif is_object_dtype(arr.dtype): - # if we have a datetime/timedelta array of objects # then coerce to datetime64[ns] and use DatetimeArray.astype diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index cf2e79ead9e15..fff1624648a74 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -99,7 +99,6 @@ ) if TYPE_CHECKING: - from pandas import Index from pandas.core.arrays import ( Categorical, @@ -363,7 +362,6 @@ def trans(x): return result if is_bool_dtype(dtype) or is_integer_dtype(dtype): - if not result.size: # if we don't have any elements, just astype it return trans(result).astype(dtype) @@ -779,7 +777,6 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> tuple[DtypeObj, val = lib.item_from_zerodim(val) elif isinstance(val, str): - # If we create an empty array using a string to infer # the dtype, NumPy will only allocate one character per entry # so this is kind of bad. Alternately we could use np.repeat @@ -1027,7 +1024,6 @@ def convert_dtypes( if ( convert_string or convert_integer or convert_boolean or convert_floating ) and isinstance(input_array, np.ndarray): - if is_object_dtype(input_array.dtype): inferred_dtype = lib.infer_dtype(input_array) else: @@ -1349,7 +1345,6 @@ def common_dtype_categorical_compat( # TODO: more generally, could do `not can_hold_na(dtype)` if isinstance(dtype, np.dtype) and dtype.kind in ["i", "u"]: - for obj in objs: # We don't want to accientally allow e.g. "categorical" str here obj_dtype = getattr(obj, "dtype", None) @@ -1441,7 +1436,6 @@ def find_common_type(types): def construct_2d_arraylike_from_scalar( value: Scalar, length: int, width: int, dtype: np.dtype, copy: bool ) -> np.ndarray: - shape = (length, width) if dtype.kind in ["m", "M"]: @@ -1498,7 +1492,6 @@ def construct_1d_arraylike_from_scalar( subarr = cls._from_sequence(seq, dtype=dtype).repeat(length) else: - if length and is_integer_dtype(dtype) and isna(value): # coerce if we have nan for an integer dtype dtype = np.dtype("float64") diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 3444ad77c2981..0fbb0006d0b32 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -591,7 +591,6 @@ def is_dtype_equal(source, target) -> bool: target = get_dtype(target) return source == target except (TypeError, AttributeError, ImportError): - # invalid comparison # object == category will hit this return False @@ -1573,7 +1572,6 @@ def infer_dtype_from_object(dtype) -> type: if is_extension_array_dtype(dtype): return dtype.type elif isinstance(dtype, str): - # TODO(jreback) # should deprecate these if dtype in ["datetimetz", "datetime64tz"]: diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 80eaf13d9dd06..28bc849088d5f 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -48,6 +48,7 @@ def concat_compat(to_concat, axis: AxisInt = 0, ea_compat_axis: bool = False): ------- a single array, preserving the combined dtypes """ + # filter empty arrays # 1-d dtypes always are included here def is_nonempty(x) -> bool: @@ -102,7 +103,6 @@ def is_nonempty(x) -> bool: # object if we have non-numeric type operands (numpy would otherwise # cast this to float) if len(kinds) != 1: - if not len(kinds - {"i", "u", "f"}) or not len(kinds - {"b", "i", "u"}): # let numpy coerce pass diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 33ff6d1eee686..123e20d6258bf 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -337,7 +337,6 @@ def construct_from_string(cls, string: str_type) -> CategoricalDtype: return cls(ordered=None) def _finalize(self, categories, ordered: Ordered, fastpath: bool = False) -> None: - if ordered is not None: self.validate_ordered(ordered) @@ -534,7 +533,6 @@ def validate_categories(categories, fastpath: bool = False) -> Index: categories = Index._with_infer(categories, tupleize_cols=False) if not fastpath: - if categories.hasnans: raise ValueError("Categorical categories cannot be null") @@ -953,7 +951,6 @@ def __eq__(self, other: Any) -> bool: return other in [self.name, self.name.title()] elif isinstance(other, PeriodDtype): - # For freqs that can be held by a PeriodDtype, this check is # equivalent to (and much faster than) self.freq == other.freq sfreq = self.freq diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 211b67d3590ed..99c0553998d63 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -311,7 +311,6 @@ def _isna_string_dtype(values: np.ndarray, inf_as_na: bool) -> npt.NDArray[np.bo if dtype.kind in ("S", "U"): result = np.zeros(values.shape, dtype=bool) else: - if values.ndim in {1, 2}: result = libmissing.isnaobj(values, inf_as_na=inf_as_na) else: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2bdb43f7dedde..9607d2032b630 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -235,7 +235,6 @@ import pandas.plotting if TYPE_CHECKING: - from pandas.core.groupby.generic import DataFrameGroupBy from pandas.core.interchange.dataframe_protocol import DataFrame as DataFrameXchg from pandas.core.internals import SingleDataManager @@ -646,7 +645,6 @@ def __init__( dtype: Dtype | None = None, copy: bool | None = None, ) -> None: - if dtype is not None: dtype = self._validate_dtype(dtype) @@ -3998,7 +3996,6 @@ def igetitem(obj, i: int): self[col] = igetitem(value, i) else: - ilocs = self.columns.get_indexer_non_unique(key)[0] if (ilocs < 0).any(): # key entries not in self.columns @@ -6721,7 +6718,6 @@ def sort_values( f" != length of by ({len(by)})" ) if len(by) > 1: - keys = [self._get_label_or_level_values(x, axis=axis) for x in by] # need to rewrap columns in Series to apply key function @@ -8951,7 +8947,6 @@ def melt( col_level: Level = None, ignore_index: bool = True, ) -> DataFrame: - return melt( self, id_vars=id_vars, @@ -10607,7 +10602,6 @@ def idxmin( def idxmax( self, axis: Axis = 0, skipna: bool = True, numeric_only: bool = False ) -> Series: - axis = self._get_axis_number(axis) if numeric_only: data = self._get_numeric_data() diff --git a/pandas/core/generic.py b/pandas/core/generic.py index cb321f0584294..78b0a8a7a6ded 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -187,7 +187,6 @@ from pandas.io.formats.printing import pprint_thing if TYPE_CHECKING: - from pandas._libs.tslibs import BaseOffset from pandas.core.frame import DataFrame @@ -1712,7 +1711,6 @@ def _check_label_or_level_ambiguity(self, key: Level, axis: Axis = 0) -> None: and key in self.axes[axis_int].names and any(key in self.axes[ax] for ax in other_axes) ): - # Build an informative and grammatical warning level_article, level_type = ( ("an", "index") if axis_int == 0 else ("a", "column") @@ -1773,7 +1771,6 @@ def _get_label_or_level_values(self, key: Level, axis: AxisInt = 0) -> ArrayLike # Check for duplicates if values.ndim > 1: - if other_axes and isinstance(self._get_axis(other_axes[0]), MultiIndex): multi_message = ( "\n" @@ -4516,7 +4513,6 @@ def drop( inplace: bool_t = False, errors: IgnoreRaise = "raise", ) -> NDFrameT | None: - inplace = validate_bool_kwarg(inplace, "inplace") if labels is not None: @@ -5057,7 +5053,6 @@ def sort_index( ignore_index: bool_t = False, key: IndexKeyFunc = None, ) -> NDFrameT | None: - inplace = validate_bool_kwarg(inplace, "inplace") axis = self._get_axis_number(axis) ascending = validate_ascending(ascending) @@ -6085,7 +6080,6 @@ def _is_mixed_type(self) -> bool_t: def _check_inplace_setting(self, value) -> bool_t: """check whether we allow in-place setting with this type of value""" if self._is_mixed_type and not self._mgr.is_numeric_mixed_type: - # allow an actual np.nan thru if is_float(value) and np.isnan(value): return True @@ -6955,17 +6949,14 @@ def fillna( elif not is_list_like(value): if axis == 1: - result = self.T.fillna(value=value, limit=limit).T new_data = result else: - new_data = self._mgr.fillna( value=value, limit=limit, inplace=inplace, downcast=downcast ) elif isinstance(value, ABCDataFrame) and self.ndim == 2: - new_data = self.where(self.notna(), value)._mgr else: raise ValueError(f"invalid fill value with a {type(value)}") @@ -7282,7 +7273,6 @@ def replace( to_replace, value, inplace=inplace, limit=limit, regex=regex ) else: - # need a non-zero len on all axes if not self.size: if inplace: @@ -7349,7 +7339,6 @@ def replace( regex, value, inplace=inplace, limit=limit, regex=True ) else: - # dest iterable dict-like if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1} # Operate column-wise @@ -8021,7 +8010,6 @@ def _clip_with_scalar(self, lower, upper, inplace: bool_t = False): @final def _clip_with_one_bound(self, threshold, method, axis, inplace): - if axis is not None: axis = self._get_axis_number(axis) @@ -9529,7 +9517,6 @@ def _align_series( # series/series compat, other must always be a Series if not axis: - # equal if self.index.equals(other.index): join_index, lidx, ridx = None, None, None @@ -9550,7 +9537,6 @@ def _align_series( right = other._reindex_indexer(join_index, ridx, copy) else: - # one has > 1 ndim fdata = self._mgr join_index = self.axes[1] @@ -9643,10 +9629,8 @@ def _where( # try to align with other if isinstance(other, NDFrame): - # align with me if other.ndim <= self.ndim: - # CoW: Make sure reference is not kept alive other = self.align( other, @@ -9682,7 +9666,6 @@ def _where( other = extract_array(other, extract_numpy=True) if isinstance(other, (np.ndarray, ExtensionArray)): - if other.shape != self.shape: if self.ndim != 1: # In the ndim == 1 case we may have @@ -9968,7 +9951,6 @@ def mask( axis: Axis | None = None, level: Level = None, ) -> NDFrameT | None: - inplace = validate_bool_kwarg(inplace, "inplace") cond = common.apply_if_callable(cond, self) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 8743f124b033b..eecf292e4c3c8 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -217,7 +217,6 @@ def apply(self, func, *args, **kwargs) -> Series: @doc(_agg_template, examples=_agg_examples_doc, klass="Series") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): - if maybe_use_numba(engine): return self._aggregate_with_numba( func, *args, engine_kwargs=engine_kwargs, **kwargs @@ -291,7 +290,6 @@ def _aggregate_multiple_funcs(self, arg, *args, **kwargs) -> DataFrame: # Combine results using the index, need to adjust index after # if as_index=False (GH#50724) for idx, (name, func) in enumerate(arg): - key = base.OutputKey(label=name, position=idx) results[key] = self.aggregate(func, *args, **kwargs) @@ -681,7 +679,6 @@ def value_counts( lab, lev = algorithms.factorize(val, sort=True) llab = lambda lab, inc: lab[inc] else: - # lab is a Categorical with categories an IntervalIndex cat_ser = cut(Series(val), bins, include_lowest=True) cat_obj = cast("Categorical", cat_ser._values) @@ -1156,7 +1153,6 @@ def unique(self) -> Series: class DataFrameGroupBy(GroupBy[DataFrame]): - _agg_examples_doc = dedent( """ Examples @@ -1252,7 +1248,6 @@ class DataFrameGroupBy(GroupBy[DataFrame]): @doc(_agg_template, examples=_agg_examples_doc, klass="DataFrame") def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs): - if maybe_use_numba(engine): return self._aggregate_with_numba( func, *args, engine_kwargs=engine_kwargs, **kwargs @@ -1278,7 +1273,6 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) result.columns = columns # type: ignore[assignment] if result is None: - # grouper specific aggregations if self.grouper.nkeys > 1: # test_groupby_as_index_series_scalar gets here with 'not self.as_index' @@ -1295,7 +1289,6 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) return result else: - # try to treat as if we are passing a list gba = GroupByApply(self, [func], args=(), kwargs={}) try: @@ -1370,7 +1363,6 @@ def _wrap_applied_output( not_indexed_same: bool = False, is_transform: bool = False, ): - if len(values) == 0: if is_transform: # GH#47787 see test_group_on_empty_multiindex diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 763494666d870..5b380ff1cf7b8 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -910,7 +910,6 @@ def __init__( observed: bool = False, dropna: bool = True, ) -> None: - self._selection = selection assert isinstance(obj, NDFrame), type(obj) @@ -1011,9 +1010,7 @@ def _concat_objects( from pandas.core.reshape.concat import concat if self.group_keys and not is_transform: - if self.as_index: - # possible MI return case group_keys = self.grouper.result_index group_levels = self.grouper.levels @@ -1028,7 +1025,6 @@ def _concat_objects( sort=False, ) else: - # GH5610, returns a MI, with the first level being a # range index keys = list(range(len(values))) @@ -1060,7 +1056,6 @@ def _concat_objects( name = self.obj.name if self.obj.ndim == 1 else self._selection if isinstance(result, Series) and name is not None: - result.name = name return result @@ -1321,7 +1316,6 @@ def _aggregate_with_numba(self, func, *args, engine_kwargs=None, **kwargs): ) ) def apply(self, func, *args, **kwargs) -> NDFrameT: - func = com.is_builtin_func(func) if isinstance(func, str): @@ -1349,7 +1343,6 @@ def f(g): "func must be a callable if args or kwargs are supplied" ) else: - f = func # ignore SettingWithCopy here in case the user mutates @@ -1452,7 +1445,6 @@ def _agg_general( alias: str, npfunc: Callable, ): - result = self._cython_agg_general( how=alias, alt=npfunc, @@ -1551,7 +1543,6 @@ def _cython_transform( @final def _transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): - if maybe_use_numba(engine): return self._transform_with_numba( func, *args, engine_kwargs=engine_kwargs, **kwargs @@ -3094,7 +3085,6 @@ def _nth( # get a new grouper for our dropped obj if self.keys is None and self.level is None: - # we don't have the grouper info available # (e.g. we have selected out # a column that is not in the current object) @@ -3109,7 +3099,6 @@ def _nth( grouper = Index(values, dtype="Int64") else: - # create a grouper with the original parameters, but on dropped # object grouper, _, _ = get_grouper( @@ -4254,7 +4243,6 @@ def get_groupby( grouper: ops.BaseGrouper | None = None, group_keys: bool | lib.NoDefault = True, ) -> GroupBy: - klass: type[GroupBy] if isinstance(obj, Series): from pandas.core.groupby.generic import SeriesGroupBy diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 5f69d297f4426..88780bac06637 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -925,7 +925,6 @@ def get_grouper( # if the actual grouper should be obj[key] def is_in_axis(key) -> bool: - if not _is_label_like(key): if obj.ndim == 1: return False @@ -961,7 +960,6 @@ def is_in_obj(gpr) -> bool: return False for gpr, level in zip(keys, levels): - if is_in_obj(gpr): # df.groupby(df['name']) in_axis = True exclusions.add(gpr.name) diff --git a/pandas/core/groupby/numba_.py b/pandas/core/groupby/numba_.py index acfc690ab3fdb..282cb81e743f9 100644 --- a/pandas/core/groupby/numba_.py +++ b/pandas/core/groupby/numba_.py @@ -105,7 +105,6 @@ def group_agg( num_columns: int, *args: Any, ) -> np.ndarray: - assert len(begin) == len(end) num_groups = len(begin) @@ -166,7 +165,6 @@ def group_transform( num_columns: int, *args: Any, ) -> np.ndarray: - assert len(begin) == len(end) num_groups = len(begin) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 20c3733b50bc5..52b8301554c96 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -153,7 +153,6 @@ def __init__(self, kind: str, how: str, has_dropped_na: bool) -> None: def _get_cython_function( cls, kind: str, how: str, dtype: np.dtype, is_numeric: bool ): - dtype_str = dtype.name ftype = cls._CYTHON_FUNCTIONS[kind][how] diff --git a/pandas/core/indexers/objects.py b/pandas/core/indexers/objects.py index c15cbf368c159..714fe92301a08 100644 --- a/pandas/core/indexers/objects.py +++ b/pandas/core/indexers/objects.py @@ -67,7 +67,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - raise NotImplementedError @@ -83,7 +82,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - if center: offset = (self.window_size - 1) // 2 else: @@ -114,7 +112,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - # error: Argument 4 to "calculate_variable_window_bounds" has incompatible # type "Optional[bool]"; expected "bool" # error: Argument 6 to "calculate_variable_window_bounds" has incompatible @@ -153,7 +150,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - if step is not None: raise NotImplementedError("step not implemented for variable offset window") if num_values <= 0: @@ -229,7 +225,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - return ( np.zeros(num_values, dtype=np.int64), np.arange(1, num_values + 1, dtype=np.int64), @@ -270,7 +265,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - if center: raise ValueError("Forward-looking windows can't have center=True") if closed is not None: @@ -336,7 +330,6 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - # 1) For each group, get the indices that belong to the group # 2) Use the indices to calculate the start & end bounds of the window # 3) Append the window bounds in group order @@ -394,5 +387,4 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - return np.array([0], dtype=np.int64), np.array([num_values], dtype=np.int64) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 8adb7cca45323..5d523da12c51c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -454,7 +454,6 @@ def __new__( name=None, tupleize_cols: bool = True, ) -> Index: - from pandas.core.indexes.range import RangeIndex name = maybe_extract_name(name, data, cls) @@ -479,7 +478,6 @@ def __new__( pass elif isinstance(data, (np.ndarray, Index, ABCSeries)): - if isinstance(data, ABCMultiIndex): data = data._values @@ -500,7 +498,6 @@ def __new__( raise cls._raise_scalar_data_error(data) else: - if tupleize_cols: # GH21470: convert iterable to list before determining if empty if is_iterator(data): @@ -798,7 +795,6 @@ def _engine( # For base class (object dtype) we get ObjectEngine target_values = self._get_engine_target() if isinstance(target_values, ExtensionArray): - if isinstance(target_values, BaseMaskedArray): return _masked_engines[target_values.dtype.name](target_values) elif self._engine_type is libindex.ObjectEngine: @@ -922,7 +918,6 @@ def ravel(self, order: str_t = "C") -> Index: return self[:] def view(self, cls=None): - # we need to see if we are subclassing an # index type here if cls is not None and not hasattr(cls, "_typ"): @@ -1211,7 +1206,6 @@ def __repr__(self) -> str_t: return f"{klass_name}({data}{prepr})" def _format_space(self) -> str_t: - # using space here controls if the attributes # are line separated or not (the default) @@ -3880,7 +3874,6 @@ def _convert_tolerance(self, tolerance, target: np.ndarray | Index) -> np.ndarra def _get_fill_indexer( self, target: Index, method: str_t, limit: int | None = None, tolerance=None ) -> npt.NDArray[np.intp]: - if self._is_multi: # TODO: get_indexer_with_fill docstring says values must be _sorted_ # but that doesn't appear to be enforced @@ -3988,7 +3981,6 @@ def _filter_indexer_tolerance( indexer: npt.NDArray[np.intp], tolerance, ) -> npt.NDArray[np.intp]: - distance = self._difference_compat(target, indexer) return np.where(distance <= tolerance, indexer, -1) @@ -4310,12 +4302,10 @@ def _reindex_non_unique( # GH#38906 if not len(self): - new_indexer = np.arange(0, dtype=np.intp) # a unique indexer elif target.is_unique: - # see GH5553, make sure we use the right indexer new_indexer = np.arange(len(indexer), dtype=np.intp) new_indexer[cur_indexer] = np.arange(len(cur_labels)) @@ -4324,7 +4314,6 @@ def _reindex_non_unique( # we have a non_unique selector, need to use the original # indexer here else: - # need to retake to have the same size as the indexer indexer[~check] = -1 @@ -4426,7 +4415,6 @@ def join( # try to figure out the join level # GH3662 if level is None and (self._is_multi or other._is_multi): - # have the same levels/names so a simple join if self.names == other.names: pass @@ -4557,7 +4545,6 @@ def _join_multi(self, other: Index, how: JoinHow): raise ValueError("cannot join with no overlapping index names") if isinstance(self, MultiIndex) and isinstance(other, MultiIndex): - # Drop the non-matching levels from left and right respectively ldrop_names = sorted(self_names - overlap, key=self_names_order) rdrop_names = sorted(other_names - overlap, key=other_names_order) @@ -5877,7 +5864,6 @@ def _raise_if_missing(self, key, indexer, axis_name: str_t) -> None: nmissing = missing_mask.sum() if nmissing: - # TODO: remove special-case; this is just to keep exception # message tests from raising while debugging use_interval_msg = is_interval_dtype(self.dtype) or ( diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index ff24f97106c51..51ff92560fe5f 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -210,7 +210,6 @@ def __new__( copy: bool = False, name: Hashable = None, ) -> CategoricalIndex: - name = maybe_extract_name(name, data, cls) if is_scalar(data): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index dec691f7335e3..9237423fb03b4 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -300,7 +300,6 @@ def _partial_date_slice( unbox = self._data._unbox if self.is_monotonic_increasing: - if len(self) and ( (t1 < self[0] and t2 < self[0]) or (t1 > self[-1] and t2 > self[-1]) ): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 64dde64371e29..096e501c7bd6e 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -316,7 +316,6 @@ def __new__( copy: bool = False, name: Hashable = None, ) -> DatetimeIndex: - if is_scalar(data): cls._raise_scalar_data_error(data) @@ -550,7 +549,6 @@ def get_loc(self, key): key = Timestamp(key) elif isinstance(key, str): - try: parsed, reso = self._parse_with_reso(key) except (ValueError, pytz.NonExistentTimeError) as err: @@ -585,7 +583,6 @@ def get_loc(self, key): @doc(DatetimeTimedeltaMixin._maybe_cast_slice_bound) def _maybe_cast_slice_bound(self, label, side: str): - # GH#42855 handle date here instead of get_slice_bound if isinstance(label, dt.date) and not isinstance(label, dt.datetime): # Pandas supports slicing with dates, treated as datetimes at midnight. diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 69dacb043010a..47a7e59ba0229 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -218,7 +218,6 @@ def __new__( name: Hashable = None, verify_integrity: bool = True, ) -> IntervalIndex: - name = maybe_extract_name(name, data, cls) with rewrite_exception("IntervalArray", cls.__name__): @@ -673,7 +672,6 @@ def _get_indexer( limit: int | None = None, tolerance: Any | None = None, ) -> npt.NDArray[np.intp]: - if isinstance(target, IntervalIndex): # We only get here with not self.is_overlapping # -> at most one match per interval in target diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index a4df2acf0ab45..3d8948615f288 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -321,7 +321,6 @@ def __new__( name=None, verify_integrity: bool = True, ) -> MultiIndex: - # compat with Index if name is not None: names = name @@ -1337,7 +1336,6 @@ def format( na = na_rep if na_rep is not None else _get_na_rep(lev.dtype) if len(lev) > 0: - formatted = lev.take(level_codes).format(formatter=formatter) # we have some NA @@ -1535,7 +1533,6 @@ def is_monotonic_increasing(self) -> bool: sort_order = np.lexsort(values) # type: ignore[arg-type] return Index(sort_order).is_monotonic_increasing except TypeError: - # we have mixed types and np.lexsort is not happy return Index(self._values).is_monotonic_increasing @@ -1661,7 +1658,6 @@ def get_level_values(self, level): @doc(Index.unique) def unique(self, level=None): - if level is None: return self.drop_duplicates() else: @@ -1881,7 +1877,6 @@ def _sort_levels_monotonic(self, raise_if_incomparable: bool = False) -> MultiIn new_codes = [] for lev, level_codes in zip(self.levels, self.codes): - if not lev.is_monotonic_increasing: try: # indexer to reorder the levels @@ -1948,7 +1943,6 @@ def remove_unused_levels(self) -> MultiIndex: changed = False for lev, level_codes in zip(self.levels, self.codes): - # Since few levels are typically unused, bincount() is more # efficient than unique() - however it only accepts positive values # (and drops order): @@ -1956,7 +1950,6 @@ def remove_unused_levels(self) -> MultiIndex: has_na = int(len(uniques) and (uniques[0] == -1)) if len(uniques) != len(lev) + has_na: - if lev.isna().any() and len(uniques) == len(lev): break # We have unused levels @@ -2449,7 +2442,6 @@ def sortlevel( # level ordering else: - codes = list(self.codes) shape = list(self.levshape) @@ -2534,7 +2526,6 @@ def _should_fallback_to_positional(self) -> bool: def _get_indexer_strict( self, key, axis_name: str ) -> tuple[Index, npt.NDArray[np.intp]]: - keyarr = key if not isinstance(keyarr, Index): keyarr = com.asarray_tuplesafe(keyarr) @@ -2979,7 +2970,6 @@ def maybe_mi_droplevels(indexer, levels): key = tuple(key) if isinstance(key, tuple) and level == 0: - try: # Check if this tuple is a single key in our first level if key in self.levels[0]: @@ -2990,7 +2980,6 @@ def maybe_mi_droplevels(indexer, levels): pass if not any(isinstance(k, slice) for k in key): - if len(key) == self.nlevels and self.is_unique: # Complete key in unique index -> standard get_loc try: @@ -3138,7 +3127,6 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes): else: stop = len(level_index) - 1 except KeyError: - # we have a partial slice (like looking up a partial date # string) start = stop = level_index.slice_indexer(key.start, key.stop, key.step) @@ -3166,7 +3154,6 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes): return slice(i, j, step) else: - idx = self._get_loc_single_level_index(level_index, key) if level > 0 or self._lexsort_depth == 0: @@ -3258,7 +3245,6 @@ def _to_bool_indexer(indexer) -> npt.NDArray[np.bool_]: indexer: npt.NDArray[np.bool_] | None = None for i, k in enumerate(seq): - lvl_indexer: npt.NDArray[np.bool_] | slice | None = None if com.is_bool_indexer(k): @@ -3622,7 +3608,6 @@ def _convert_can_do_setop(self, other): result_names = self.names if not isinstance(other, Index): - if len(other) == 0: return self[:0], self.names else: diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 5c849b47745eb..2d4f0736e30fa 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -207,7 +207,6 @@ def __new__( name: Hashable = None, **fields, ) -> PeriodIndex: - valid_field_set = { "year", "month", @@ -401,7 +400,6 @@ def get_loc(self, key): key = NaT elif isinstance(key, str): - try: parsed, reso = self._parse_with_reso(key) except ValueError as err: diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 670b97adf7c36..0be539a9c3216 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -929,7 +929,6 @@ def _getitem_slice(self: RangeIndex, slobj: slice) -> RangeIndex: @unpack_zerodim_and_defer("__floordiv__") def __floordiv__(self, other): - if is_integer(other) and other != 0: if len(self) == 0 or self.start % other == 0 and self.step % other == 0: start = self.start // other diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 8c3e56b686e79..d981d8e097dbb 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -970,7 +970,6 @@ def _getitem_tuple_same_dim(self, tup: tuple): @final def _getitem_lowerdim(self, tup: tuple): - # we can directly get the axis result since the axis is specified if self.axis is not None: axis = self.obj._get_axis_number(self.axis) @@ -1075,7 +1074,6 @@ def _getitem_nested_tuple(self, tup: tuple): # which selects only necessary blocks which avoids dtype conversion if possible axis = len(tup) - 1 for key in tup[::-1]: - if com.is_null_slice(key): axis -= 1 continue @@ -1330,10 +1328,8 @@ def _getitem_axis(self, key, axis: AxisInt): elif com.is_bool_indexer(key): return self._getbool_axis(key, axis=axis) elif is_list_like_indexer(key): - # an iterable multi-selection if not (isinstance(key, tuple) and isinstance(labels, MultiIndex)): - if hasattr(key, "ndim") and key.ndim > 1: raise ValueError("Cannot index with multidimensional key") @@ -1424,7 +1420,6 @@ def _convert_to_indexer(self, key, axis: AxisInt): return labels.get_locs(key) elif is_list_like_indexer(key): - if is_iterator(key): key = list(key) @@ -1600,7 +1595,6 @@ def _validate_integer(self, key: int, axis: AxisInt) -> None: # ------------------------------------------------------------------- def _getitem_tuple(self, tup: tuple): - tup = self._validate_tuple_indexer(tup) with suppress(IndexingError): return self._getitem_lowerdim(tup) @@ -1742,7 +1736,6 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc"): nindexer = [] for i, idx in enumerate(indexer): if isinstance(idx, dict): - # reindex the axis to the new value # and set inplace key, _ = convert_missing_indexer(idx) @@ -1753,7 +1746,6 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc"): # essentially this separates out the block that is needed # to possibly be modified if self.ndim > 1 and i == info_axis: - # add the new item, and set the value # must have all defined axes if we have a scalar # or a list-like on the non-info axes if we have a @@ -1823,7 +1815,6 @@ def _setitem_with_indexer(self, indexer, value, name: str = "iloc"): indexer = tuple(nindexer) else: - indexer, missing = convert_missing_indexer(indexer) if missing: @@ -1871,7 +1862,6 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str): # we need an iterable, with a ndim of at least 1 # eg. don't pass through np.array(0) if is_list_like_indexer(value) and getattr(value, "ndim", 1) > 0: - if isinstance(value, ABCDataFrame): self._setitem_with_indexer_frame_value(indexer, value, name) @@ -1927,7 +1917,6 @@ def _setitem_with_indexer_split_path(self, indexer, value, name: str): ) else: - # scalar value for loc in ilocs: self._setitem_single_column(loc, value, pi) @@ -2024,7 +2013,6 @@ def _setitem_single_column(self, loc: int, value, plane_indexer) -> None: return elif is_full_setter: - try: self.obj._mgr.column_setitem( loc, plane_indexer, value, inplace_only=True @@ -2050,7 +2038,6 @@ def _setitem_single_block(self, indexer, value, name: str) -> None: info_axis = self.obj._info_axis_number item_labels = self.obj._get_axis(info_axis) if isinstance(indexer, tuple): - # if we are setting on the info axis ONLY # set using those methods to avoid block-splitting # logic here @@ -2144,7 +2131,6 @@ def _setitem_with_indexer_missing(self, indexer, value): self.obj._maybe_update_cacher(clear=True) elif self.ndim == 2: - if not len(self.obj.columns): # no columns and scalar raise ValueError("cannot set a frame with no defined columns") @@ -2226,7 +2212,6 @@ def _align_series(self, indexer, ser: Series, multiindex_indexer: bool = False): indexer = (indexer,) if isinstance(indexer, tuple): - # flatten np.ndarray indexers def ravel(i): return i.ravel() if isinstance(i, np.ndarray) else i @@ -2284,7 +2269,6 @@ def ravel(i): # 2 dims elif single_aligner: - # reindex along index ax = self.obj.axes[1] if ser.index.equals(ax) or not len(ax): @@ -2315,7 +2299,6 @@ def _align_frame(self, indexer, df: DataFrame) -> DataFrame: is_frame = self.ndim == 2 if isinstance(indexer, tuple): - idx, cols = None, None sindexers = [] for i, ix in enumerate(indexer): @@ -2333,7 +2316,6 @@ def _align_frame(self, indexer, df: DataFrame) -> DataFrame: sindexers.append(i) if idx is not None and cols is not None: - if df.index.equals(idx) and df.columns.equals(cols): val = df.copy() else: @@ -2345,7 +2327,6 @@ def _align_frame(self, indexer, df: DataFrame) -> DataFrame: if df.index.equals(ax): val = df.copy() else: - # we have a multi-index and are trying to align # with a particular, level GH3738 if ( @@ -2377,7 +2358,6 @@ def _convert_key(self, key): def __getitem__(self, key): if not isinstance(key, tuple): - # we could have a convertible item here (e.g. Timestamp) if not is_list_like_indexer(key): key = (key,) @@ -2427,7 +2407,6 @@ def _axes_are_unique(self) -> bool: return self.obj.index.is_unique and self.obj.columns.is_unique def __getitem__(self, key): - if self.ndim == 2 and not self._axes_are_unique: # GH#33041 fall back to .loc if not isinstance(key, tuple) or not all(is_scalar(x) for x in key): @@ -2549,7 +2528,6 @@ def convert_missing_indexer(indexer): return the scalar indexer and a boolean indicating if we converted """ if isinstance(indexer, dict): - # a missing key (but not a tuple indexer) indexer = indexer["key"] diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 431313e3a2960..6f21545006f75 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -219,9 +219,7 @@ def apply( f = kwargs.pop("func") for i, arr in enumerate(self.arrays): - if aligned_args: - for k, obj in aligned_args.items(): if isinstance(obj, (ABCSeries, ABCDataFrame)): # The caller is responsible for ensuring that @@ -263,7 +261,6 @@ def apply_with_block( result_arrays = [] for i, arr in enumerate(self.arrays): - if aligned_args: for k, obj in aligned_args.items(): if isinstance(obj, (ABCSeries, ABCDataFrame)): @@ -357,7 +354,6 @@ def shift(self: T, periods: int, axis: AxisInt, fill_value) -> T: ) def fillna(self: T, value, limit, inplace: bool, downcast) -> T: - if limit is not None: # Do this validation even if we go through one of the no-op paths limit = libalgos.validate_limit(None, limit=limit) @@ -815,7 +811,6 @@ def iset( """ # single column -> single integer index if lib.is_integer(loc): - # 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: @@ -1020,7 +1015,6 @@ def quantile( transposed: bool = False, interpolation: QuantileInterpolation = "linear", ) -> ArrayManager: - arrs = [ensure_block_shape(x, 2) for x in self.arrays] assert axis == 1 new_arrs = [ @@ -1146,7 +1140,6 @@ def as_array( class SingleArrayManager(BaseArrayManager, SingleDataManager): - __slots__ = [ "_axes", # private attribute, because 'axes' has different order, see below "arrays", diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py index 8a0f2863d851f..bb5d7e839a98c 100644 --- a/pandas/core/internals/base.py +++ b/pandas/core/internals/base.py @@ -35,7 +35,6 @@ class DataManager(PandasObject): - # TODO share more methods/attributes axes: list[Index] diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 6d20935d5f244..db5cb4a70c8f1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -130,7 +130,6 @@ def maybe_split(meth: F) -> F: @wraps(meth) def newfunc(self, *args, **kwargs) -> list[Block]: - if self.ndim == 1 or self.shape[0] == 1: return meth(self, *args, **kwargs) else: @@ -249,7 +248,6 @@ def __repr__(self) -> str: if self.ndim == 1: result = f"{name}: {len(self)} dtype: {self.dtype}" else: - shape = " x ".join([str(s) for s in self.shape]) result = f"{name}: {self.mgr_locs.indexer}, {shape}, dtype: {self.dtype}" @@ -1045,7 +1043,6 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: return [self.copy(deep=False)] return [self] except LossySetitemError: - if self.ndim == 1 or self.shape[0] == 1: # no need to split columns @@ -1255,7 +1252,6 @@ def interpolate( using_cow: bool = False, **kwargs, ) -> list[Block]: - inplace = validate_bool_kwarg(inplace, "inplace") if not self._can_hold_na: @@ -1426,7 +1422,6 @@ def delete(self, loc) -> list[Block]: # don't share data refs = self.refs if self.refs.has_reference() else None for idx in loc: - if idx == previous_loc + 1: # There is no column between current and last idx pass @@ -1558,7 +1553,6 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: _catch_deprecated_value_error(err) if self.ndim == 1 or self.shape[0] == 1: - if is_interval_dtype(self.dtype): # TestSetitemFloatIntervalWithIntIntervalValues blk = self.coerce_to_target_dtype(orig_other) @@ -1630,7 +1624,6 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: _catch_deprecated_value_error(err) if self.ndim == 1 or self.shape[0] == 1: - if is_interval_dtype(self.dtype): # Discussion about what we want to support in the general # case GH#39584 @@ -1830,7 +1823,6 @@ def _unwrap_setitem_indexer(self, indexer): # Length 1 is reached vis setitem_single_block and setitem_single_column # each of which pass indexer=(pi,) if len(indexer) == 2: - if all(isinstance(x, np.ndarray) and x.ndim == 2 for x in indexer): # GH#44703 went through indexing.maybe_convert_ix first, second = indexer @@ -2451,7 +2443,6 @@ def to_native_types( return new_values else: - mask = isna(values) itemsize = writers.word_len(na_rep) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index eb2f8533fafb4..3c357bd7516c0 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -352,7 +352,6 @@ def _get_mgr_concatenation_plan(mgr: BlockManager, indexers: dict[int, np.ndarra plan = [] for blkno, placements in libinternals.get_blkno_placements(blknos, group=False): - assert placements.is_slice_like assert blkno != -1 diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index e5b2e5ce42fcd..934d08341395c 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -317,7 +317,6 @@ def ndarray_to_mgr( _check_values_indices_shape_match(values, index, columns) if typ == "array": - if issubclass(values.dtype.type, str): values = np.array(values, dtype=object) @@ -952,7 +951,6 @@ def _validate_or_indexify_columns( if columns is None: columns = default_index(len(content)) else: - # Add mask for data which is composed of list of lists is_mi_list = isinstance(columns, list) and all( isinstance(col, list) for col in columns @@ -965,7 +963,6 @@ def _validate_or_indexify_columns( f"{len(content)} columns" ) if is_mi_list: - # check if nested list column, length of each sub-list should be equal if len({len(col) for col in columns}) > 1: raise ValueError( diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index eb4c2d642862b..329ac877e0ef4 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -307,9 +307,7 @@ def apply( aligned_args = {k: kwargs[k] for k in align_keys} for b in self.blocks: - if aligned_args: - for k, obj in aligned_args.items(): if isinstance(obj, (ABCSeries, ABCDataFrame)): # The caller is responsible for ensuring that @@ -394,7 +392,6 @@ def shift(self: T, periods: int, axis: AxisInt, fill_value) -> T: return self.apply("shift", periods=periods, axis=axis, fill_value=fill_value) def fillna(self: T, value, limit, inplace: bool, downcast) -> T: - if limit is not None: # Do this validation even if we go through one of the no-op paths limit = libalgos.validate_limit(None, limit=limit) @@ -945,7 +942,6 @@ def __init__( axes: Sequence[Index], verify_integrity: bool = True, ) -> None: - if verify_integrity: # Assertion disabled for performance # assert all(isinstance(x, Index) for x in axes) @@ -2201,7 +2197,6 @@ def _tuples_to_blocks_no_consolidate(tuples, refs) -> list[Block]: def _stack_arrays(tuples, dtype: np.dtype): - placement, arrays = zip(*tuples) first = arrays[0] @@ -2234,12 +2229,10 @@ def _consolidate(blocks: tuple[Block, ...]) -> tuple[Block, ...]: def _merge_blocks( blocks: list[Block], dtype: DtypeObj, can_consolidate: bool ) -> tuple[list[Block], bool]: - if len(blocks) == 1: return blocks, False if can_consolidate: - # 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]) diff --git a/pandas/core/missing.py b/pandas/core/missing.py index fc3178c8b7132..ff307b592737b 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -994,14 +994,12 @@ def inner(invalid, limit): return idx if fw_limit is not None: - if fw_limit == 0: f_idx = set(np.where(invalid)[0]) else: f_idx = inner(invalid, fw_limit) if bw_limit is not None: - if bw_limit == 0: # then we don't even need to care about backwards # just use forwards diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 1ffcf93278e50..41ed9485643e7 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -794,7 +794,6 @@ def get_median(x, _mask=None): # an array from a frame if values.ndim > 1 and axis is not None: - # there's a non-empty array to apply over otherwise numpy raises if notempty: if not skipna: @@ -1081,7 +1080,6 @@ def reduction( skipna: bool = True, mask: npt.NDArray[np.bool_] | None = None, ) -> Dtype: - values, mask, dtype, dtype_max, fill_value = _get_values( values, skipna, fill_value_typ=fill_value_typ, mask=mask ) diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 3908422bba523..64619fdc4b8d4 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -163,7 +163,6 @@ def align_method_SERIES(left: Series, right, align_asobject: bool = False): if isinstance(right, ABCSeries): # avoid repeated alignment if not left.index.equals(right.index): - if align_asobject: # to keep original value's dtype for bool ops left = left.astype(object) @@ -257,7 +256,6 @@ def to_series(right): return right if isinstance(right, np.ndarray): - if right.ndim == 1: right = to_series(right) diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py index 8bba400cedc9a..d4ae143372271 100644 --- a/pandas/core/ops/common.py +++ b/pandas/core/ops/common.py @@ -66,7 +66,6 @@ def _unpack_zerodim_and_defer(method, name: str): @wraps(method) def new_method(self, other): - if is_cmp and isinstance(self, ABCIndex) and isinstance(other, ABCSeries): # For comparison ops, Index does *not* defer to Series pass diff --git a/pandas/core/ops/missing.py b/pandas/core/ops/missing.py index 850ca44e996c4..3ba611c3bd0df 100644 --- a/pandas/core/ops/missing.py +++ b/pandas/core/ops/missing.py @@ -59,10 +59,8 @@ def _fill_zeros(result, x, y): y = np.array(y) if is_integer_dtype(y.dtype): - ymask = y == 0 if ymask.any(): - # GH#7325, mask and nans must be broadcastable mask = ymask & ~np.isnan(result) @@ -114,7 +112,6 @@ def mask_zero_div_zero(x, y, result: np.ndarray) -> np.ndarray: zmask = y == 0 if zmask.any(): - # Flip sign if necessary for -0.0 zneg_mask = zmask & np.signbit(y) zpos_mask = zmask & ~zneg_mask diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 1d03baff33297..f23256c64db2d 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -326,7 +326,6 @@ def pipe( axis="", ) def aggregate(self, func=None, *args, **kwargs): - result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() if result is None: how = func @@ -1253,7 +1252,6 @@ def _resampler_for_grouping(self): return DatetimeIndexResamplerGroupby def _get_binner_for_time(self): - # this is how we are actually creating the bins if self.kind == "period": return self._timegrouper._get_time_period_bins(self.ax) @@ -1291,7 +1289,6 @@ def _downsample(self, how, **kwargs): and len(self.grouper.binlabels) > len(ax) and how is None ): - # let's do an asfreq return self.asfreq() @@ -1950,7 +1947,6 @@ def _get_period_bins(self, ax: PeriodIndex): def _take_new_index( obj: NDFrameT, indexer: npt.NDArray[np.intp], new_index: Index, axis: AxisInt = 0 ) -> NDFrameT: - if isinstance(obj, ABCSeries): new_values = algos.take_nd(obj._values, indexer) # error: Incompatible return value type (got "Series", expected "NDFrameT") diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index a36352e83ff3e..a3068e5c9e4b8 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -519,7 +519,6 @@ def __init__( max_ndim = sample.ndim self.objs, objs = [], self.objs for obj in objs: - ndim = obj.ndim if ndim == max_ndim: pass @@ -713,7 +712,6 @@ def _concat_indexes(indexes) -> Index: def _make_concat_multiindex(indexes, keys, levels=None, names=None) -> MultiIndex: - if (levels is None and isinstance(keys[0], tuple)) or ( levels is not None and len(levels) > 1 ): diff --git a/pandas/core/reshape/encoding.py b/pandas/core/reshape/encoding.py index 2aa1a3001fb6b..d00fade8a1c6f 100644 --- a/pandas/core/reshape/encoding.py +++ b/pandas/core/reshape/encoding.py @@ -159,7 +159,6 @@ def get_dummies( # validate prefixes and separator to avoid silently dropping cols def check_len(item, name): - if is_list_like(item): if not len(item) == data_to_encode.shape[1]: len_msg = ( @@ -199,7 +198,7 @@ def check_len(item, name): # columns to prepend to result. with_dummies = [data.select_dtypes(exclude=dtypes_to_encode)] - for (col, pre, sep) in zip(data_to_encode.items(), prefix, prefix_sep): + for col, pre, sep in zip(data_to_encode.items(), prefix, prefix_sep): # col is (column_name, column), use just column data here dummy = _get_dummies_1d( col[1], @@ -281,7 +280,6 @@ def get_empty_frame(data) -> DataFrame: index = None if sparse: - fill_value: bool | float if is_integer_dtype(dtype): fill_value = 0 diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 37013a5d1fb8f..9029716f4b435 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -179,7 +179,6 @@ def _groupby_and_merge(by, left: DataFrame, right: DataFrame, merge_pieces): rby = right.groupby(by, sort=False) for key, lhs in lby.grouper.get_iterator(lby._selected_obj, axis=lby.axis): - if rby is None: rhs = right else: @@ -835,7 +834,6 @@ def _indicator_name(self) -> str | None: def _indicator_pre_merge( self, left: DataFrame, right: DataFrame ) -> tuple[DataFrame, DataFrame]: - columns = left.columns.union(right.columns) for i in ["_left_indicator", "_right_indicator"]: @@ -861,7 +859,6 @@ def _indicator_pre_merge( return left, right def _indicator_post_merge(self, result: DataFrame) -> DataFrame: - result["_left_indicator"] = result["_left_indicator"].fillna(0) result["_right_indicator"] = result["_right_indicator"].fillna(0) @@ -914,7 +911,6 @@ def _maybe_restore_index_levels(self, result: DataFrame) -> None: and left_key == right_key and name not in result.index.names ): - names_to_restore.append(name) if names_to_restore: @@ -926,7 +922,6 @@ def _maybe_add_join_keys( left_indexer: np.ndarray | None, right_indexer: np.ndarray | None, ) -> None: - left_has_missing = None right_has_missing = None @@ -940,10 +935,8 @@ def _maybe_add_join_keys( take_left, take_right = None, None if name in result: - if left_indexer is not None and right_indexer is not None: if name in self.left: - if left_has_missing is None: left_has_missing = (left_indexer == -1).any() @@ -956,7 +949,6 @@ def _maybe_add_join_keys( take_left = self.left[name]._values elif name in self.right: - if right_has_missing is None: right_has_missing = (right_indexer == -1).any() @@ -973,7 +965,6 @@ def _maybe_add_join_keys( take_right = self.right_join_keys[i] if take_left is not None or take_right is not None: - if take_left is None: lvals = result[name]._values else: @@ -1470,7 +1461,6 @@ def _validate_left_right_on(self, left_on, right_on): ) # Hm, any way to make this logic less complicated?? elif self.on is None and left_on is None and right_on is None: - if self.left_index and self.right_index: left_on, right_on = (), () elif self.left_index: @@ -1544,7 +1534,6 @@ def _validate_left_right_on(self, left_on, right_on): return left_on, right_on def _validate(self, validate: str) -> None: - # Check uniqueness of each if self.left_index: left_unique = self.orig_left.index.is_unique @@ -1783,7 +1772,6 @@ def __init__( fill_method: str | None = None, how: JoinHow | Literal["asof"] = "outer", ) -> None: - self.fill_method = fill_method _MergeOperation.__init__( self, @@ -1876,7 +1864,6 @@ def __init__( allow_exact_matches: bool = True, direction: str = "backward", ) -> None: - self.by = by self.left_by = left_by self.right_by = right_by @@ -1981,7 +1968,6 @@ def _validate_left_right_on(self, left_on, right_on): def _get_merge_keys( self, ) -> tuple[list[AnyArrayLike], list[AnyArrayLike], list[Hashable]]: - # note this function has side effects (left_join_keys, right_join_keys, join_names) = super()._get_merge_keys() @@ -2010,7 +1996,6 @@ def _get_merge_keys( # validate tolerance; datetime.timedelta or Timedelta if we have a DTI if self.tolerance is not None: - if self.left_index: # Actually more specifically an Index lt = cast(AnyArrayLike, self.left.index) @@ -2185,7 +2170,6 @@ def injection(obj): def _get_multiindex_indexer( join_keys, index: MultiIndex, sort: bool ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: - # left & right join labels and num. of levels at each location mapped = ( _factorize_keys(index.levels[n], join_keys[n], sort=sort) @@ -2464,7 +2448,6 @@ def _convert_arrays_and_get_rizer_klass( def _sort_labels( uniques: np.ndarray, left: npt.NDArray[np.intp], right: npt.NDArray[np.intp] ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: - llength = len(left) labels = np.concatenate([left, right]) @@ -2480,7 +2463,6 @@ def _get_join_keys( shape: Shape, sort: bool, ) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]: - # how many levels can be done without overflow nlev = next( lev diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 91a97f743efeb..a919f72c7d220 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -342,7 +342,6 @@ def _add_margins( def _compute_grand_margin( data: DataFrame, values, aggfunc, margins_name: Hashable = "All" ): - if values: grand_margin = {} for k, v in data[values].items(): @@ -504,7 +503,6 @@ def pivot( index: IndexLabel | lib.NoDefault = lib.NoDefault, values: IndexLabel | lib.NoDefault = lib.NoDefault, ) -> DataFrame: - columns_listlike = com.convert_to_list_like(columns) # If columns is None we will create a MultiIndex level with None as name @@ -737,7 +735,6 @@ def crosstab( def _normalize( table: DataFrame, normalize, margins: bool, margins_name: Hashable = "All" ) -> DataFrame: - if not isinstance(normalize, (bool, str)): axis_subs = {0: "index", 1: "columns"} try: @@ -746,7 +743,6 @@ def _normalize( raise ValueError("Not a valid normalize argument") from err if margins is False: - # Actual Normalizations normalizers: dict[bool | str, Callable] = { "all": lambda x: x / x.sum(axis=1).sum(axis=0), diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 6265e35cc2c84..e83317ebc74ce 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -95,7 +95,6 @@ class _Unstacker: """ def __init__(self, index: MultiIndex, level=-1, constructor=None) -> None: - if constructor is None: constructor = DataFrame self.constructor = constructor @@ -205,7 +204,6 @@ def arange_result(self) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.bool_]]: # TODO: in all tests we have mask.any(0).all(); can we rely on that? def get_result(self, values, value_columns, fill_value) -> DataFrame: - if values.ndim == 1: values = values[:, np.newaxis] @@ -221,7 +219,6 @@ def get_result(self, values, value_columns, fill_value) -> DataFrame: ) def get_new_values(self, values, fill_value=None): - if values.ndim == 1: values = values[:, np.newaxis] @@ -461,7 +458,6 @@ def _unstack_multiple(data, clocs, fill_value=None): def unstack(obj: Series | DataFrame, level, fill_value=None): - if isinstance(level, (tuple, list)): if len(level) != 1: # _unstack_multiple only handles MultiIndexes, diff --git a/pandas/core/series.py b/pandas/core/series.py index c8b431abd1958..7af68a118889e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -235,6 +235,7 @@ def wrapper(self): # ---------------------------------------------------------------------- # Series class + # error: Definition of "max" in base class "IndexOpsMixin" is incompatible with # definition in base class "NDFrame" # error: Definition of "min" in base class "IndexOpsMixin" is incompatible with @@ -372,7 +373,6 @@ def __init__( copy: bool = False, fastpath: bool = False, ) -> None: - if ( isinstance(data, (SingleBlockManager, SingleArrayManager)) and index is None @@ -424,7 +424,6 @@ def __init__( "initializing a Series from a MultiIndex is not supported" ) if isinstance(data, Index): - if dtype is not None: # astype copies data = data.astype(dtype) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 803dbe32bc16b..0e45c9a71a5c5 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -3314,7 +3314,6 @@ def str_extractall(arr, pat, flags: int = 0): for subject_key, subject in arr.items(): if isinstance(subject, str): - if not is_mi: subject_key = (subject_key,) diff --git a/pandas/core/tools/times.py b/pandas/core/tools/times.py index edb6b97ad2e53..cb178926123d3 100644 --- a/pandas/core/tools/times.py +++ b/pandas/core/tools/times.py @@ -51,7 +51,6 @@ def to_time( """ def _convert_listlike(arg, format): - if isinstance(arg, (list, tuple)): arg = np.array(arg, dtype="O") diff --git a/pandas/core/window/common.py b/pandas/core/window/common.py index 51d9f70c1d018..b6c7bc5684d20 100644 --- a/pandas/core/window/common.py +++ b/pandas/core/window/common.py @@ -15,7 +15,6 @@ def flex_binary_moment(arg1, arg2, f, pairwise: bool = False): - if isinstance(arg1, ABCSeries) and isinstance(arg2, ABCSeries): X, Y = prep_binary(arg1, arg2) return f(X, Y) @@ -67,7 +66,6 @@ def dataframe_from_int_dict(data, frame_template) -> DataFrame: result_index = arg1.index.union(arg2.index) if len(result_index): - # construct result frame result = concat( [ @@ -119,7 +117,6 @@ def dataframe_from_int_dict(data, frame_template) -> DataFrame: [result_index] + [arg2.columns] ) else: - # empty result result = DataFrame( index=MultiIndex( diff --git a/pandas/core/window/numba_.py b/pandas/core/window/numba_.py index 0f9f01e93a477..756f8e3a1cffc 100644 --- a/pandas/core/window/numba_.py +++ b/pandas/core/window/numba_.py @@ -141,7 +141,6 @@ def ewm( is_observation = not np.isnan(cur) nobs += is_observation if not np.isnan(weighted): - if is_observation or not ignore_na: if normalize: # note that len(deltas) = len(vals) - 1 and deltas[i] diff --git a/pandas/core/window/online.py b/pandas/core/window/online.py index 2e25bdd12d3e0..f9e3122b304bc 100644 --- a/pandas/core/window/online.py +++ b/pandas/core/window/online.py @@ -63,7 +63,6 @@ def online_ewma( for j in numba.prange(len(cur)): if not np.isnan(weighted_avg[j]): if is_observations[j] or not ignore_na: - # note that len(deltas) = len(vals) - 1 and deltas[i] is to be # used in conjunction with vals[i+1] old_wt[j] *= old_wt_factor ** deltas[j - 1] diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 57ed10e798928..a08c26adf2e38 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1251,7 +1251,6 @@ def calc(x): def aggregate(self, func, *args, **kwargs): result = ResamplerWindowApply(self, func, args=args, kwargs=kwargs).agg() if result is None: - # these must apply directly result = func(self) @@ -1738,7 +1737,6 @@ def corr_func(x, y): class Rolling(RollingAndExpandingMixin): - _attributes: list[str] = [ "window", "min_periods", @@ -1759,7 +1757,6 @@ def _validate(self): self.obj.empty or isinstance(self._on, (DatetimeIndex, TimedeltaIndex, PeriodIndex)) ) and isinstance(self.window, (str, BaseOffset, timedelta)): - self._validate_datetimelike_monotonic() # this will raise ValueError on non-fixed freqs diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 79d174db5c0a7..13057a6277673 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -472,7 +472,6 @@ def read_excel( storage_options: StorageOptions = None, use_nullable_dtypes: bool | lib.NoDefault = lib.no_default, ) -> DataFrame | dict[IntStrT, DataFrame]: - should_close = False if not isinstance(io, ExcelFile): should_close = True @@ -720,7 +719,6 @@ def parse( use_nullable_dtypes: bool = False, **kwds, ): - validate_header_arg(header) validate_integer("nrows", nrows) @@ -806,7 +804,6 @@ def parse( # a row containing just the index name(s) has_index_names = False if is_list_header and not is_len_one_list_header and index_col is not None: - index_col_list: Sequence[int] if isinstance(index_col, int): index_col_list = [index_col] diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 10bb1dc548313..69ddadc58f10b 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -495,7 +495,6 @@ def _write_cells( setattr(xcell, k, v) if cell.mergestart is not None and cell.mergeend is not None: - wks.merge_cells( start_row=startrow + cell.row + 1, start_column=startcol + cell.col + 1, @@ -567,7 +566,6 @@ def get_sheet_by_index(self, index: int): return self.book.worksheets[index] def _convert_cell(self, cell) -> Scalar: - from openpyxl.cell.cell import ( TYPE_ERROR, TYPE_NUMERIC, @@ -588,7 +586,6 @@ def _convert_cell(self, cell) -> Scalar: def get_sheet_data( self, sheet, file_rows_needed: int | None = None ) -> list[list[Scalar]]: - if self.book.read_only: sheet.reset_dimensions() diff --git a/pandas/io/excel/_xlrd.py b/pandas/io/excel/_xlrd.py index c556e4c68c6c0..37bd4c1ba5ba5 100644 --- a/pandas/io/excel/_xlrd.py +++ b/pandas/io/excel/_xlrd.py @@ -79,7 +79,6 @@ def _parse_cell(cell_contents, cell_typ): converts the contents of the cell into a pandas appropriate object """ if cell_typ == XL_CELL_DATE: - # Use the newer xlrd datetime handling. try: cell_contents = xldate.xldate_as_datetime(cell_contents, epoch1904) diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 9f3d7d965f7c9..bda8de2de8897 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -245,7 +245,6 @@ def save(self) -> None: compression=self.compression, storage_options=self.storage_options, ) as handles: - # Note: self.encoding is irrelevant here self.writer = csvlib.writer( handles.handle, diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 9c2973c544e65..34c4d330761f5 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -556,7 +556,6 @@ def __init__( self.style_converter = None self.df = df if cols is not None: - # all missing, raise if not len(Index(cols).intersection(df.columns)): raise KeyError("passes columns are not ALL present dataframe") @@ -803,7 +802,6 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]: # if index labels are not empty go ahead and dump if com.any_not_none(*index_labels) and self.header is not False: - for cidx, name in enumerate(index_labels): yield ExcelCell(self.rowcounter - 1, cidx, name, self.header_style) @@ -817,7 +815,6 @@ def _format_hierarchical_rows(self) -> Iterable[ExcelCell]: for spans, levels, level_codes in zip( level_lengths, self.df.index.levels, self.df.index.codes ): - values = levels.take( level_codes, allow_fill=levels._can_hold_na, diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index afe6a405afbb8..ccae3887c248e 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1918,7 +1918,6 @@ def _make_fixed_width( minimum: int | None = None, adj: TextAdjustment | None = None, ) -> list[str]: - if len(strings) == 0 or justify == "all": return strings diff --git a/pandas/io/formats/html.py b/pandas/io/formats/html.py index 79f33245ef917..6fbbbd01cf773 100644 --- a/pandas/io/formats/html.py +++ b/pandas/io/formats/html.py @@ -430,7 +430,6 @@ def _write_regular_rows( row: list[str] = [] for i in range(nrows): - if is_truncated_vertically and i == (self.fmt.tr_row_num): str_sep_row = ["..."] * len(row) self.write_tr( diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index 6cc343703d00c..e734304471144 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -355,7 +355,6 @@ def format_object_summary( def _extend_line( s: str, line: str, value: str, display_width: int, next_line_prefix: str ) -> tuple[str, str]: - if adj.len(line.rstrip()) + adj.len(value.rstrip()) >= display_width: s += line.rstrip() line = next_line_prefix @@ -380,7 +379,6 @@ def best_len(values: list[str]) -> int: last = formatter(obj[-1]) summary = f"[{first}, {last}]{close}" else: - if max_seq_items == 1: # If max_seq_items=1 show only last element head = [] diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 442f2ab72a1e2..13aa035e34374 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -512,7 +512,6 @@ def to_excel( freeze_panes: tuple[int, int] | None = None, storage_options: StorageOptions = None, ) -> None: - from pandas.io.formats.excel import ExcelFormatter formatter = ExcelFormatter( diff --git a/pandas/io/formats/style_render.py b/pandas/io/formats/style_render.py index 5264342661b3f..6ae9c528e4772 100644 --- a/pandas/io/formats/style_render.py +++ b/pandas/io/formats/style_render.py @@ -89,7 +89,6 @@ def __init__( cell_ids: bool = True, precision: int | None = None, ) -> None: - # validate ordered args if isinstance(data, Series): data = data.to_frame() @@ -2152,7 +2151,7 @@ def _parse_latex_cell_styles( """ if convert_css: latex_styles = _parse_latex_css_conversion(latex_styles) - for (command, options) in latex_styles[::-1]: # in reverse for most recent style + for command, options in latex_styles[::-1]: # in reverse for most recent style formatter = { "--wrap": f"{{\\{command}--to_parse {display_value}}}", "--nowrap": f"\\{command}--to_parse {display_value}", @@ -2295,7 +2294,7 @@ def color(value, user_arg, command, comm_arg): } latex_styles: CSSList = [] - for (attribute, value) in styles: + for attribute, value in styles: if isinstance(value, str) and "--latex" in value: # return the style without conversion but drop '--latex' latex_styles.append((attribute, value.replace("--latex", ""))) diff --git a/pandas/io/formats/xml.py b/pandas/io/formats/xml.py index 60831b38dba31..cc258e0271031 100644 --- a/pandas/io/formats/xml.py +++ b/pandas/io/formats/xml.py @@ -299,7 +299,6 @@ def build_elems(self, d: dict[str, Any], elem_row: Any) -> None: raise AbstractMethodError(self) def _build_elems(self, sub_element_cls, d: dict[str, Any], elem_row: Any) -> None: - if not self.elem_cols: return diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 1494b11125319..bdc070d04bd69 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -145,7 +145,6 @@ def to_json( storage_options: StorageOptions = None, mode: Literal["a", "w"] = "w", ) -> str | None: - if not index and orient not in ["split", "table"]: raise ValueError( "'index=False' is only valid when 'orient' is 'split' or 'table'" @@ -826,7 +825,6 @@ def __init__( use_nullable_dtypes: bool = False, engine: JSONEngine = "ujson", ) -> None: - self.orient = orient self.typ = typ self.dtype = dtype @@ -1216,7 +1214,6 @@ def _try_convert_data( # Fall through for conversion later on return data, True elif data.dtype == "object": - # try float try: data = data.astype("float64") @@ -1224,9 +1221,7 @@ def _try_convert_data( pass if data.dtype.kind == "f": - if data.dtype != "float64": - # coerce floats to 64 try: data = data.astype("float64") @@ -1235,7 +1230,6 @@ def _try_convert_data( # don't coerce 0-len data if len(data) and data.dtype in ("float", "object"): - # coerce ints if we can try: new_data = data.astype("int64") @@ -1246,7 +1240,6 @@ def _try_convert_data( # coerce ints to 64 if data.dtype == "int": - # coerce floats to 64 try: data = data.astype("int64") @@ -1332,7 +1325,6 @@ class FrameParser(Parser): _split_keys = ("columns", "index", "data") def _parse(self) -> None: - json = self.json orient = self.orient @@ -1389,7 +1381,6 @@ def _process_converter(self, f, filt=None) -> None: new_obj[i] = c if needs_new_obj: - # possibly handle dup columns new_frame = DataFrame(new_obj, index=obj.index) new_frame.columns = obj.columns diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 49e0eea8259db..11706b671e1b1 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -117,7 +117,6 @@ def _get_path_or_handle( class BaseImpl: @staticmethod def validate_dataframe(df: DataFrame) -> None: - if not isinstance(df, DataFrame): raise ValueError("to_parquet only supports IO with DataFrames") @@ -228,7 +227,6 @@ def read( dtype_backend = get_option("mode.dtype_backend") to_pandas_kwargs = {} if use_nullable_dtypes: - if dtype_backend == "pandas": from pandas.io._util import _arrow_dtype_mapping diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 6d2f569ddb753..83064d87069c1 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -104,7 +104,6 @@ class BadLineHandleMethod(Enum): _first_chunk: bool def __init__(self, kwds) -> None: - self.names = kwds.get("names") self.orig_names: Sequence[Hashable] | None = None @@ -453,7 +452,6 @@ def _agg_index(self, index, try_parse_dates: bool = True) -> Index: converters = self._clean_mapping(self.converters) for i, arr in enumerate(index): - if try_parse_dates and self._should_parse_dates(i): arr = self._date_conv(arr) diff --git a/pandas/io/parsers/c_parser_wrapper.py b/pandas/io/parsers/c_parser_wrapper.py index 7842a3d18166d..dbf36b830971b 100644 --- a/pandas/io/parsers/c_parser_wrapper.py +++ b/pandas/io/parsers/c_parser_wrapper.py @@ -166,7 +166,6 @@ def __init__(self, src: ReadCsvBuffer[str], **kwds) -> None: if self._reader.leading_cols == 0 and is_index_col( self.index_col # type: ignore[has-type] ): - self._name_processed = True ( index_names, diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 62a4e80147780..263966269c0fa 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -476,7 +476,6 @@ def _infer_columns( this_columns[i] = col counts[col] = cur_count + 1 elif have_mi_columns: - # if we have grabbed an extra line, but its not in our # format so save in the buffer, and create an blank extra # line for the rest of the parsing code @@ -677,7 +676,6 @@ def _check_for_bom(self, first_row: list[Scalar]) -> list[Scalar]: new_row += first_row_bom[end + 1 :] else: - # No quotation so just remove BOM from first element new_row = first_row_bom[1:] @@ -1008,7 +1006,6 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]: and self.index_col is not False # type: ignore[comparison-overlap] and self.usecols is None ): - footers = self.skipfooter if self.skipfooter else 0 bad_lines = [] @@ -1016,7 +1013,7 @@ def _rows_to_cols(self, content: list[list[Scalar]]) -> list[np.ndarray]: content_len = len(content) content = [] - for (i, _content) in iter_content: + for i, _content in iter_content: actual_len = len(_content) if actual_len > col_len: @@ -1110,7 +1107,6 @@ def _get_lines(self, rows: int | None = None) -> list[list[Scalar]]: new_rows = [] try: if rows is not None: - rows_to_skip = 0 if self.skiprows is not None and self.pos is not None: # Only read additional rows if pos is in skiprows diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py index da998371788d5..4fedb74518f20 100644 --- a/pandas/io/pickle.py +++ b/pandas/io/pickle.py @@ -187,7 +187,6 @@ def read_pickle( is_text=False, storage_options=storage_options, ) as handles: - # 1) try standard library Pickle # 2) try pickle_compat (older pandas version) to handle subclass changes # 3) try pickle_compat with latin-1 encoding upon a UnicodeDecodeError diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 64480a7da3326..4a95daafd82a9 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -554,7 +554,6 @@ def __init__( fletcher32: bool = False, **kwargs, ) -> None: - if "format" in kwargs: raise ValueError("format is not a defined argument for HDFStore") @@ -1033,7 +1032,6 @@ def select_as_multiple( axis = {t.non_index_axes[0][0] for t in _tbls}.pop() def func(_start, _stop, _where): - # retrieve the objs, _where is always passed as a set of # coordinates here objs = [ @@ -1554,14 +1552,12 @@ def copy( for k in keys: s = self.get_storer(k) if s is not None: - if k in new_store: if overwrite: new_store.remove(k) data = self.select(k) if isinstance(s, Table): - index: bool | list[str] = False if propindexes: index = [a.name for a in s.axes if a.is_indexed] @@ -1978,7 +1974,6 @@ def __init__( meta=None, metadata=None, ) -> None: - if not isinstance(name, str): raise ValueError("`name` must be a str.") @@ -2179,7 +2174,6 @@ def update_info(self, info) -> None: if there is a conflict raise/warn as needed """ for key in self._info_fields: - value = getattr(self, key, None) idx = info.setdefault(self.name, {}) @@ -2529,7 +2523,6 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): ) else: - try: converted = converted.astype(dtype, copy=False) except TypeError: @@ -3187,7 +3180,6 @@ def read( axes = [] for i in range(self.ndim): - _start, _stop = (start, stop) if i == select_axis else (None, None) ax = self.read_index(f"axis{i}", start=_start, stop=_stop) axes.append(ax) @@ -3196,7 +3188,6 @@ def read( dfs = [] for i in range(self.nblocks): - blk_items = self.read_index(f"block{i}_items") values = self.read_array(f"block{i}_values", start=_start, stop=_stop) @@ -3340,7 +3331,6 @@ def validate(self, other) -> None: sv = getattr(self, c, None) ov = getattr(other, c, None) if sv != ov: - # show the error for the specific axes # Argument 1 to "enumerate" has incompatible type # "Optional[Any]"; expected "Iterable[Any]" [arg-type] @@ -3531,7 +3521,6 @@ def validate_min_itemsize(self, min_itemsize) -> None: q = self.queryables() for k in min_itemsize: - # ok, apply generally if k == "values": continue @@ -3862,7 +3851,6 @@ def _create_axes( indexer = len(new_non_index_axes) # i.e. 0 exist_axis = self.non_index_axes[indexer][1] if not array_equivalent(np.array(append_axis), np.array(exist_axis)): - # ahah! -> reindex if array_equivalent( np.array(sorted(append_axis)), np.array(sorted(exist_axis)) @@ -3914,7 +3902,6 @@ def _create_axes( # add my values vaxes = [] for i, (blk, b_items) in enumerate(zip(blocks, blk_items)): - # shape of the data column are the indexable axes klass = DataCol name = None @@ -4096,7 +4083,6 @@ def process_axes(self, obj, selection: Selection, columns=None) -> DataFrame: obj = _reindex_axis(obj, axis, labels, columns) def process_filter(field, filt, op): - for axis_name in obj._AXIS_ORDERS: axis_number = obj._get_axis_number(axis_name) axis_values = obj._get_axis(axis_name) @@ -4104,7 +4090,6 @@ def process_filter(field, filt, op): # see if the field is the name of an axis if field == axis_name: - # if we have a multi-index, then need to include # the levels if self.is_multi_index: @@ -4115,7 +4100,6 @@ def process_filter(field, filt, op): # this might be the name of a file IN an axis elif field in axis_values: - # we need to filter on this dimension values = ensure_index(getattr(obj, field).values) filt = ensure_index(filt) @@ -4306,7 +4290,6 @@ def write( # type: ignore[override] a.validate_names() if not table.is_exists: - # create the table options = table.create_description( complib=complib, @@ -4437,7 +4420,6 @@ def write_data_chunk( self.table.flush() def delete(self, where=None, start: int | None = None, stop: int | None = None): - # delete all rows (and return the nrows) if where is None or not len(where): if start is None and stop is None: @@ -4465,7 +4447,6 @@ def delete(self, where=None, start: int | None = None, stop: int | None = None): ln = len(sorted_series) if ln: - # construct groups of consecutive rows diff = sorted_series.diff() groups = list(diff[diff > 1].index) @@ -4523,7 +4504,6 @@ def read( start: int | None = None, stop: int | None = None, ): - # validate the version self.validate_version(where) @@ -4627,7 +4607,6 @@ def read( start: int | None = None, stop: int | None = None, ) -> Series: - is_multi_index = self.is_multi_index if columns is not None and is_multi_index: assert isinstance(self.levels, list) # needed for mypy @@ -4760,7 +4739,6 @@ def read( start: int | None = None, stop: int | None = None, ): - df = super().read(where=where, columns=columns, start=start, stop=stop) df = df.set_index(self.levels) @@ -4897,7 +4875,6 @@ def _convert_index(name: str, index: Index, encoding: str, errors: str) -> Index name, converted, "date", _tables().Time32Col(), index_name=index_name ) elif inferred_type == "string": - converted = _convert_string_array(values, encoding, errors) itemsize = converted.dtype.itemsize return IndexCol( @@ -4954,7 +4931,6 @@ def _maybe_convert_for_string_atom( errors, columns: list[str], ): - if bvalues.dtype != object: return bvalues @@ -4982,7 +4958,6 @@ def _maybe_convert_for_string_atom( # see if we have a valid string type inferred_type = lib.infer_dtype(data, skipna=False) if inferred_type != "string": - # we cannot serialize this data, so report an exception on a column # by column basis @@ -5073,7 +5048,6 @@ def _unconvert_string_array( data = np.asarray(data.ravel(), dtype=object) if len(data): - itemsize = libwriters.max_len_string_array(ensure_object(data)) dtype = f"U{itemsize}" @@ -5223,7 +5197,6 @@ def __init__( self.coordinates = None if is_list_like(where): - # see if we have a passed coordinate like with suppress(ValueError): inferred = lib.infer_dtype(where, skipna=False) @@ -5246,7 +5219,6 @@ def __init__( self.coordinates = where if self.coordinates is None: - self.terms = self.generate(where) # create the numexpr & the filter diff --git a/pandas/io/sas/sas7bdat.py b/pandas/io/sas/sas7bdat.py index fd47396347ff9..7fd93e7ed0e23 100644 --- a/pandas/io/sas/sas7bdat.py +++ b/pandas/io/sas/sas7bdat.py @@ -170,7 +170,6 @@ def __init__( convert_header_text: bool = True, compression: CompressionOptions = "infer", ) -> None: - self.index = index self.convert_dates = convert_dates self.blank_missing = blank_missing @@ -241,7 +240,6 @@ def close(self) -> None: self.handles.close() def _get_properties(self) -> None: - # Check magic number self._path_or_buf.seek(0) self._cached_page = self._path_or_buf.read(288) @@ -446,7 +444,6 @@ def _process_page_metadata(self) -> None: subheader_processor(subheader_offset, subheader_length) def _process_rowsize_subheader(self, offset: int, length: int) -> None: - int_len = self._int_length lcs_offset = offset lcp_offset = offset @@ -491,7 +488,6 @@ def _process_subheader_counts(self, offset: int, length: int) -> None: pass def _process_columntext_subheader(self, offset: int, length: int) -> None: - offset += self._int_length text_block_size = self._read_uint(offset, const.text_block_size_length) @@ -655,7 +651,6 @@ def _process_format_subheader(self, offset: int, length: int) -> None: self.columns.append(col) def read(self, nrows: int | None = None) -> DataFrame: - if (nrows is None) and (self.chunksize is not None): nrows = self.chunksize elif nrows is None: @@ -712,7 +707,6 @@ def _read_next_page(self): return False def _chunk_to_dataframe(self) -> DataFrame: - n = self._current_row_in_chunk_index m = self._current_row_in_file_index ix = range(m - n, m) @@ -720,7 +714,6 @@ def _chunk_to_dataframe(self) -> DataFrame: js, jb = 0, 0 for j in range(self.column_count): - name = self.column_names[j] if self._column_types[j] == b"d": diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index a66910392d788..6767dec6e4528 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -260,7 +260,6 @@ def __init__( chunksize=None, compression: CompressionOptions = "infer", ) -> None: - self._encoding = encoding self._lines_read = 0 self._index = index @@ -468,7 +467,6 @@ def _missing_double(self, vec): @Appender(_read_method_doc) def read(self, nrows: int | None = None) -> pd.DataFrame: - if nrows is None: nrows = self.nobs diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 6764c0578bf7a..4e86166ef512d 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -677,7 +677,6 @@ def read_sql( ) with pandasSQL_builder(con) as pandas_sql: - if isinstance(pandas_sql, SQLiteDatabase): return pandas_sql.read_query( sql, @@ -1033,7 +1032,6 @@ def insert_data(self) -> tuple[list[str], list[np.ndarray]]: def insert( self, chunksize: int | None = None, method: str | None = None ) -> int | None: - # set insert method if method is None: exec_insert = self._execute_insert @@ -1288,7 +1286,6 @@ def _harmonize_columns( pass # this column not in results def _sqlalchemy_type(self, col): - dtype: DtypeArg = self.dtype or {} if is_dict_like(dtype): dtype = cast(dict, dtype) @@ -2429,7 +2426,6 @@ def to_sql( return table.insert(chunksize, method) def has_table(self, name: str, schema: str | None = None) -> bool: - wld = "?" query = f"SELECT name FROM sqlite_master WHERE type='table' AND name={wld};" diff --git a/pandas/io/stata.py b/pandas/io/stata.py index fd6ffe5c165ab..155f989eb0634 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -352,7 +352,6 @@ def convert_delta_safe(base, deltas, unit) -> Series: ms = dates conv_dates = convert_delta_safe(base, ms, "ms") elif fmt.startswith(("%tC", "tC")): - warnings.warn( "Encountered %tC format. Leaving in Stata Internal Format.", stacklevel=find_stack_level(), @@ -679,7 +678,6 @@ class StataValueLabel: def __init__( self, catarray: Series, encoding: Literal["latin-1", "utf-8"] = "latin-1" ) -> None: - if encoding not in ("latin-1", "utf-8"): raise ValueError("Only latin-1 and utf-8 are supported.") self.labname = catarray.name @@ -809,7 +807,6 @@ def __init__( value_labels: dict[float, str], encoding: Literal["latin-1", "utf-8"] = "latin-1", ) -> None: - if encoding not in ("latin-1", "utf-8"): raise ValueError("Only latin-1 and utf-8 are supported.") @@ -957,7 +954,6 @@ def get_base_missing_value(cls, dtype: np.dtype) -> float: class StataParser: def __init__(self) -> None: - # type code. # -------------------- # str1 1 = 0x01 @@ -1294,7 +1290,6 @@ def _read_new_header(self) -> None: def _get_dtypes( self, seek_vartypes: int ) -> tuple[list[int | str], list[str | np.dtype]]: - self.path_or_buf.seek(seek_vartypes) raw_typlist = [ struct.unpack(self.byteorder + "H", self.path_or_buf.read(2))[0] @@ -1868,7 +1863,6 @@ def _insert_strls(self, data: DataFrame) -> DataFrame: return data def _do_select_columns(self, data: DataFrame, columns: Sequence[str]) -> DataFrame: - if not self._column_selector_set: column_set = set(columns) if len(column_set) != len(columns): @@ -2024,7 +2018,6 @@ def read_stata( compression: CompressionOptions = "infer", storage_options: StorageOptions = None, ) -> DataFrame | StataReader: - reader = StataReader( filepath_or_buffer, convert_dates=convert_dates, @@ -2643,7 +2636,6 @@ def write_file(self) -> None: is_text=False, storage_options=self.storage_options, ) as self.handles: - if self.handles.compression["method"] is not None: # ZipFile creates a file (with the same name) for each write call. # Write it first into a buffer and then write the buffer to the ZipFile. diff --git a/pandas/io/xml.py b/pandas/io/xml.py index 3ee4e64faf75c..90d67ac45d4fd 100644 --- a/pandas/io/xml.py +++ b/pandas/io/xml.py @@ -580,7 +580,6 @@ def parse_data(self) -> list[dict[str, str | None]]: return xml_dicts def _validate_path(self) -> list[Any]: - msg = ( "xpath does not return any nodes or attributes. " "Be sure to specify in `xpath` the parent nodes of " diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 5060e48484fb5..e2f30da1b839c 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -314,7 +314,6 @@ def boxplot( return_type=None, **kwds, ): - import matplotlib.pyplot as plt # validate return_type: diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 69f46a333503d..9b0fe99e2d61e 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -371,7 +371,6 @@ def _get_unit(self): class MilliSecondLocator(mdates.DateLocator): - UNIT = 1.0 / (24 * 3600 * 1000) def __init__(self, tz) -> None: @@ -1071,7 +1070,6 @@ def set_locs(self, locs) -> None: self._set_default_format(vmin, vmax) def __call__(self, x, pos: int = 0) -> str: - if self.formatdict is None: return "" else: diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index fd737cdcb967f..455dd1f75b225 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -147,7 +147,6 @@ def __init__( column: IndexLabel | None = None, **kwds, ) -> None: - import matplotlib.pyplot as plt self.data = data @@ -186,7 +185,6 @@ def __init__( self.subplots = self._validate_subplots_kwarg(subplots) if sharex is None: - # if by is defined, subplots are used and sharex should be False if ax is None and by is None: self.sharex = True @@ -428,7 +426,6 @@ def _iter_data(self, data=None, keep_index: bool = False, fillna=None): @property def nseries(self) -> int: - # When `by` is explicitly assigned, grouped data size will be defined, and # this will determine number of subplots to have, aka `self.nseries` if self.data.ndim == 1: @@ -718,7 +715,7 @@ def _adorn_subplots(self): f"number of columns = {self.nseries}" ) - for (ax, title) in zip(self.axes, self.title): + for ax, title in zip(self.axes, self.title): ax.set_title(title) else: self.fig.suptitle(self.title) @@ -1025,7 +1022,6 @@ def match_labels(data, e): # key-matched DataFrame if isinstance(err, ABCDataFrame): - err = match_labels(self.data, err) # key-matched dict elif isinstance(err, dict): @@ -1392,7 +1388,6 @@ def _make_plot(self) -> None: self._append_legend_handles_labels(newlines[0], label) if self._is_ts_plot(): - # reset of xlim should be used for ts data # TODO: GH28021, should find a way to change view limit on xaxis lines = get_all_lines(ax) @@ -1552,7 +1547,6 @@ def _plot( # type: ignore[override] is_errorbar: bool = False, **kwds, ): - if column_num == 0: cls._initialize_stacker(ax, stacking_id, len(y)) y_values = cls._get_stacked_values(ax, stacking_id, y, kwds["label"]) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index d20f69cc0a8de..bc8e6ed753d99 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -277,7 +277,6 @@ def _grouped_plot( ax=None, **kwargs, ): - if figsize == "default": # allowed to specify mpl default with 'default' raise ValueError( diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 9c054b5f03198..291a6dff9650d 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -194,7 +194,6 @@ def normalize(series): ax.add_patch(patches.Circle((0.0, 0.0), radius=1.0, facecolor="none")) for xy, name in zip(s, df.columns): - ax.add_patch(patches.Circle(xy, radius=0.025, facecolor="gray")) if xy[0] < 0.0 and xy[1] < 0.0: @@ -297,7 +296,6 @@ def bootstrap_plot( samples: int = 500, **kwds, ) -> Figure: - import matplotlib.pyplot as plt # TODO: is the failure mentioned below still relevant? diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 366fcf3442ed6..8e21b2c691185 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -306,7 +306,6 @@ def format_dateaxis(subplot, freq, index) -> None: # Note: DatetimeIndex does not use this # interface. DatetimeIndex uses matplotlib.date directly if isinstance(index, ABCPeriodIndex): - majlocator = TimeSeries_DateLocator( freq, dynamic_mode=True, minor_locator=False, plot_obj=subplot ) diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index e448e1bce9146..94430e23b054a 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -187,7 +187,6 @@ class TestPDApi(Base): ] def test_api(self): - checkthese = ( self.public_lib + self.private_lib diff --git a/pandas/tests/api/test_types.py b/pandas/tests/api/test_types.py index 0f89549f2ab03..fbaa6e7e18bca 100644 --- a/pandas/tests/api/test_types.py +++ b/pandas/tests/api/test_types.py @@ -6,7 +6,6 @@ class TestTypes(Base): - allowed = [ "is_any_real_numeric_dtype", "is_bool", @@ -55,11 +54,9 @@ class TestTypes(Base): dtypes = ["CategoricalDtype", "DatetimeTZDtype", "PeriodDtype", "IntervalDtype"] def test_types(self): - self.check(types, self.allowed + self.dtypes + self.deprecated) def test_deprecated_from_api_types(self): - for t in self.deprecated: with tm.assert_produces_warning(FutureWarning): getattr(types, t)(1) diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index a0e667dc8f243..e0be8f3e7ce04 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -379,7 +379,6 @@ def test_apply_differently_indexed(): def test_apply_bug(): - # GH 6125 positions = DataFrame( [ @@ -753,7 +752,6 @@ def non_reducing_function(row): def test_applymap_function_runs_once(): - df = DataFrame({"a": [1, 2, 3]}) values = [] # Save values function is applied to @@ -1069,7 +1067,6 @@ def test_agg_transform(axis, float_frame): other_axis = 1 if axis in {0, "index"} else 0 with np.errstate(all="ignore"): - f_abs = np.abs(float_frame) f_sqrt = np.sqrt(float_frame) @@ -1260,7 +1257,6 @@ def test_agg_reduce(axis, float_frame): def test_nuiscance_columns(): - # GH 15015 df = DataFrame( { @@ -1298,7 +1294,6 @@ def test_nuiscance_columns(): @pytest.mark.parametrize("how", ["agg", "apply"]) def test_non_callable_aggregates(how): - # GH 16405 # 'size' is a property of frame/series # validate that this is working diff --git a/pandas/tests/apply/test_invalid_arg.py b/pandas/tests/apply/test_invalid_arg.py index 101e7be70e691..294693df7340a 100644 --- a/pandas/tests/apply/test_invalid_arg.py +++ b/pandas/tests/apply/test_invalid_arg.py @@ -112,7 +112,6 @@ def test_series_nested_renamer(renamer): def test_apply_dict_depr(): - tsdf = DataFrame( np.random.randn(10, 3), columns=["A", "B", "C"], @@ -125,7 +124,6 @@ def test_apply_dict_depr(): @pytest.mark.parametrize("method", ["agg", "transform"]) def test_dict_nested_renaming_depr(method): - df = DataFrame({"A": range(5), "B": 5}) # nested renaming diff --git a/pandas/tests/apply/test_series_apply.py b/pandas/tests/apply/test_series_apply.py index 30f040b4197eb..7b8a6204cf2c6 100644 --- a/pandas/tests/apply/test_series_apply.py +++ b/pandas/tests/apply/test_series_apply.py @@ -258,7 +258,6 @@ def test_transform(string_series): # transforming functions with np.errstate(all="ignore"): - f_sqrt = np.sqrt(string_series) f_abs = np.abs(string_series) diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py index add7b5c77ef65..64f93e48b255c 100644 --- a/pandas/tests/apply/test_str.py +++ b/pandas/tests/apply/test_str.py @@ -258,7 +258,6 @@ def test_transform_groupby_kernel_series(request, string_series, op): @pytest.mark.parametrize("op", frame_transform_kernels) def test_transform_groupby_kernel_frame(request, axis, float_frame, op): - if op == "ngroup": request.node.add_marker( pytest.mark.xfail(raises=ValueError, reason="ngroup not valid for NDFrame") diff --git a/pandas/tests/arithmetic/conftest.py b/pandas/tests/arithmetic/conftest.py index d2fb384c91c39..7dd5169202ba4 100644 --- a/pandas/tests/arithmetic/conftest.py +++ b/pandas/tests/arithmetic/conftest.py @@ -20,6 +20,7 @@ def switch_numexpr_min_elements(request): # ------------------------------------------------------------------ + # doctest with +SKIP for one fixture fails during setup with # 'DoctestItem' object has no attribute 'callspec' # due to switch_numexpr_min_elements fixture diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 213acdadfddbc..8bbb0452e822f 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -393,7 +393,6 @@ def test_dt64_compare_datetime_scalar(self, datetimelike, op, expected): class TestDatetimeIndexComparisons: - # TODO: moved from tests.indexes.test_base; parametrize and de-duplicate def test_comparators(self, comparison_op): index = tm.makeDateIndex(100) @@ -442,7 +441,6 @@ def test_dti_cmp_datetimelike(self, other, tz_naive_fixture): @pytest.mark.parametrize("dtype", [None, object]) def test_dti_cmp_nat(self, dtype, box_with_array): - left = DatetimeIndex([Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")]) right = DatetimeIndex([NaT, NaT, Timestamp("2011-01-03")]) @@ -505,7 +503,6 @@ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): # Check pd.NaT is handles as the same as np.nan with tm.assert_produces_warning(None): for idx1, idx2 in cases: - result = idx1 < idx2 expected = np.array([True, False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected) @@ -926,7 +923,6 @@ def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture): other - obj def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): - tz = tz_naive_fixture dti = date_range("2016-01-01", periods=3, tz=tz) tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) @@ -1040,7 +1036,6 @@ def test_dt64arr_naive_sub_dt64ndarray(self, box_with_array): def test_dt64arr_aware_sub_dt64ndarray_raises( self, tz_aware_fixture, box_with_array ): - tz = tz_aware_fixture dti = date_range("2016-01-01", periods=3, tz=tz) dt64vals = dti.values @@ -1228,7 +1223,6 @@ def test_dt64_mul_div_numeric_invalid(self, one, dt64_series, box_with_array): class TestDatetime64DateOffsetArithmetic: - # ------------------------------------------------------------- # Tick DateOffsets @@ -1783,7 +1777,6 @@ def test_empty_series_add_sub(self, box_with_array): b - a def test_operators_datetimelike(self): - # ## timedelta64 ### td1 = Series([timedelta(minutes=5, seconds=3)] * 3) td1.iloc[2] = np.nan diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 1aa3df64cc37b..eaf80f4768458 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -795,7 +795,6 @@ def test_operators_frame(self): # de-duplication with test_modulo above def test_modulo2(self): with np.errstate(all="ignore"): - # GH#3590, modulo as ints p = pd.DataFrame({"first": [3, 4, 5, 8], "second": [0, 0, 0, 3]}) result = p["first"] % p["second"] diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 75f27d38c8fd8..7a079ae7795e6 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -42,7 +42,6 @@ class TestPeriodArrayLikeComparisons: @pytest.mark.parametrize("other", ["2017", Period("2017", freq="D")]) def test_eq_scalar(self, other, box_with_array): - idx = PeriodIndex(["2017", "2017", "2018"], freq="D") idx = tm.box_expected(idx, box_with_array) xbox = get_upcast_box(idx, other, True) @@ -1463,7 +1462,6 @@ def test_pi_ops_nat(self): self._check(idx + 3, lambda x: np.subtract(x, 3), idx) def test_pi_ops_array_int(self): - idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" ) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 65d39f7c7b9fb..33fc63938407c 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -353,7 +353,6 @@ def test_subtraction_ops(self): tm.assert_index_equal(result, expected) def test_subtraction_ops_with_tz(self, box_with_array): - # check that dt/dti subtraction ops with tz are validated dti = pd.date_range("20130101", periods=3) dti = tm.box_expected(dti, box_with_array) diff --git a/pandas/tests/arrays/categorical/test_api.py b/pandas/tests/arrays/categorical/test_api.py index 450581f89d735..aa02585ee81a5 100644 --- a/pandas/tests/arrays/categorical/test_api.py +++ b/pandas/tests/arrays/categorical/test_api.py @@ -429,7 +429,6 @@ def test_describe(self, factor): class TestPrivateCategoricalAPI: def test_codes_immutable(self): - # Codes should be read only c = Categorical(["a", "b", "c", "a", np.nan]) exp = np.array([0, 1, 2, 0, -1], dtype="int8") diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 36c06a77b7822..6cb0e31eb0a5d 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -110,7 +110,6 @@ def test_constructor_tuples_datetimes(self): tm.assert_index_equal(result.categories, expected) def test_constructor_unsortable(self): - # it works! arr = np.array([1, 2, 3, datetime.now()], dtype="O") factor = Categorical(arr, ordered=False) @@ -134,7 +133,6 @@ def test_constructor_interval(self): tm.assert_index_equal(result.categories, ii) def test_constructor(self): - exp_arr = np.array(["a", "b", "c", "a", "b", "c"], dtype=np.object_) c1 = Categorical(exp_arr) tm.assert_numpy_array_equal(c1.__array__(), exp_arr) @@ -263,7 +261,6 @@ def test_constructor_not_sequence(self): Categorical(["a", "b"], categories="a") def test_constructor_with_null(self): - # Cannot have NaN in categories msg = "Categorical categories cannot be null" with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py index 7447daadbdd48..c905916772bff 100644 --- a/pandas/tests/arrays/categorical/test_dtypes.py +++ b/pandas/tests/arrays/categorical/test_dtypes.py @@ -16,7 +16,6 @@ class TestCategoricalDtypes: def test_categories_match_up_to_permutation(self): - # test dtype comparisons between cats c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False) @@ -98,7 +97,6 @@ def test_set_dtype_no_overlap(self): tm.assert_categorical_equal(result, expected) def test_codes_dtypes(self): - # GH 8453 result = Categorical(["foo", "bar", "baz"]) assert result.codes.dtype == "int8" diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index d42b73b7c0020..635b331c14ac9 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -32,7 +32,6 @@ def test_getitem(self, factor): tm.assert_numpy_array_equal(subf._codes, np.array([2, 2, 2], dtype=np.int8)) def test_setitem(self, factor): - # int/positional c = factor.copy() c[0] = "b" @@ -104,7 +103,6 @@ def test_setitem_tuple(self): assert cat[1] == (0, 1) def test_setitem_listlike(self): - # GH#9469 # properly coerce the input indexers np.random.seed(1) @@ -131,7 +129,6 @@ def test_getitem_slice(self): tm.assert_categorical_equal(sliced, expected) def test_getitem_listlike(self): - # GH 9469 # properly coerce the input indexers np.random.seed(1) @@ -367,6 +364,7 @@ def non_coercible_categorical(monkeypatch): ValueError When Categorical.__array__ is called. """ + # TODO(Categorical): identify other places where this may be # useful and move to a conftest.py def array(self, dtype=None): diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py index fb5330a9665ff..95748f619172b 100644 --- a/pandas/tests/arrays/categorical/test_missing.py +++ b/pandas/tests/arrays/categorical/test_missing.py @@ -37,7 +37,6 @@ def test_na_flags_int_categories(self): tm.assert_numpy_array_equal(isna(cat), labels == -1) def test_nan_handling(self): - # Nans are represented as -1 in codes c = Categorical(["a", "b", np.nan, "a"]) tm.assert_index_equal(c.categories, Index(["a", "b"])) diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 70636d633b674..bfe65f8bf3c29 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -345,7 +345,6 @@ def test_compare_unordered_different_order(self): assert not a.equals(b) def test_numeric_like_ops(self): - df = DataFrame({"value": np.random.randint(0, 10000, 100)}) labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)] cat_labels = Categorical(labels, labels) diff --git a/pandas/tests/arrays/categorical/test_repr.py b/pandas/tests/arrays/categorical/test_repr.py index e8b43ea98c032..d31489aba5a6f 100644 --- a/pandas/tests/arrays/categorical/test_repr.py +++ b/pandas/tests/arrays/categorical/test_repr.py @@ -83,7 +83,6 @@ def test_unicode_print(self): # unicode option should not affect to Categorical, as it doesn't care # the repr width with option_context("display.unicode.east_asian_width", True): - c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20) expected = """['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう'] Length: 60 diff --git a/pandas/tests/arrays/categorical/test_sorting.py b/pandas/tests/arrays/categorical/test_sorting.py index 4f65c8dfaf0be..ae527065b3fb9 100644 --- a/pandas/tests/arrays/categorical/test_sorting.py +++ b/pandas/tests/arrays/categorical/test_sorting.py @@ -41,7 +41,6 @@ def test_numpy_argsort(self): np.argsort(c, order="C") def test_sort_values(self): - # unordered cats are sortable cat = Categorical(["a", "b", "b", "a"], ordered=False) cat.sort_values() diff --git a/pandas/tests/arrays/floating/test_arithmetic.py b/pandas/tests/arrays/floating/test_arithmetic.py index f207540a76f2a..056c22d8c1131 100644 --- a/pandas/tests/arrays/floating/test_arithmetic.py +++ b/pandas/tests/arrays/floating/test_arithmetic.py @@ -123,7 +123,6 @@ def test_arith_zero_dim_ndarray(other): def test_error_invalid_values(data, all_arithmetic_operators): - op = all_arithmetic_operators s = pd.Series(data) ops = getattr(s, op) @@ -179,7 +178,6 @@ def test_error_invalid_values(data, all_arithmetic_operators): def test_cross_type_arithmetic(): - df = pd.DataFrame( { "A": pd.array([1, 2, np.nan], dtype="Float64"), diff --git a/pandas/tests/arrays/floating/test_concat.py b/pandas/tests/arrays/floating/test_concat.py index dcb021045c6a7..2174a834aa959 100644 --- a/pandas/tests/arrays/floating/test_concat.py +++ b/pandas/tests/arrays/floating/test_concat.py @@ -13,7 +13,6 @@ ], ) def test_concat_series(to_concat_dtypes, result_dtype): - result = pd.concat([pd.Series([1, 2, pd.NA], dtype=t) for t in to_concat_dtypes]) expected = pd.concat([pd.Series([1, 2, pd.NA], dtype=object)] * 2).astype( result_dtype diff --git a/pandas/tests/arrays/floating/test_repr.py b/pandas/tests/arrays/floating/test_repr.py index a8868fd93747a..ea2cdd4fab86a 100644 --- a/pandas/tests/arrays/floating/test_repr.py +++ b/pandas/tests/arrays/floating/test_repr.py @@ -41,7 +41,6 @@ def test_repr_array_long(): def test_frame_repr(data_missing): - df = pd.DataFrame({"A": data_missing}) result = repr(df) expected = " A\n0 <NA>\n1 0.1" diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 092cbc6c7997f..a6e91b05efbe9 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -173,7 +173,6 @@ def test_numpy_zero_dim_ndarray(other): def test_error_invalid_values(data, all_arithmetic_operators): - op = all_arithmetic_operators s = pd.Series(data) ops = getattr(s, op) @@ -262,7 +261,6 @@ def test_arithmetic_conversion(all_arithmetic_operators, other): def test_cross_type_arithmetic(): - df = pd.DataFrame( { "A": pd.Series([1, 2, np.nan], dtype="Int64"), diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py index 629b104dc1424..f50b4cfd0b520 100644 --- a/pandas/tests/arrays/integer/test_dtypes.py +++ b/pandas/tests/arrays/integer/test_dtypes.py @@ -225,7 +225,6 @@ def test_astype_dt64(): def test_construct_cast_invalid(dtype): - msg = "cannot safely" arr = [1.2, 2.3, 3.7] with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/arrays/integer/test_repr.py b/pandas/tests/arrays/integer/test_repr.py index 35d07bda9a333..168210eed5d06 100644 --- a/pandas/tests/arrays/integer/test_repr.py +++ b/pandas/tests/arrays/integer/test_repr.py @@ -61,7 +61,6 @@ def test_repr_array_long(): def test_frame_repr(data_missing): - df = pd.DataFrame({"A": data_missing}) result = repr(df) expected = " A\n0 <NA>\n1 1" diff --git a/pandas/tests/arrays/masked_shared.py b/pandas/tests/arrays/masked_shared.py index 6174ae0a3c19b..831fc64512b98 100644 --- a/pandas/tests/arrays/masked_shared.py +++ b/pandas/tests/arrays/masked_shared.py @@ -11,7 +11,6 @@ class ComparisonOps(BaseOpsUtil): def _compare_other(self, data, op, other): - # array result = pd.Series(op(data, other)) expected = pd.Series(op(data._data, other), dtype="boolean") diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index 35d58c29b1e03..018de26ec1f92 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -432,7 +432,6 @@ def test_to_block_index(self): class TestIntIndex: def test_check_integrity(self): - # Too many indices than specified in self.length msg = "Too many indices" diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 7e17efe4e7380..8f9bf83881d3e 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -243,7 +243,6 @@ def test_comparison_methods_scalar_not_string(comparison_op, dtype): def test_comparison_methods_array(comparison_op, dtype): - op_name = f"__{comparison_op.__name__}__" a = pd.array(["a", None, "c"], dtype=dtype) @@ -302,7 +301,6 @@ def test_constructor_nan_like(na): @pytest.mark.parametrize("copy", [True, False]) def test_from_sequence_no_mutate(copy, cls, request): - nan_arr = np.array(["a", np.nan], dtype=object) expected_input = nan_arr.copy() na_arr = np.array(["a", pd.NA], dtype=object) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 362abee1d482a..8db056b8fef58 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -430,7 +430,6 @@ def test_setitem(self): ], ) def test_setitem_object_dtype(self, box, arr1d): - expected = arr1d.copy()[::-1] if expected.dtype.kind in ["m", "M"]: expected = expected._with_freq(None) diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 8bd26a7b0b4c7..9374b232f3cd2 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -99,7 +99,6 @@ def _eval_single_bin(lhs, cmp1, rhs, engine): ids=["DataFrame", "Series", "SeriesNaN", "DataFrameNaN", "float"], ) def lhs(request): - nan_df1 = DataFrame(np.random.rand(10, 5)) nan_df1[nan_df1 > 0.5] = np.nan @@ -179,7 +178,6 @@ def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser): @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS) def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser): if parser == "python" and op in ["in", "not in"]: - msg = "'(In|NotIn)' nodes are not implemented" with pytest.raises(NotImplementedError, match=msg): ex = f"~(lhs {op} rhs)" @@ -754,7 +752,6 @@ def should_warn(*args): class TestAlignment: - index_types = ["i", "s", "dt"] lhs_index_types = index_types + ["s"] # 'p' @@ -805,7 +802,6 @@ def test_frame_comparison(self, engine, parser, r_idx_type, c_idx_type): @pytest.mark.parametrize("r2", index_types) @pytest.mark.parametrize("c2", index_types) def test_medium_complex_frame_alignment(self, engine, parser, r1, c1, r2, c2): - with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) @@ -897,7 +893,6 @@ def test_basic_series_frame_alignment( def test_series_frame_commutativity( self, engine, parser, index_name, op, r_idx_type, c_idx_type ): - with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) @@ -1723,7 +1718,6 @@ def test_disallowed_nodes(engine, parser): inst = VisitorClass("x + 1", engine, parser) for ops in VisitorClass.unsupported_nodes: - msg = "nodes are not implemented" with pytest.raises(NotImplementedError, match=msg): getattr(inst, ops)() @@ -1895,7 +1889,6 @@ def test_set_inplace(using_copy_on_write): class TestValidate: @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) def test_validate_bool_args(self, value): - msg = 'For argument "inplace" expected type bool, received type' with pytest.raises(ValueError, match=msg): pd.eval("2+2", inplace=value) diff --git a/pandas/tests/config/test_config.py b/pandas/tests/config/test_config.py index 8a2d53313702d..aad42b27cb80b 100644 --- a/pandas/tests/config/test_config.py +++ b/pandas/tests/config/test_config.py @@ -25,7 +25,6 @@ def clean_config(self, monkeypatch): yield def test_api(self): - # the pandas object exposes the user API assert hasattr(pd, "get_option") assert hasattr(pd, "set_option") diff --git a/pandas/tests/copy_view/test_internals.py b/pandas/tests/copy_view/test_internals.py index 67022e533dbc4..9180bd5a3a426 100644 --- a/pandas/tests/copy_view/test_internals.py +++ b/pandas/tests/copy_view/test_internals.py @@ -11,7 +11,6 @@ @td.skip_array_manager_invalid_test def test_consolidate(using_copy_on_write): - # create unconsolidated DataFrame df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]}) df["c"] = [4, 5, 6] diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index d822cc03c499d..ec9cb7589f1ff 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1188,7 +1188,6 @@ def test_items(using_copy_on_write): # triggered, and we want to make sure it still works then. for i in range(2): for name, ser in df.items(): - assert np.shares_memory(get_array(ser, name), get_array(df, name)) # mutating df triggers a copy-on-write for that column / block diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py index 68deb0972cebb..1848872335518 100644 --- a/pandas/tests/dtypes/cast/test_promote.py +++ b/pandas/tests/dtypes/cast/test_promote.py @@ -218,7 +218,6 @@ def test_maybe_promote_int_with_float(any_int_numpy_dtype, float_numpy_dtype): def test_maybe_promote_float_with_int(float_numpy_dtype, any_int_numpy_dtype): - dtype = np.dtype(float_numpy_dtype) fill_dtype = np.dtype(any_int_numpy_dtype) @@ -260,7 +259,6 @@ def test_maybe_promote_float_with_int(float_numpy_dtype, any_int_numpy_dtype): ], ) def test_maybe_promote_float_with_float(dtype, fill_value, expected_dtype): - dtype = np.dtype(dtype) expected_dtype = np.dtype(expected_dtype) diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index 8ae0f60bfc88e..638cfa9d82bc2 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -35,7 +35,6 @@ def to_numpy_dtypes(dtypes): class TestPandasDtype: - # Passing invalid dtype, both as a string or object, must raise TypeError # Per issue GH15520 @pytest.mark.parametrize("box", [pd.Timestamp, "pd.Timestamp", list]) @@ -122,7 +121,6 @@ def test_period_dtype(self, dtype): @pytest.mark.parametrize("name1,dtype1", list(dtypes.items()), ids=lambda x: str(x)) @pytest.mark.parametrize("name2,dtype2", list(dtypes.items()), ids=lambda x: str(x)) def test_dtype_equal(name1, dtype1, name2, dtype2): - # match equal to self, but not equal to other assert com.is_dtype_equal(dtype1, dtype1) if name1 != name2: diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index d054fb59d8561..590cedeb6b373 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -166,7 +166,6 @@ def test_is_dtype(self, dtype): assert not CategoricalDtype.is_dtype(np.float64) def test_basic(self, dtype): - assert is_categorical_dtype(dtype) factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"]) @@ -336,7 +335,6 @@ def test_equality(self, dtype): assert dtype == "M8[ns, US/Eastern]" def test_basic(self, dtype): - assert is_datetime64tz_dtype(dtype) dr = date_range("20130101", periods=3, tz="US/Eastern") @@ -349,7 +347,6 @@ def test_basic(self, dtype): assert not is_datetime64tz_dtype(1.0) def test_dst(self): - dr1 = date_range("2013-01-01", periods=3, tz="US/Eastern") s1 = Series(dr1, name="A") assert is_datetime64tz_dtype(s1) diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 30b775490e02f..650eb033dcd9e 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -430,7 +430,6 @@ def test_is_names_tuple_fails(ll): def test_is_hashable(): - # all new-style classes are hashable by default class HashableClass: pass @@ -1049,7 +1048,6 @@ def test_mixed_dtypes_remain_object_array(self): ], ) def test_maybe_convert_objects_ea(self, idx): - result = lib.maybe_convert_objects( np.array(idx, dtype=object), convert_period=True, @@ -1059,7 +1057,6 @@ def test_maybe_convert_objects_ea(self, idx): class TestTypeInference: - # Dummy class used for testing with Python objects class Dummy: pass @@ -1264,7 +1261,6 @@ def test_object_empty(self, box, missing, dtype, skipna, expected): assert result == expected def test_datetime(self): - dates = [datetime(2012, 1, x) for x in range(1, 20)] index = Index(dates) assert index.inferred_type == "datetime64" @@ -1533,7 +1529,6 @@ def test_other_dtypes_for_array(self, func): assert not func(arr.reshape(2, 1)) def test_date(self): - dates = [date(2012, 1, day) for day in range(1, 20)] index = Index(dates) assert index.inferred_type == "date" @@ -1561,7 +1556,6 @@ def test_infer_dtype_date_order_invariant(self, values, skipna): assert result == "date" def test_is_numeric_array(self): - assert lib.is_float_array(np.array([1, 2.0])) assert lib.is_float_array(np.array([1, 2.0, np.nan])) assert not lib.is_float_array(np.array([1, 2])) @@ -1618,7 +1612,6 @@ def test_to_object_array_tuples(self): lib.to_object_array_tuples(values) def test_object(self): - # GH 7431 # cannot infer more than this as only a single element arr = np.array([None], dtype="O") @@ -1653,7 +1646,6 @@ def test_is_period(self): assert not lib.is_period(np.nan) def test_categorical(self): - # GH 8974 arr = Categorical(list("abc")) result = lib.infer_dtype(arr, skipna=True) @@ -1686,7 +1678,6 @@ def test_interval(self, asobject): @pytest.mark.parametrize("value", [Timestamp(0), Timedelta(0), 0, 0.0]) def test_interval_mismatched_closed(self, value): - first = Interval(value, value, closed="left") second = Interval(value, value, closed="right") @@ -1738,7 +1729,6 @@ def test_boolean_dtype(self, data, skipna, klass): class TestNumberScalar: def test_is_number(self): - assert is_number(True) assert is_number(1) assert is_number(1.1) @@ -1828,7 +1818,6 @@ def test_is_float(self): assert not is_float(Timedelta("1 days")) def test_is_datetime_dtypes(self): - ts = pd.date_range("20130101", periods=3) tsa = pd.date_range("20130101", periods=3, tz="US/Eastern") @@ -1979,7 +1968,6 @@ def test_datetimeindex_from_empty_datetime64_array(unit): def test_nan_to_nat_conversions(): - df = DataFrame( {"A": np.asarray(range(10), dtype="float64"), "B": Timestamp("20010101")} ) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 1d3514e39cf00..db6c51d0f6991 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -876,7 +876,6 @@ def test_is_matching_na(self, nulls_fixture, nulls_fixture2): assert not libmissing.is_matching_na(left, right) def test_is_matching_na_nan_matches_none(self): - assert not libmissing.is_matching_na(None, np.nan) assert not libmissing.is_matching_na(np.nan, None) diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index 419d1e114bade..24ccedda31f74 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -136,7 +136,6 @@ class BaseComparisonOpsTests(BaseOpsUtil): """Various Series and DataFrame comparison ops methods.""" def _compare_other(self, ser: pd.Series, data, op, other): - if op.__name__ in ["eq", "ne"]: # comparison should match point-wise comparisons result = op(ser, other) diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 6eaa90d7b868a..afeca326a9fd4 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -233,7 +233,6 @@ def _concat_same_type(cls, to_concat): return cls(np.concatenate([x._data for x in to_concat])) def _reduce(self, name: str, *, skipna: bool = True, **kwargs): - if skipna: # If we don't have any NAs, we can ignore skipna if self.isna().any(): diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 90f89d71b15a9..3544d025f0230 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -111,7 +111,6 @@ class TestMissing(base.BaseMissingTests): class Reduce: def check_reduce(self, s, op_name, skipna): - if op_name in ["median", "skew", "kurt", "sem"]: msg = r"decimal does not support the .* operation" with pytest.raises(NotImplementedError, match=msg): diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 681d048f38485..9406c7c2f59c6 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -987,7 +987,6 @@ def test_basic_equals(self, data): class TestBaseArithmeticOps(base.BaseArithmeticOpsTests): - divmod_exc = NotImplementedError def _patch_combine(self, obj, other, op): diff --git a/pandas/tests/extension/test_common.py b/pandas/tests/extension/test_common.py index 62bc250193564..a3c0b328da075 100644 --- a/pandas/tests/extension/test_common.py +++ b/pandas/tests/extension/test_common.py @@ -54,7 +54,6 @@ def test_is_not_extension_array_dtype(self, values): def test_astype(): - arr = DummyArray(np.array([1, 2, 3])) expected = np.array([1, 2, 3], dtype=object) diff --git a/pandas/tests/extension/test_external_block.py b/pandas/tests/extension/test_external_block.py index 13dec96b144ff..1b5b46c6a01bb 100644 --- a/pandas/tests/extension/test_external_block.py +++ b/pandas/tests/extension/test_external_block.py @@ -12,7 +12,6 @@ class CustomBlock(ExtensionBlock): - _holder = np.ndarray # Cannot override final attribute "_can_hold_na" diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index fc7ca41399baf..1ecd279e1f34b 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -112,7 +112,6 @@ def test_fillna_copy_series(self, data_missing, using_copy_on_write): class TestInterface(BasePeriodTests, base.BaseInterfaceTests): - pass diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py index 60cb0f4490705..18bf633d60186 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -29,7 +29,6 @@ def test_from_records_dt64tz_frame(self): tm.assert_frame_equal(res, df) def test_from_records_with_datetimes(self): - # this may fail on certain platforms because of a numpy issue # related GH#6140 if not is_platform_little_endian(): @@ -137,7 +136,6 @@ def test_from_records_sequencelike_empty(self): assert len(result.columns) == 0 def test_from_records_dictlike(self): - # test the dict methods df = DataFrame( { @@ -367,7 +365,6 @@ def test_from_records_columns_not_modified(self): assert columns == original_columns def test_from_records_decimal(self): - tuples = [(Decimal("1.5"),), (Decimal("2.5"),), (None,)] df = DataFrame.from_records(tuples, columns=["a"]) diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py index ad65ea4ee3fed..7880916f66812 100644 --- a/pandas/tests/frame/indexing/test_getitem.py +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -245,7 +245,6 @@ def test_loc_multiindex_columns_one_level(self): class TestGetitemBooleanMask: def test_getitem_bool_mask_categorical_index(self): - df3 = DataFrame( { "A": np.arange(6, dtype="int64"), @@ -375,7 +374,6 @@ def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols): 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" diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 54e30a3355943..efbd7058dc3b0 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -67,7 +67,6 @@ def test_getitem_numeric_should_not_fallback_to_positional(self, any_numeric_dty tm.assert_frame_equal(result, expected, check_exact=True) def test_getitem2(self, float_frame): - df = float_frame.copy() df["$10"] = np.random.randn(len(df)) @@ -90,7 +89,6 @@ def test_setitem_numeric_should_not_fallback_to_positional(self, any_numeric_dty tm.assert_frame_equal(df, expected, check_exact=True) def test_setitem_list(self, float_frame): - float_frame["E"] = "foo" data = float_frame[["A", "B"]] float_frame[["B", "A"]] = data @@ -110,7 +108,6 @@ def test_setitem_list(self, float_frame): 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] @@ -164,7 +161,6 @@ def test_getitem_boolean(self, mixed_float_frame, mixed_int_frame, datetime_fram mixed_float_frame, mixed_int_frame, ]: - data = df._get_numeric_data() bif = df[df > 0] bifw = DataFrame( @@ -185,7 +181,6 @@ def test_getitem_boolean(self, mixed_float_frame, mixed_int_frame, datetime_fram assert bif[c].dtype == df[c].dtype def test_getitem_boolean_casting(self, datetime_frame): - # don't upcast if we don't need to df = datetime_frame.copy() df["E"] = 1 @@ -563,7 +558,6 @@ def test_getitem_setitem_integer_slice_keyerrors(self): def test_fancy_getitem_slice_mixed( self, float_frame, float_string_frame, using_copy_on_write ): - sliced = float_string_frame.iloc[:, -3:] assert sliced["D"].dtype == np.float64 @@ -576,7 +570,6 @@ def test_fancy_getitem_slice_mixed( sliced.loc[:, "C"] = 4.0 if not using_copy_on_write: - assert (float_frame["C"] == 4).all() # with the enforcement of GH#45333 in 2.0, this remains a view @@ -1023,7 +1016,6 @@ def test_iloc_row(self): tm.assert_frame_equal(result, expected) def test_iloc_row_slice_view(self, using_copy_on_write, request): - df = DataFrame(np.random.randn(10, 4), index=range(0, 20, 2)) original = df.copy() @@ -1044,7 +1036,6 @@ def test_iloc_row_slice_view(self, using_copy_on_write, request): tm.assert_series_equal(df[2], exp_col) def test_iloc_col(self): - df = DataFrame(np.random.randn(4, 10), columns=range(0, 20, 2)) result = df.iloc[:, 1] @@ -1523,7 +1514,6 @@ def test_setitem_value_coercing_dtypes(self, indexer, idx): class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame): - df = uint64_frame idx = df["A"].rename("foo") diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py index f67ecf601f838..d084f841f9e19 100644 --- a/pandas/tests/frame/indexing/test_insert.py +++ b/pandas/tests/frame/indexing/test_insert.py @@ -42,7 +42,6 @@ def test_insert(self): assert df.columns.name == "some_name" def test_insert_column_bug_4032(self): - # GH#4032, inserting a column and renaming causing errors df = DataFrame({"b": [1.1, 2.2]}) diff --git a/pandas/tests/frame/indexing/test_set_value.py b/pandas/tests/frame/indexing/test_set_value.py index 7b68566bab225..8d7a5cbcc08e0 100644 --- a/pandas/tests/frame/indexing/test_set_value.py +++ b/pandas/tests/frame/indexing/test_set_value.py @@ -16,7 +16,6 @@ def test_set_value(self, float_frame): assert float_frame[col][idx] == 1 def test_set_value_resize(self, float_frame): - res = float_frame._set_value("foobar", "B", 0) assert res is None assert float_frame.index[-1] == "foobar" diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 62f05cb523b1b..c20db86904d06 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -72,7 +72,6 @@ def test_setitem_list_not_dataframe(self, float_frame): tm.assert_almost_equal(float_frame[["A", "B"]].values, data) def test_setitem_error_msmgs(self): - # GH 7432 df = DataFrame( {"bar": [1, 2, 3], "baz": ["d", "e", "f"]}, @@ -321,7 +320,6 @@ def test_frame_setitem_existing_datetime64_col_other_units(self, unit): assert (df["dates"].values == ex_vals).all() def test_setitem_dt64tz(self, timezone_frame): - df = timezone_frame idx = df["B"].rename("foo") @@ -472,7 +470,6 @@ def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self): 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) @@ -997,7 +994,6 @@ class TestDataFrameSetItemBooleanMask: ids=["dataframe", "array"], ) def test_setitem_boolean_mask(self, mask_type, float_frame): - # Test for issue #18582 df = float_frame.copy() mask = mask_type(df) diff --git a/pandas/tests/frame/indexing/test_take.py b/pandas/tests/frame/indexing/test_take.py index 3b59d3cf10658..a3d13ecd7b98e 100644 --- a/pandas/tests/frame/indexing/test_take.py +++ b/pandas/tests/frame/indexing/test_take.py @@ -8,7 +8,6 @@ def test_take(self, float_frame): # homogeneous order = [3, 1, 2, 0] for df in [float_frame]: - result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected) @@ -21,7 +20,6 @@ def test_take(self, float_frame): # negative indices order = [2, 1, -1] for df in [float_frame]: - result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected) @@ -46,11 +44,9 @@ def test_take(self, float_frame): df.take([3, 1, 2, -5], axis=1) def test_take_mixed_type(self, float_string_frame): - # mixed-dtype order = [4, 1, 2, 0, 3] for df in [float_string_frame]: - result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected) @@ -63,7 +59,6 @@ def test_take_mixed_type(self, float_string_frame): # negative indices order = [4, 1, -2] for df in [float_string_frame]: - result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected) @@ -77,7 +72,6 @@ def test_take_mixed_numeric(self, mixed_float_frame, mixed_int_frame): # by dtype order = [1, 2, 0, 3] for df in [mixed_float_frame, mixed_int_frame]: - result = df.take(order, axis=0) expected = df.reindex(df.index.take(order)) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 002fde78cfd35..f0fb0a0595cbd 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -364,7 +364,6 @@ def test_where_bug_transposition(self): tm.assert_frame_equal(result, expected) def test_where_datetime(self): - # GH 3311 df = DataFrame( { diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py index 65aadc9de4f23..ec7d75ef4debb 100644 --- a/pandas/tests/frame/methods/test_align.py +++ b/pandas/tests/frame/methods/test_align.py @@ -136,7 +136,6 @@ def test_align_int(self, int_frame): tm.assert_index_equal(bf.columns, other.columns) def test_align_mixed_type(self, float_string_frame): - af, bf = float_string_frame.align( float_string_frame, join="inner", axis=1, method="pad" ) diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index c13817dd1cdb7..08546f03cee69 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -111,7 +111,6 @@ def test_astype_with_exclude_string(self, float_frame): tm.assert_frame_equal(casted, expected) def test_astype_with_view_float(self, float_frame): - # this is the only real reason to do it this way tf = np.round(float_frame).astype(np.int32) casted = tf.astype(np.float32, copy=False) @@ -121,7 +120,6 @@ def test_astype_with_view_float(self, float_frame): casted = tf.astype(np.int64, copy=False) # noqa def test_astype_with_view_mixed_float(self, mixed_float_frame): - tf = mixed_float_frame.reindex(columns=["A", "B", "C"]) casted = tf.astype(np.int64) diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 776e5b85317ff..ac0b0866c467f 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -245,7 +245,6 @@ def test_drop_api_equivalence(self): ], ) def test_raise_on_drop_duplicate_index(self, actual): - # GH#19186 level = 0 if isinstance(actual.index, MultiIndex) else None msg = re.escape("\"['c'] not found in axis\"") diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 2b5d675f029d3..f161cf7b3c525 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -81,7 +81,6 @@ def test_fillna_datetime(self, datetime_frame): datetime_frame.fillna(5, method="ffill") def test_fillna_mixed_type(self, float_string_frame): - mf = float_string_frame mf.loc[mf.index[5:20], "foo"] = np.nan mf.loc[mf.index[-10:], "A"] = np.nan @@ -90,7 +89,6 @@ def test_fillna_mixed_type(self, float_string_frame): mf.fillna(method="pad") def test_fillna_mixed_float(self, mixed_float_frame): - # mixed numeric (but no float16) mf = mixed_float_frame.reindex(columns=["A", "B", "D"]) mf.loc[mf.index[-10:], "A"] = np.nan @@ -194,7 +192,6 @@ def test_fillna_tzaware_different_column(self): tm.assert_frame_equal(result, expected) def test_na_actions_categorical(self): - cat = Categorical([1, 2, 3, np.nan], categories=[1, 2, 3]) vals = ["a", "b", np.nan, "d"] df = DataFrame({"cats": cat, "vals": vals}) diff --git a/pandas/tests/frame/methods/test_get_numeric_data.py b/pandas/tests/frame/methods/test_get_numeric_data.py index 456dfe1075981..bed611b3a969e 100644 --- a/pandas/tests/frame/methods/test_get_numeric_data.py +++ b/pandas/tests/frame/methods/test_get_numeric_data.py @@ -21,7 +21,6 @@ def test_get_numeric_data_preserve_dtype(self): tm.assert_frame_equal(result, expected) def test_get_numeric_data(self): - datetime64name = np.dtype("M8[ns]").name objectname = np.dtype(np.object_).name diff --git a/pandas/tests/frame/methods/test_join.py b/pandas/tests/frame/methods/test_join.py index 9a4837939aceb..e158a99eedc1e 100644 --- a/pandas/tests/frame/methods/test_join.py +++ b/pandas/tests/frame/methods/test_join.py @@ -113,7 +113,6 @@ def right_w_dups(right_no_dup): ], ) def test_join(left, right, how, sort, expected): - result = left.join(right, how=how, sort=sort, validate="1:1") tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_nlargest.py b/pandas/tests/frame/methods/test_nlargest.py index a317dae562ae0..b5c33a41dd780 100644 --- a/pandas/tests/frame/methods/test_nlargest.py +++ b/pandas/tests/frame/methods/test_nlargest.py @@ -59,7 +59,6 @@ def df_main_dtypes(): class TestNLargestNSmallest: - # ---------------------------------------------------------------------- # Top / bottom @pytest.mark.parametrize( @@ -85,7 +84,6 @@ def test_nlargest_n(self, df_strings, nselect_method, n, order): # GH#10393 df = df_strings if "b" in order: - error_msg = ( f"Column 'b' has dtype object, " f"cannot use method '{nselect_method}' with this dtype" diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 0a4d1dedfae9d..a2d958c31c8bb 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -182,7 +182,6 @@ def test_quantile_date_range(self, interp_method, request, using_array_manager): tm.assert_series_equal(result, expected) def test_quantile_axis_mixed(self, interp_method, request, using_array_manager): - # mixed on axis=1 interpolation, method = interp_method df = DataFrame( @@ -833,7 +832,6 @@ def compute_quantile(self, obj, qs): return result def test_quantile_ea(self, request, obj, index): - # result should be invariant to shuffling indexer = np.arange(len(index), dtype=np.intp) np.random.shuffle(indexer) @@ -861,7 +859,6 @@ def test_quantile_ea(self, request, obj, index): tm.assert_equal(result, expected) def test_quantile_ea_with_na(self, obj, index): - obj.iloc[0] = index._na_value obj.iloc[-1] = index._na_value diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index f455213bd436b..8a46429c8fec9 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -54,7 +54,6 @@ def test_dti_set_index_reindex_freq_with_tz(self): 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 @@ -674,7 +673,6 @@ def test_reindex_columns(self, float_frame): assert new_frame.empty def test_reindex_columns_method(self): - # GH 14992, reindexing over columns ignored method df = DataFrame( data=[[11, 12, 13], [21, 22, 23], [31, 32, 33]], @@ -794,7 +792,6 @@ def test_reindex_single_column_ea_index_and_columns(self, any_numeric_ea_dtype): tm.assert_frame_equal(result, expected) def test_reindex_dups(self): - # GH4746, reindex on duplicate index error messages arr = np.random.randn(10) df = DataFrame(arr, index=[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]) @@ -811,7 +808,6 @@ def test_reindex_dups(self): 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"] diff --git a/pandas/tests/frame/methods/test_rename.py b/pandas/tests/frame/methods/test_rename.py index ce84c5b7428a6..6d8af97a5d210 100644 --- a/pandas/tests/frame/methods/test_rename.py +++ b/pandas/tests/frame/methods/test_rename.py @@ -96,7 +96,6 @@ def test_rename_chainmap(self, args, kwargs): tm.assert_frame_equal(result, expected) def test_rename_multiindex(self): - tuples_index = [("foo1", "bar1"), ("foo2", "bar2")] tuples_columns = [("fizz1", "buzz1"), ("fizz2", "buzz2")] index = MultiIndex.from_tuples(tuples_index, names=["foo", "bar"]) diff --git a/pandas/tests/frame/methods/test_reorder_levels.py b/pandas/tests/frame/methods/test_reorder_levels.py index 9080bdbee0e3d..5d6b65daae4d5 100644 --- a/pandas/tests/frame/methods/test_reorder_levels.py +++ b/pandas/tests/frame/methods/test_reorder_levels.py @@ -53,7 +53,6 @@ def test_reorder_levels(self, frame_or_series): def test_reorder_levels_swaplevel_equivalence( self, multiindex_year_month_day_dataframe_random_data ): - ymd = multiindex_year_month_day_dataframe_random_data result = ymd.reorder_levels(["month", "day", "year"]) diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index 1923299476a32..466d48fba4779 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -541,7 +541,6 @@ def test_replace_mixed(self, float_string_frame): tm.assert_frame_equal(result.replace(-1e8, np.nan), float_string_frame) def test_replace_mixed_int_block_upcasting(self): - # int block upcasting df = DataFrame( { @@ -563,7 +562,6 @@ def test_replace_mixed_int_block_upcasting(self): tm.assert_frame_equal(df, expected) def test_replace_mixed_int_block_splitting(self): - # int block splitting df = DataFrame( { @@ -583,7 +581,6 @@ def test_replace_mixed_int_block_splitting(self): tm.assert_frame_equal(result, expected) def test_replace_mixed2(self): - # to object block upcasting df = DataFrame( { @@ -713,7 +710,6 @@ def test_replace_value_is_none(self, datetime_frame): datetime_frame.iloc[1, 0] = orig2 def test_replace_for_new_dtypes(self, datetime_frame): - # dtypes tsframe = datetime_frame.copy().astype(np.float32) tsframe.loc[tsframe.index[:5], "A"] = np.nan @@ -1111,7 +1107,6 @@ def test_replace_datetime(self): tm.assert_frame_equal(result, expected) def test_replace_datetimetz(self): - # GH 11326 # behaving poorly when presented with a datetime64[ns, tz] df = DataFrame( diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 0ee19ab29c13b..8a11a59cdcb58 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -46,7 +46,6 @@ def test_reset_index_empty_rangeindex(self): tm.assert_frame_equal(result, df[[]], check_index_type=True) def test_set_reset(self): - idx = Index([2**63, 2**63 + 5, 2**63 + 10], name="foo") # set/reset @@ -58,7 +57,6 @@ def test_set_reset(self): tm.assert_index_equal(df.index, idx) def test_set_index_reset_index_dt64tz(self): - idx = Index(date_range("20130101", periods=3, tz="US/Eastern"), name="foo") # set/reset diff --git a/pandas/tests/frame/methods/test_sample.py b/pandas/tests/frame/methods/test_sample.py index 30dc631c2e949..69e799b8ff189 100644 --- a/pandas/tests/frame/methods/test_sample.py +++ b/pandas/tests/frame/methods/test_sample.py @@ -306,7 +306,6 @@ def test_sample_axis1(self): ) def test_sample_aligns_weights_with_frame(self): - # Test that function aligns weights with frame df = DataFrame({"col1": [5, 6, 7], "col2": ["a", "b", "c"]}, index=[9, 5, 3]) ser = Series([1, 0, 0], index=[3, 5, 9]) diff --git a/pandas/tests/frame/methods/test_select_dtypes.py b/pandas/tests/frame/methods/test_select_dtypes.py index 9284e0c0cced6..2e9c75fe25652 100644 --- a/pandas/tests/frame/methods/test_select_dtypes.py +++ b/pandas/tests/frame/methods/test_select_dtypes.py @@ -327,7 +327,6 @@ def test_select_dtypes_bad_datetime64(self): df.select_dtypes(exclude=["datetime64[as]"]) def test_select_dtypes_datetime_with_tz(self): - df2 = DataFrame( { "A": Timestamp("20130102", tz="US/Eastern"), diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 9e4eb78428802..8384fcb4de5aa 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -303,7 +303,6 @@ def test_sort_index_level(self): tm.assert_frame_equal(result, expected) def test_sort_index_categorical_index(self): - df = DataFrame( { "A": np.arange(6, dtype="int64"), @@ -529,7 +528,6 @@ def test_sort_index_categorical_multiindex(self): tm.assert_frame_equal(result, expected) def test_sort_index_and_reconstruction(self): - # GH#15622 # lexsortedness should be identical # across MultiIndex construction methods @@ -610,7 +608,6 @@ def test_sort_index_level2(self, multiindex_dataframe_random_data): tm.assert_frame_equal(rs, frame.sort_index(level=0)) def test_sort_index_level_large_cardinality(self): - # GH#2684 (int64) index = MultiIndex.from_arrays([np.arange(4000)] * 3) df = DataFrame(np.random.randn(4000).astype("int64"), index=index) @@ -680,7 +677,6 @@ def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data): ], ) def test_sort_index_multilevel_repr_8017(self, gen, extra): - np.random.seed(0) data = np.random.randn(3, 4) diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 026c3ae7011a0..5ea78bb2131e5 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -291,7 +291,6 @@ def test_sort_values_stable_categorial(self): tm.assert_frame_equal(sorted_df, expected) def test_sort_values_datetimes(self): - # GH#3461, argsort / lexsort differences for a datetime column df = DataFrame( ["a", "a", "a", "b", "c", "d", "e", "f", "g"], @@ -349,7 +348,6 @@ def test_sort_values_frame_column_inplace_sort_exception( cp.sort_values() # it works! def test_sort_values_nat_values_in_int_column(self): - # GH#14922: "sorting with large float and multiple columns incorrect" # cause was that the int64 value NaT was considered as "na". Which is @@ -509,7 +507,6 @@ def test_sort_values_na_position_with_categories(self): tm.assert_frame_equal(result, expected) def test_sort_values_nat(self): - # GH#16836 d1 = [Timestamp(x) for x in ["2016-01-01", "2015-01-01", np.nan, "2016-01-01"]] diff --git a/pandas/tests/frame/methods/test_to_csv.py b/pandas/tests/frame/methods/test_to_csv.py index a7e077c0d7408..8a68876d7e11a 100644 --- a/pandas/tests/frame/methods/test_to_csv.py +++ b/pandas/tests/frame/methods/test_to_csv.py @@ -33,7 +33,6 @@ def read_csv(self, path, **kwargs): return read_csv(path, **params) def test_to_csv_from_csv1(self, float_frame, datetime_frame): - with tm.ensure_clean("__tmp_to_csv_from_csv1__") as path: float_frame.iloc[:5, float_frame.columns.get_loc("A")] = np.nan @@ -72,9 +71,7 @@ def test_to_csv_from_csv1(self, float_frame, datetime_frame): tm.assert_frame_equal(dm, recons) def test_to_csv_from_csv2(self, float_frame): - with tm.ensure_clean("__tmp_to_csv_from_csv2__") as path: - # duplicate index df = DataFrame( np.random.randn(3, 3), index=["a", "a", "b"], columns=["x", "y", "z"] @@ -104,7 +101,6 @@ def test_to_csv_from_csv2(self, float_frame): float_frame.to_csv(path, header=["AA", "X"]) def test_to_csv_from_csv3(self): - with tm.ensure_clean("__tmp_to_csv_from_csv3__") as path: df1 = DataFrame(np.random.randn(3, 1)) df2 = DataFrame(np.random.randn(3, 1)) @@ -118,7 +114,6 @@ def test_to_csv_from_csv3(self): tm.assert_frame_equal(xp, rs) def test_to_csv_from_csv4(self): - with tm.ensure_clean("__tmp_to_csv_from_csv4__") as path: # GH 10833 (TimedeltaIndex formatting) dt = pd.Timedelta(seconds=1) @@ -135,10 +130,8 @@ def test_to_csv_from_csv4(self): tm.assert_frame_equal(df, result, check_index_type=True) def test_to_csv_from_csv5(self, timezone_frame): - # tz, 8260 with tm.ensure_clean("__tmp_to_csv_from_csv5__") as path: - timezone_frame.to_csv(path) result = read_csv(path, index_col=0, parse_dates=["A"]) @@ -181,7 +174,6 @@ def test_to_csv_new_dupe_cols(self, cols): # we wrote them in a different order # so compare them in that order if cols is not None: - if df.columns.is_unique: rs_c.columns = cols else: @@ -418,7 +410,6 @@ def test_to_csv_params(self, nrows, df_params, func_params, ncols): tm.assert_frame_equal(result, expected, check_names=False) def test_to_csv_from_csv_w_some_infs(self, float_frame): - # test roundtrip with inf, -inf, nan, as full columns and mix float_frame["G"] = np.nan f = lambda x: [np.inf, np.nan][np.random.rand() < 0.5] @@ -432,7 +423,6 @@ def test_to_csv_from_csv_w_some_infs(self, float_frame): tm.assert_frame_equal(np.isinf(float_frame), np.isinf(recons)) def test_to_csv_from_csv_w_all_infs(self, float_frame): - # test roundtrip with inf, -inf, nan, as full columns and mix float_frame["E"] = np.inf float_frame["F"] = -np.inf @@ -483,7 +473,6 @@ def test_to_csv_headers(self): tm.assert_frame_equal(to_df, recons) def test_to_csv_multiindex(self, float_frame, datetime_frame): - frame = float_frame old_index = frame.index arrays = np.arange(len(old_index) * 2, dtype=np.int64).reshape(2, -1) @@ -491,7 +480,6 @@ def test_to_csv_multiindex(self, float_frame, datetime_frame): frame.index = new_index with tm.ensure_clean("__tmp_to_csv_multiindex__") as path: - frame.to_csv(path, header=False) frame.to_csv(path, columns=["A", "B"]) @@ -643,7 +631,6 @@ def test_to_csv_float32_nanrep(self): assert lines[1].split(",")[2] == "999" def test_to_csv_withcommas(self): - # Commas inside fields should be correctly escaped when saving as CSV. df = DataFrame({"A": [1, 2, 3], "B": ["5,6", "7,8", "9,0"]}) @@ -699,7 +686,6 @@ def create_cols(name): tm.assert_frame_equal(rs, df) def test_to_csv_dups_cols(self): - df = DataFrame( np.random.randn(1000, 30), columns=list(range(15)) + list(range(15)), @@ -750,7 +736,6 @@ def test_to_csv_dups_cols(self): @pytest.mark.parametrize("chunksize", [10000, 50000, 100000]) def test_to_csv_chunking(self, chunksize): - aa = DataFrame({"A": range(100000)}) aa["B"] = aa.A + 1.0 aa["C"] = aa.A + 2.0 @@ -783,10 +768,8 @@ def test_to_csv_bug(self): tm.assert_frame_equal(recons, newdf, check_names=False) def test_to_csv_unicode(self): - df = DataFrame({"c/\u03c3": [1, 2, 3]}) with tm.ensure_clean() as path: - df.to_csv(path, encoding="UTF-8") df2 = read_csv(path, index_col=0, encoding="UTF-8") tm.assert_frame_equal(df, df2) @@ -817,7 +800,6 @@ def test_to_csv_stringio(self, float_frame): tm.assert_frame_equal(recons, float_frame) def test_to_csv_float_format(self): - df = DataFrame( [[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]], index=["A", "B"], @@ -825,7 +807,6 @@ def test_to_csv_float_format(self): ) with tm.ensure_clean() as filename: - df.to_csv(filename, float_format="%.2f") rs = read_csv(filename, index_col=0) @@ -920,7 +901,6 @@ def test_to_csv_lineterminators(self): assert f.read() == expected def test_to_csv_from_csv_categorical(self): - # CSV with categoricals should result in the same output # as when one would add a "normal" Series/DataFrame. s = Series(pd.Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])) @@ -974,9 +954,7 @@ def test_to_csv_path_is_none(self, float_frame): ], ) def test_to_csv_compression(self, df, encoding, compression): - with tm.ensure_clean() as filename: - df.to_csv(filename, compression=compression, encoding=encoding) # test the round trip - to_csv -> read_csv result = read_csv( @@ -1070,7 +1048,6 @@ def test_to_csv_date_format(self, datetime_frame): @pytest.mark.parametrize("td", [pd.Timedelta(0), pd.Timedelta("10s")]) def test_to_csv_with_dst_transitions(self, td): - with tm.ensure_clean("csv_date_format_with_dst") as path: # make sure we are not failing on transitions times = date_range( diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py index e14dc8da68136..e64b212a8513c 100644 --- a/pandas/tests/frame/methods/test_to_dict.py +++ b/pandas/tests/frame/methods/test_to_dict.py @@ -21,7 +21,6 @@ class TestDataFrameToDict: def test_to_dict_timestamp(self): - # GH#11247 # split/records producing np.datetime64 rather than Timestamps # on datetime64[ns] dtypes only diff --git a/pandas/tests/frame/methods/test_to_timestamp.py b/pandas/tests/frame/methods/test_to_timestamp.py index d1c10ce37bf3d..fea070a3c0b38 100644 --- a/pandas/tests/frame/methods/test_to_timestamp.py +++ b/pandas/tests/frame/methods/test_to_timestamp.py @@ -130,7 +130,6 @@ def test_to_timestamp_invalid_axis(self): obj.to_timestamp(axis=2) def test_to_timestamp_hourly(self, frame_or_series): - index = period_range(freq="H", start="1/1/2001", end="1/2/2001") obj = Series(1, index=index, name="foo") if frame_or_series is not Series: diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index 4f4477ad993ca..6213a6dbbd0ca 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -86,7 +86,6 @@ def test_transpose_object_to_tzaware_mixed_tz(self): assert (res2.dtypes == [dti.dtype, dti2.dtype]).all() def test_transpose_uint64(self, uint64_frame): - result = uint64_frame.T expected = DataFrame(uint64_frame.values.T) expected.index = ["A", "B"] diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py index c5f6870769afc..b3d2bd795c45a 100644 --- a/pandas/tests/frame/methods/test_tz_convert.py +++ b/pandas/tests/frame/methods/test_tz_convert.py @@ -59,7 +59,6 @@ def test_tz_convert_and_localize(self, fn): l1 = l1.tz_localize("UTC") for idx in [l0, l1]: - l0_expected = getattr(idx, fn)("US/Pacific") l1_expected = getattr(idx, fn)("US/Pacific") diff --git a/pandas/tests/frame/methods/test_tz_localize.py b/pandas/tests/frame/methods/test_tz_localize.py index e34b21a73453c..ed2b0b247e62c 100644 --- a/pandas/tests/frame/methods/test_tz_localize.py +++ b/pandas/tests/frame/methods/test_tz_localize.py @@ -42,7 +42,6 @@ def test_tz_localize_axis1(self): tm.assert_frame_equal(result, expected.T) def test_tz_localize_naive(self, frame_or_series): - # Can't localize if already tz-aware rng = date_range("1/1/2011", periods=100, freq="H", tz="utc") ts = Series(1, index=rng) diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index ef468065f7e0e..e8a9c418b1d98 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -46,7 +46,6 @@ def test_update(self): tm.assert_frame_equal(df, expected) def test_update_dtypes(self): - # gh 3016 df = DataFrame( [[1.0, 2.0, False, True], [4.0, 5.0, True, False]], diff --git a/pandas/tests/frame/methods/test_values.py b/pandas/tests/frame/methods/test_values.py index 1f134af68be6b..134534e3c8f8c 100644 --- a/pandas/tests/frame/methods/test_values.py +++ b/pandas/tests/frame/methods/test_values.py @@ -115,7 +115,6 @@ def test_frame_values_with_tz(self): tm.assert_numpy_array_equal(result, expected) def test_interleave_with_tzaware(self, timezone_frame): - # interleave with object result = timezone_frame.assign(D="foo").values expected = np.array( @@ -185,7 +184,6 @@ def test_values_numeric_cols(self, float_frame): assert values.dtype == np.float64 def test_values_lcd(self, mixed_float_frame, mixed_int_frame): - # mixed lcd values = mixed_float_frame[["A", "B", "C", "D"]].values assert values.dtype == np.float64 diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 78cadae3f206d..4ffb4b6b355b6 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -209,7 +209,6 @@ def test_empty_like(self, df): assert df.T.empty def test_with_datetimelikes(self): - df = DataFrame( { "A": date_range("20130101", periods=10), diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 0453d7881a811..d2d2b66df36d7 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -621,7 +621,6 @@ def test_arith_flex_frame_raise(self, all_arithmetic_operators, float_frame, dim getattr(float_frame, op)(arr) def test_arith_flex_frame_corner(self, float_frame): - const_add = float_frame.add(1) tm.assert_frame_equal(const_add, float_frame + 1) @@ -966,7 +965,6 @@ def test_df_bool_mul_int(self): assert (kinds == "i").all() def test_arith_mixed(self): - left = DataFrame({"A": ["a", "b", "c"], "B": [1, 2, 3]}) result = left + left @@ -1072,7 +1070,6 @@ def test_frame_with_frame_reindex(self): ids=lambda x: x.__name__, ) def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements, request): - skip = { (operator.truediv, "bool"), (operator.pow, "bool"), @@ -1122,7 +1119,6 @@ def test_binop_other(self, op, value, dtype, switch_numexpr_min_elements, reques op(df, elem.value) elif (op, dtype) in skip: - if op in [operator.add, operator.mul]: if expr.USE_NUMEXPR and switch_numexpr_min_elements == 0: # "evaluating in Python space because ..." @@ -1274,7 +1270,6 @@ def test_logical_typeerror_with_non_valid(self, op, res, float_frame): @pytest.mark.parametrize("op", ["add", "sub", "mul", "div", "truediv"]) def test_binary_ops_align(self, op): - # test aligning binary ops # GH 6681 @@ -1415,7 +1410,6 @@ def test_combineFrame(self, float_frame, mixed_float_frame, mixed_int_frame): _check_mixed_float(added, dtype="float64") def test_combine_series(self, float_frame, mixed_float_frame, mixed_int_frame): - # Series series = float_frame.xs(float_frame.index[0]) @@ -1572,7 +1566,6 @@ def test_comparison_protected_from_errstate(self): tm.assert_numpy_array_equal(result, expected) def test_boolean_comparison(self): - # GH 4576 # boolean comparisons with a tuple/list give unexpected results df = DataFrame(np.arange(6).reshape((3, 2))) @@ -1651,7 +1644,6 @@ def test_boolean_comparison(self): df == tup def test_inplace_ops_alignment(self): - # inplace ops / ops alignment # GH 8511 @@ -1700,7 +1692,6 @@ def test_inplace_ops_alignment(self): tm.assert_frame_equal(result1, result4) def test_inplace_ops_identity(self): - # GH 5104 # make sure that we are actually changing the object s_orig = Series([1, 2, 3]) @@ -1774,7 +1765,6 @@ def test_inplace_ops_identity(self): ], ) def test_inplace_ops_identity2(self, op): - if op == "div": return diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 04f4766e49227..8b0ac237f1480 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -207,7 +207,6 @@ def test_construction_with_mixed(self, float_string_frame): tm.assert_series_equal(result, expected) def test_construction_with_conversions(self): - # convert from a numpy array of non-ns timedelta64; as of 2.0 this does # *not* convert arr = np.array([1, 2, 3], dtype="timedelta64[s]") @@ -330,7 +329,6 @@ def test_is_mixed_type(self, float_frame, float_string_frame): assert float_string_frame._is_mixed_type def test_stale_cached_series_bug_473(self, using_copy_on_write): - # this is chained, but ok with option_context("chained_assignment", None): Y = DataFrame( diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 7c7e419fd8dfd..569ec613cbcb9 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1399,7 +1399,6 @@ def test_constructor_generator(self): tm.assert_frame_equal(result, expected, check_dtype=False) def test_constructor_list_of_dicts(self): - result = DataFrame([{}]) expected = DataFrame(index=RangeIndex(1), columns=[]) tm.assert_frame_equal(result, expected) @@ -1872,7 +1871,6 @@ def test_constructor_with_datetimes(self): tm.assert_series_equal(result, expected) def test_constructor_with_datetimes1(self): - # GH 2809 ind = date_range(start="2000-01-01", freq="D", periods=10) datetimes = [ts.to_pydatetime() for ts in ind] @@ -2194,7 +2192,6 @@ def test_constructor_ndarray_categorical_dtype(self): tm.assert_frame_equal(result, expected) def test_constructor_categorical(self): - # GH8626 # dict creation @@ -2247,7 +2244,6 @@ def test_construct_from_listlikes_mismatched_lengths(self): tm.assert_frame_equal(df, expected) def test_constructor_categorical_series(self): - items = [1, 2, 3, 1] exp = Series(items).astype("category") res = Series(items, dtype="category") @@ -2459,7 +2455,6 @@ def test_constructor_list_str(self, input_vals, string_dtype): tm.assert_frame_equal(result, expected) def test_constructor_list_str_na(self, string_dtype): - result = DataFrame({"A": [1.0, 2.0, None]}, dtype=string_dtype) expected = DataFrame({"A": ["1.0", "2.0", None]}, dtype=object) tm.assert_frame_equal(result, expected) @@ -2794,7 +2789,6 @@ def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture, pydt): DataFrame([[ts]], columns=[0], dtype="datetime64[ns]") def test_from_dict(self): - # 8260 # support datetime64 with tz @@ -2809,7 +2803,6 @@ def test_from_dict(self): tm.assert_series_equal(df["B"], Series(dr, name="B")) def test_from_index(self): - # from index idx2 = date_range("20130101", periods=3, tz="US/Eastern", name="foo") df2 = DataFrame(idx2) @@ -2969,7 +2962,6 @@ def box(self, request): @pytest.fixture def constructor(self, frame_or_series, box): - extra = {"index": range(2)} if frame_or_series is DataFrame: extra["columns"] = ["A"] @@ -3011,7 +3003,6 @@ def test_from_timestamp_scalar_preserves_nanos(self, constructor, fixed_now_ts): assert get1(obj) == ts def test_from_timedelta64_scalar_object(self, constructor): - td = Timedelta(1) td64 = td.to_timedelta64() diff --git a/pandas/tests/frame/test_iteration.py b/pandas/tests/frame/test_iteration.py index 154dee23e6042..6d4849d60084f 100644 --- a/pandas/tests/frame/test_iteration.py +++ b/pandas/tests/frame/test_iteration.py @@ -138,7 +138,6 @@ def test_itertuples(self, float_frame): assert hasattr(result_255_columns, "_fields") def test_sequence_like_with_categorical(self): - # GH#7839 # make sure can iterate df = DataFrame( diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 819a8304769ab..bd708408f4246 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -19,7 +19,6 @@ def check(result, expected=None): class TestDataFrameNonuniqueIndexes: def test_setattr_columns_vs_construct_with_columns(self): - # assignment # GH 3687 arr = np.random.randn(3, 2) diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index c815b897e6a14..2d38e6b75ee65 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -53,7 +53,6 @@ def expected2(self, df): return df.A + 1 def test_query_default(self, df, expected1, expected2): - # GH 12749 # this should always work, whether NUMEXPR_INSTALLED or not result = df.query("A>0") @@ -62,21 +61,18 @@ def test_query_default(self, df, expected1, expected2): tm.assert_series_equal(result, expected2, check_names=False) def test_query_None(self, df, expected1, expected2): - result = df.query("A>0", engine=None) tm.assert_frame_equal(result, expected1) result = df.eval("A+1", engine=None) tm.assert_series_equal(result, expected2, check_names=False) def test_query_python(self, df, expected1, expected2): - result = df.query("A>0", engine="python") tm.assert_frame_equal(result, expected1) result = df.eval("A+1", engine="python") tm.assert_series_equal(result, expected2, check_names=False) def test_query_numexpr(self, df, expected1, expected2): - if NUMEXPR_INSTALLED: result = df.query("A>0", engine="numexpr") tm.assert_frame_equal(result, expected1) @@ -95,7 +91,6 @@ def test_query_numexpr(self, df, expected1, expected2): class TestDataFrameEval: - # smaller hits python, larger hits numexpr @pytest.mark.parametrize("n", [4, 4000]) @pytest.mark.parametrize( @@ -108,7 +103,6 @@ class TestDataFrameEval: ], ) def test_ops(self, op_str, op, rop, n): - # tst ops and reversed ops in evaluation # GH7198 @@ -538,7 +532,6 @@ def test_query_doesnt_pickup_local(self): df.query("sin > 5", engine=engine, parser=parser) def test_query_builtin(self): - engine, parser = self.engine, self.parser n = m = 10 @@ -1077,7 +1070,6 @@ def test_query_with_nested_special_character(self, parser, engine): ], ) def test_query_lex_compare_strings(self, parser, engine, op, func): - a = Series(np.random.choice(list("abcde"), 20)) b = Series(np.arange(a.size)) df = DataFrame({"X": a, "Y": b}) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 3e6074971352d..eaa789a5d3e67 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -142,7 +142,6 @@ def wrapper(x): class TestDataFrameAnalytics: - # --------------------------------------------------------------------- # Reductions @pytest.mark.parametrize("axis", [0, 1]) @@ -543,7 +542,6 @@ def test_sem(self, datetime_frame): ], ) def test_mode_dropna(self, dropna, expected): - df = DataFrame( { "A": [12, 12, 19, 11], @@ -1143,7 +1141,6 @@ def test_any_all_object_dtype(self, axis, bool_agg_func, skipna): "ignore:'any' with datetime64 dtypes is deprecated.*:FutureWarning" ) def test_any_datetime(self): - # GH 23070 float_data = [1, np.nan, 3, np.nan] datetime_data = [ @@ -1160,7 +1157,6 @@ def test_any_datetime(self): tm.assert_series_equal(result, expected) def test_any_all_bool_only(self): - # GH 25101 df = DataFrame( {"col1": [1, 2, 3], "col2": [4, 5, 6], "col3": [None, None, None]} @@ -1278,7 +1274,6 @@ def test_any_all_object(self): assert result is False def test_any_all_object_bool_only(self): - df = DataFrame({"A": ["foo", 2], "B": [True, False]}).astype(object) df._consolidate_inplace() df["C"] = Series([True, True]) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index 5034a8473fe63..4a23e750e7875 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -76,7 +76,6 @@ def test_unstack_not_consolidated(self, using_array_manager): tm.assert_series_equal(res, expected) def test_unstack_fill(self): - # GH #9746: fill_value keyword argument for Series # and DataFrame unstack @@ -123,7 +122,6 @@ def test_unstack_fill(self): tm.assert_frame_equal(result, expected) def test_unstack_fill_frame(self): - # From a dataframe rows = [[1, 2], [3, 4], [5, 6], [7, 8]] df = DataFrame(rows, columns=list("AB"), dtype=np.int32) @@ -160,7 +158,6 @@ def test_unstack_fill_frame(self): tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_datetime(self): - # Test unstacking with date times dv = date_range("2012-01-01", periods=4).values data = Series(dv) @@ -183,7 +180,6 @@ def test_unstack_fill_frame_datetime(self): tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_timedelta(self): - # Test unstacking with time deltas td = [Timedelta(days=i) for i in range(4)] data = Series(td) @@ -206,7 +202,6 @@ def test_unstack_fill_frame_timedelta(self): tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_period(self): - # Test unstacking with period periods = [ Period("2012-01"), @@ -237,7 +232,6 @@ def test_unstack_fill_frame_period(self): tm.assert_frame_equal(result, expected) def test_unstack_fill_frame_categorical(self): - # Test unstacking with categorical data = Series(["a", "b", "c", "a"], dtype="category") data.index = MultiIndex.from_tuples( @@ -557,7 +551,6 @@ def test_unstack_to_series(self, float_frame): tm.assert_frame_equal(old_data, data) def test_unstack_dtypes(self): - # GH 2929 rows = [[1, 1, 3, 4], [1, 2, 3, 4], [2, 1, 3, 4], [2, 2, 3, 4]] diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index f1adff58325ce..5c44a957b9373 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -585,7 +585,6 @@ def test_subclassed_reductions(self, all_reductions): assert isinstance(result, tm.SubclassedSeries) def test_subclassed_count(self): - df = tm.SubclassedDataFrame( { "Person": ["John", "Myla", "Lewis", "John", "Myla"], @@ -617,7 +616,6 @@ def test_subclassed_count(self): assert isinstance(result, tm.SubclassedSeries) def test_isin(self): - df = tm.SubclassedDataFrame( {"num_legs": [2, 4], "num_wings": [2, 0]}, index=["falcon", "dog"] ) @@ -625,7 +623,6 @@ def test_isin(self): assert isinstance(result, tm.SubclassedDataFrame) def test_duplicated(self): - df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) result = df.duplicated() assert isinstance(result, tm.SubclassedSeries) @@ -636,13 +633,11 @@ def test_duplicated(self): @pytest.mark.parametrize("idx_method", ["idxmax", "idxmin"]) def test_idx(self, idx_method): - df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) result = getattr(df, idx_method)() assert isinstance(result, tm.SubclassedSeries) def test_dot(self): - df = tm.SubclassedDataFrame([[0, 1, -2, -1], [1, 1, 1, 1]]) s = tm.SubclassedSeries([1, 1, 2, 1]) result = df.dot(s) @@ -654,7 +649,6 @@ def test_dot(self): assert isinstance(result, tm.SubclassedDataFrame) def test_memory_usage(self): - df = tm.SubclassedDataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) result = df.memory_usage() assert isinstance(result, tm.SubclassedSeries) @@ -677,7 +671,6 @@ def test_corrwith(self): assert isinstance(correls, (tm.SubclassedSeries)) def test_asof(self): - N = 3 rng = pd.date_range("1/1/1990", periods=N, freq="53s") df = tm.SubclassedDataFrame( diff --git a/pandas/tests/generic/test_duplicate_labels.py b/pandas/tests/generic/test_duplicate_labels.py index f09fa147076b2..06170d2241f01 100644 --- a/pandas/tests/generic/test_duplicate_labels.py +++ b/pandas/tests/generic/test_duplicate_labels.py @@ -177,7 +177,11 @@ def test_ndframe_getitem_caching_issue(self, request, using_copy_on_write): pd.DataFrame({"A": [1, 2]}, index=["a", "b"]).set_flags( allows_duplicate_labels=False ), - pd.Series([1, 2], index=["a", "b"], name="B",).set_flags( + pd.Series( + [1, 2], + index=["a", "b"], + name="B", + ).set_flags( allows_duplicate_labels=False, ), ], diff --git a/pandas/tests/generic/test_frame.py b/pandas/tests/generic/test_frame.py index d6e3298e83c3e..8a1e0f0923531 100644 --- a/pandas/tests/generic/test_frame.py +++ b/pandas/tests/generic/test_frame.py @@ -46,7 +46,6 @@ def test_set_axis_name_mi(self, func): assert result.index.names == [None, None] def test_nonzero_single_element(self): - # allow single item via bool method df = DataFrame([[True]]) assert df.bool() @@ -88,7 +87,6 @@ def test_metadata_propagation_indiv(self, monkeypatch): # GH 6923 def finalize(self, other, method=None, **kwargs): - for name in self._metadata: if method == "merge": left, right = other.left, other.right diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 429dd9181ad50..54d08b577a47a 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -60,7 +60,6 @@ class TestGeneric: ], ) def test_rename(self, frame_or_series, func): - # single axis idx = list("ABCD") @@ -75,7 +74,6 @@ def test_rename(self, frame_or_series, func): tm.assert_equal(result, expected) def test_get_numeric_data(self, frame_or_series): - n = 4 kwargs = { frame_or_series._get_axis_name(i): list(range(n)) @@ -103,7 +101,6 @@ def test_get_numeric_data(self, frame_or_series): tm.assert_equal(result, o) def test_nonzero(self, frame_or_series): - # GH 4633 # look at the boolean/nonzero behavior for objects obj = construct(frame_or_series, shape=4) @@ -215,7 +212,6 @@ def test_metadata_propagation(self, frame_or_series): # simple boolean for op in ["__eq__", "__le__", "__ge__"]: - # this is a name matching op v1 = getattr(o, op)(o) v2 = getattr(o, op)(o2) @@ -254,7 +250,6 @@ def test_stat_unexpected_keyword(self, frame_or_series): @pytest.mark.parametrize("func", ["sum", "cumsum", "any", "var"]) def test_api_compat(self, func, frame_or_series): - # GH 12021 # compat for __name__, __qualname__ @@ -373,7 +368,6 @@ def test_transpose_frame(self): tm.assert_frame_equal(df.transpose().transpose(), df) def test_numpy_transpose(self, frame_or_series): - obj = tm.makeTimeDataFrame() obj = tm.get_obj(obj, frame_or_series) diff --git a/pandas/tests/generic/test_label_or_level_utils.py b/pandas/tests/generic/test_label_or_level_utils.py index d1c85d770621c..97be46f716d7d 100644 --- a/pandas/tests/generic/test_label_or_level_utils.py +++ b/pandas/tests/generic/test_label_or_level_utils.py @@ -68,7 +68,6 @@ def assert_level_reference(frame, levels, axis): # DataFrame # --------- def test_is_level_or_label_reference_df_simple(df_levels, axis): - axis = df_levels._get_axis_number(axis) # Compute expected labels and levels expected_labels, expected_levels = get_labels_levels(df_levels) @@ -83,7 +82,6 @@ def test_is_level_or_label_reference_df_simple(df_levels, axis): def test_is_level_reference_df_ambig(df_ambig, axis): - axis = df_ambig._get_axis_number(axis) # Transpose frame if axis == 1 @@ -105,7 +103,6 @@ def test_is_level_reference_df_ambig(df_ambig, axis): # Series # ------ def test_is_level_reference_series_simple_axis0(df): - # Make series with L1 as index s = df.set_index("L1").L2 assert_level_reference(s, ["L1"], axis=0) @@ -118,7 +115,6 @@ def test_is_level_reference_series_simple_axis0(df): def test_is_level_reference_series_axis1_error(df): - # Make series with L1 as index s = df.set_index("L1").L2 @@ -129,10 +125,10 @@ def test_is_level_reference_series_axis1_error(df): # Test _check_label_or_level_ambiguity_df # ======================================= + # DataFrame # --------- def test_check_label_or_level_ambiguity_df(df_ambig, axis): - axis = df_ambig._get_axis_number(axis) # Transpose frame if axis == 1 if axis == 1: @@ -156,7 +152,6 @@ def test_check_label_or_level_ambiguity_df(df_ambig, axis): # Series # ------ def test_check_label_or_level_ambiguity_series(df): - # A series has no columns and therefore references are never ambiguous # Make series with L1 as index @@ -172,7 +167,6 @@ def test_check_label_or_level_ambiguity_series(df): def test_check_label_or_level_ambiguity_series_axis1_error(df): - # Make series with L1 as index s = df.set_index("L1").L2 @@ -209,7 +203,6 @@ def assert_level_values(frame, levels, axis): # DataFrame # --------- def test_get_label_or_level_values_df_simple(df_levels, axis): - # Compute expected labels and levels expected_labels, expected_levels = get_labels_levels(df_levels) @@ -224,7 +217,6 @@ def test_get_label_or_level_values_df_simple(df_levels, axis): def test_get_label_or_level_values_df_ambig(df_ambig, axis): - axis = df_ambig._get_axis_number(axis) # Transpose frame if axis == 1 if axis == 1: @@ -238,7 +230,6 @@ def test_get_label_or_level_values_df_ambig(df_ambig, axis): def test_get_label_or_level_values_df_duplabels(df_duplabels, axis): - axis = df_duplabels._get_axis_number(axis) # Transpose frame if axis == 1 if axis == 1: @@ -263,7 +254,6 @@ def test_get_label_or_level_values_df_duplabels(df_duplabels, axis): # Series # ------ def test_get_label_or_level_values_series_axis0(df): - # Make series with L1 as index s = df.set_index("L1").L2 assert_level_values(s, ["L1"], axis=0) @@ -274,7 +264,6 @@ def test_get_label_or_level_values_series_axis0(df): def test_get_label_or_level_values_series_axis1_error(df): - # Make series with L1 as index s = df.set_index("L1").L2 @@ -313,7 +302,6 @@ def assert_levels_dropped(frame, levels, axis): # DataFrame # --------- def test_drop_labels_or_levels_df(df_levels, axis): - # Compute expected labels and levels expected_labels, expected_levels = get_labels_levels(df_levels) @@ -333,7 +321,6 @@ def test_drop_labels_or_levels_df(df_levels, axis): # Series # ------ def test_drop_labels_or_levels_series(df): - # Make series with L1 as index s = df.set_index("L1").L2 assert_levels_dropped(s, ["L1"], axis=0) diff --git a/pandas/tests/generic/test_series.py b/pandas/tests/generic/test_series.py index dd2380e2647d3..5098897f057a5 100644 --- a/pandas/tests/generic/test_series.py +++ b/pandas/tests/generic/test_series.py @@ -40,7 +40,6 @@ def test_get_bool_data_preserve_dtype(self): tm.assert_series_equal(result, ser) def test_nonzero_single_element(self): - # allow single item via bool method ser = Series([True]) assert ser.bool() diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index dc763e4044866..4872cc27cde9a 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -56,7 +56,6 @@ def test_agg_must_agg(df): def test_agg_ser_multi_key(df): - f = lambda x: x.sum() results = df.C.groupby([df.A, df.B]).aggregate(f) expected = df.groupby(["A", "B"]).sum()["C"] diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 04f48bb7cfabc..5fa7ed15a01d4 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -709,7 +709,6 @@ def func_with_date(batch): def test_gb_apply_list_of_unequal_len_arrays(): - # GH1738 df = DataFrame( { diff --git a/pandas/tests/groupby/test_apply_mutate.py b/pandas/tests/groupby/test_apply_mutate.py index d1f25aabe31a2..6823aeef258cb 100644 --- a/pandas/tests/groupby/test_apply_mutate.py +++ b/pandas/tests/groupby/test_apply_mutate.py @@ -21,7 +21,6 @@ def test_group_by_copy(): def test_mutate_groups(): - # GH3380 df = pd.DataFrame( @@ -54,7 +53,6 @@ def f_no_copy(x): def test_no_mutate_but_looks_like(): - # GH 8467 # first show's mutation indicator # second does not, but should yield the same results diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 9fe35876dc5b5..fa8df166d56ac 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -82,7 +82,6 @@ def get_stats(group): def test_basic(): # TODO: split this test - cats = Categorical( ["a", "a", "a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c", "d"], @@ -657,7 +656,6 @@ def test_datetime(): def test_categorical_index(): - s = np.random.RandomState(12345) levels = ["foo", "bar", "baz", "qux"] codes = s.randint(0, 4, size=20) @@ -946,7 +944,6 @@ def test_groupby_empty_with_category(): def test_sort(): - # https://stackoverflow.com/questions/23814368/sorting-pandas- # categorical-labels-after-groupby # This should result in a properly sorted Series so that the plot diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index b1ab1135f6e35..535e8fa5b9354 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -187,7 +187,6 @@ def test_extrema(self, df, method): @pytest.mark.parametrize("method", ["first", "last"]) def test_first_last(self, df, method): - expected_columns = Index( [ "int", @@ -206,7 +205,6 @@ def test_first_last(self, df, method): @pytest.mark.parametrize("method", ["sum", "cumsum"]) def test_sum_cumsum(self, df, method): - expected_columns_numeric = Index(["int", "float", "category_int"]) expected_columns = Index( ["int", "float", "string", "category_int", "timedelta"] @@ -219,7 +217,6 @@ def test_sum_cumsum(self, df, method): @pytest.mark.parametrize("method", ["prod", "cumprod"]) def test_prod_cumprod(self, df, method): - expected_columns = Index(["int", "float", "category_int"]) expected_columns_numeric = expected_columns @@ -333,7 +330,6 @@ def test_describe(self, df, gb, gni): def test_cython_api2(): - # this takes the fast apply path # cumsum (GH5614) @@ -1151,7 +1147,6 @@ def test_frame_describe_multikey(tsframe): def test_frame_describe_tupleindex(): - # GH 14848 - regression from 0.19.0 to 0.19.1 df1 = DataFrame( { diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index a0b129b65d293..d969ce4a2bb71 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -66,7 +66,6 @@ def test_groupby_std_datetimelike(): @pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"]) def test_basic(dtype): - data = Series(np.arange(9) // 3, index=np.arange(9), dtype=dtype) index = np.arange(9) @@ -322,7 +321,6 @@ def f(x): def test_indices_concatenation_order(): - # GH 2808 def f1(x): @@ -1013,7 +1011,6 @@ def aggfun(ser): def test_groupby_level_apply(mframe): - result = mframe.groupby(level=0).count() assert result.index.name == "first" result = mframe.groupby(level=1).count() @@ -1171,7 +1168,6 @@ def test_grouping_ndarray(df): def test_groupby_wrong_multi_labels(): - index = Index([0, 1, 2, 3, 4], name="index") data = DataFrame( { @@ -1295,7 +1291,6 @@ def test_series_grouper_noncontig_index(): def test_convert_objects_leave_decimal_alone(): - s = Series(range(5)) labels = np.array(["a", "b", "c", "d", "e"], dtype="O") @@ -1523,7 +1518,6 @@ def test_dont_clobber_name_column(): def test_skip_group_keys(): - tsf = tm.makeTimeDataFrame() grouped = tsf.groupby(lambda x: x.month, group_keys=False) @@ -1651,7 +1645,6 @@ def test_groupby_sort_multiindex_series(): def test_groupby_reindex_inside_function(): - periods = 1000 ind = date_range(start="2012/1/1", freq="5min", periods=periods) df = DataFrame({"high": np.arange(periods), "low": np.arange(periods)}, index=ind) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 88ecac1ab24c9..f5bbfce560d33 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -201,7 +201,6 @@ def test_grouper_multilevel_freq(self): tm.assert_frame_equal(result, expected) def test_grouper_creation_bug(self): - # GH 8795 df = DataFrame({"A": [0, 0, 1, 1, 2, 2], "B": [1, 2, 3, 4, 5, 6]}) g = df.groupby("A") @@ -354,7 +353,6 @@ def test_groupby_categorical_index_and_columns(self, observed): tm.assert_frame_equal(result, expected) def test_grouper_getting_correct_binner(self): - # GH 10063 # using a non-time-based grouper and a time-based grouper # and specifying levels @@ -450,7 +448,6 @@ def test_grouping_error_on_multidim_input(self, df): Grouping(df.index, df[["A", "A"]]) def test_multiindex_passthru(self): - # GH 7997 # regression from 0.14.1 df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) @@ -798,7 +795,6 @@ def test_get_group(self): g.get_group(("foo", "bar", "baz")) def test_get_group_empty_bins(self, observed): - d = DataFrame([3, 1, 7, 6]) bins = [0, 5, 10, 15] g = d.groupby(pd.cut(d[0], bins), observed=observed) diff --git a/pandas/tests/groupby/test_index_as_string.py b/pandas/tests/groupby/test_index_as_string.py index e32b5eb44d5dc..4aaf3de9a23b2 100644 --- a/pandas/tests/groupby/test_index_as_string.py +++ b/pandas/tests/groupby/test_index_as_string.py @@ -72,7 +72,6 @@ def test_grouper_index_level_as_string(frame, key_strs, groupers): ], ) def test_grouper_index_level_as_string_series(series, levels): - # Compute expected result if isinstance(levels, list): groupers = [pd.Grouper(level=lv) for lv in levels] diff --git a/pandas/tests/groupby/test_missing.py b/pandas/tests/groupby/test_missing.py index 76da8dfe0607b..63772c24ca34b 100644 --- a/pandas/tests/groupby/test_missing.py +++ b/pandas/tests/groupby/test_missing.py @@ -56,7 +56,6 @@ def test_fillna_with_string_dtype(method, expected): def test_fill_consistency(): - # GH9221 # pass thru keyword arguments to the generated wrapper # are set if the passed kw is None (only) diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index 77422c28d356f..cf1537b42bc9f 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -121,7 +121,6 @@ def test_first_last_with_None_expanded(method, df, expected): def test_first_last_nth_dtypes(df_mixed_floats): - df = df_mixed_floats.copy() df["E"] = True df["F"] = 1 diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 25829765a90cd..f9a1349081529 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -158,7 +158,6 @@ def test_groupby_with_timegrouper_methods(self, should_sort): assert len(groups) == 3 def test_timegrouper_with_reg_groups(self): - # GH 3794 # allow combination of timegrouper/reg groups @@ -234,7 +233,6 @@ def test_timegrouper_with_reg_groups(self): df_sorted = df_original.sort_values(by="Quantity", ascending=False) for df in [df_original, df_sorted]: - expected = DataFrame( { "Buyer": "Carl Joe Mark Carl Joe".split(), @@ -601,7 +599,6 @@ def test_frame_datetime64_handling_groupby(self): assert result["date"][3] == Timestamp("2012-07-03") def test_groupby_multi_timezone(self): - # combining multiple / different timezones yields UTC data = """0,2000-01-28 16:47:00,America/Chicago diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index ce5ce3e56ab98..2c3c2277ed627 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -73,7 +73,6 @@ def seed_df(seed_nans, n, m): ids = [] for seed_nans in [True, False]: for n, m in product((100, 1000), (5, 20)): - df = seed_df(seed_nans, n, m) bins = None, np.arange(0, max(5, df["3rd"].max()) + 1, 2) keys = "1st", "2nd", ["1st", "2nd"] @@ -549,7 +548,6 @@ def test_data_frame_value_counts_dropna( def test_categorical_single_grouper_with_only_observed_categories( education_df, as_index, observed, normalize, name, expected_data ): - # Test single categorical grouper with only observed grouping categories # when non-groupers are also categorical diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 9a64c5eea33a8..7ead3890c5130 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -82,7 +82,6 @@ def demean(arr): def test_transform_fast(): - df = DataFrame({"id": np.arange(100000) / 3, "val": np.random.randn(100000)}) grp = df.groupby("id")["val"] @@ -194,7 +193,6 @@ def test_transform_axis_1_reducer(request, reduction_func): def test_transform_axis_ts(tsframe): - # make sure that we are setting the axes # correctly when on axis=0 or 1 # in the presence of a non-monotonic indexer @@ -464,7 +462,6 @@ def nsum(x): def test_transform_coercion(): - # 14457 # when we are transforming be sure to not coerce # via assignment @@ -478,7 +475,6 @@ def test_transform_coercion(): def test_groupby_transform_with_int(): - # GH 3740, make sure that we might upcast on item-by-item transform # floats diff --git a/pandas/tests/indexes/base_class/test_reshape.py b/pandas/tests/indexes/base_class/test_reshape.py index 547d62669943c..5ecb2c753644d 100644 --- a/pandas/tests/indexes/base_class/test_reshape.py +++ b/pandas/tests/indexes/base_class/test_reshape.py @@ -18,7 +18,6 @@ def test_repeat(self): tm.assert_index_equal(result, expected) def test_insert(self): - # GH 7256 # validate neg/pos inserts result = Index(["b", "c", "d"]) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index e375af797f409..d7fdbb39f3e69 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -39,7 +39,6 @@ def test_can_hold_identifiers(self): assert idx._can_hold_identifiers_and_holds_name(key) is True def test_insert(self, simple_index): - ci = simple_index categories = ci.categories @@ -76,7 +75,6 @@ def test_insert_na_mismatched_dtype(self): tm.assert_index_equal(result, expected) def test_delete(self, simple_index): - ci = simple_index categories = ci.categories @@ -185,7 +183,6 @@ def test_has_duplicates(self): ], ) def test_drop_duplicates(self, data, categories, expected): - idx = CategoricalIndex(data, categories=categories, name="foo") for keep, e in expected.items(): tm.assert_numpy_array_equal(idx.duplicated(keep=keep), e) @@ -210,7 +207,6 @@ def test_unique(self, data, categories, expected_data, ordered): tm.assert_index_equal(idx.unique(), expected) def test_repr_roundtrip(self): - ci = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) str(ci) tm.assert_index_equal(eval(repr(ci)), ci, exact=True) @@ -224,7 +220,6 @@ def test_repr_roundtrip(self): str(ci) def test_isin(self): - ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"]) tm.assert_numpy_array_equal( ci.isin(["c"]), np.array([False, False, False, True, False, False]) @@ -246,7 +241,6 @@ def test_isin(self): tm.assert_numpy_array_equal(result, expected) def test_identical(self): - ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True) ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True) assert ci1.identical(ci1) @@ -354,7 +348,6 @@ def test_disallow_addsub_ops(self, func, op_name): func(idx) def test_method_delegation(self): - ci = CategoricalIndex(list("aabbca"), categories=list("cabdef")) result = ci.set_categories(list("cab")) tm.assert_index_equal( diff --git a/pandas/tests/indexes/categorical/test_constructors.py b/pandas/tests/indexes/categorical/test_constructors.py index 19e8ec19db641..f0c5307fc5c64 100644 --- a/pandas/tests/indexes/categorical/test_constructors.py +++ b/pandas/tests/indexes/categorical/test_constructors.py @@ -19,7 +19,6 @@ def test_construction_disallows_scalar(self): CategoricalIndex(categories=list("abcd"), ordered=False) def test_construction(self): - ci = CategoricalIndex(list("aabbca"), categories=list("abcd"), ordered=False) categories = ci.categories @@ -93,7 +92,6 @@ def test_construction(self): assert not isinstance(result, CategoricalIndex) def test_construction_with_dtype(self): - # specify dtype ci = CategoricalIndex(list("aabbca"), categories=list("abc"), ordered=False) diff --git a/pandas/tests/indexes/categorical/test_formats.py b/pandas/tests/indexes/categorical/test_formats.py index d7812888556ea..8e09f68c16707 100644 --- a/pandas/tests/indexes/categorical/test_formats.py +++ b/pandas/tests/indexes/categorical/test_formats.py @@ -78,7 +78,6 @@ def test_string_categorical_index_repr(self): # Enable Unicode option ----------------------------------------- with cf.option_context("display.unicode.east_asian_width", True): - # short idx = CategoricalIndex(["あ", "いい", "ううう"]) expected = """CategoricalIndex(['あ', 'いい', 'ううう'], categories=['あ', 'いい', 'ううう'], ordered=False, dtype='category')""" # noqa:E501 diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py index 588486452fc20..01077616c50db 100644 --- a/pandas/tests/indexes/categorical/test_indexing.py +++ b/pandas/tests/indexes/categorical/test_indexing.py @@ -77,7 +77,6 @@ def test_take_fill_value(self): idx.take(np.array([1, -5])) def test_take_fill_value_datetime(self): - # datetime category idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx") idx = CategoricalIndex(idx) @@ -239,12 +238,10 @@ def test_get_indexer_requires_unique(self): # respect duplicates instead of taking # the fast-track path. for finder in [list("aabbca"), list("aababca")]: - with pytest.raises(InvalidIndexError, match=msg): ci.get_indexer(finder) def test_get_indexer_non_unique(self): - idx1 = CategoricalIndex(list("aabcde"), categories=list("edabc")) idx2 = CategoricalIndex(list("abf")) @@ -342,7 +339,6 @@ def test_where_non_categories(self): class TestContains: def test_contains(self): - ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=False) assert "a" in ci diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index d55b35557d40f..272166e25e8a5 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -63,7 +63,6 @@ def test_pickle_compat_construction(self): self._index_cls() def test_shift(self, simple_index): - # GH8083 test the base class for shift idx = simple_index msg = ( @@ -83,7 +82,6 @@ def test_constructor_name_unhashable(self, simple_index): type(idx)(idx, name=[]) def test_create_index_existing_name(self, simple_index): - # GH11193, when an existing index is passed, and a new name is not # specified, the new index should inherit the previous object name expected = simple_index @@ -136,7 +134,6 @@ def test_create_index_existing_name(self, simple_index): ) def test_numeric_compat(self, simple_index): - idx = simple_index # Check that this doesn't cover MultiIndex case, if/when it does, # we can remove multi.test_compat.test_numeric_compat @@ -187,7 +184,6 @@ def test_logical_compat(self, simple_index): idx.any() def test_repr_roundtrip(self, simple_index): - idx = simple_index tm.assert_index_equal(eval(repr(idx)), idx) @@ -600,7 +596,6 @@ def test_map(self, simple_index): ], ) def test_map_dictlike(self, mapper, simple_index): - idx = simple_index if isinstance(idx, CategoricalIndex): # FIXME: this fails with CategoricalIndex bc it goes through diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index f836672cc8557..dade67795bc81 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -35,7 +35,6 @@ def test_can_hold_identifiers(self, simple_index): assert idx._can_hold_identifiers_and_holds_name(key) is False def test_shift_identity(self, simple_index): - idx = simple_index tm.assert_index_equal(idx, idx.shift(0)) @@ -45,7 +44,6 @@ def test_shift_empty(self, simple_index): tm.assert_index_equal(idx, idx.shift(1)) def test_str(self, simple_index): - # test the string repr idx = simple_index idx.name = "foo" diff --git a/pandas/tests/indexes/datetimelike_/test_equals.py b/pandas/tests/indexes/datetimelike_/test_equals.py index 39e8270b1c4f5..f59963ec3effc 100644 --- a/pandas/tests/indexes/datetimelike_/test_equals.py +++ b/pandas/tests/indexes/datetimelike_/test_equals.py @@ -24,7 +24,6 @@ class EqualsTests: def test_not_equals_numeric(self, index): - assert not index.equals(Index(index.asi8)) assert not index.equals(Index(index.asi8.astype("u8"))) assert not index.equals(Index(index.asi8).astype("f8")) @@ -39,7 +38,6 @@ def test_not_equals_non_arraylike(self, index): assert not index.equals(list(index)) def test_not_equals_strings(self, index): - other = Index([str(x) for x in index], dtype=object) assert not index.equals(other) assert not index.equals(CategoricalIndex(other)) diff --git a/pandas/tests/indexes/datetimelike_/test_indexing.py b/pandas/tests/indexes/datetimelike_/test_indexing.py index b64d5421a2067..ee7128601256a 100644 --- a/pandas/tests/indexes/datetimelike_/test_indexing.py +++ b/pandas/tests/indexes/datetimelike_/test_indexing.py @@ -19,7 +19,6 @@ @pytest.mark.parametrize("ldtype", dtlike_dtypes) @pytest.mark.parametrize("rdtype", dtlike_dtypes) def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype): - vals = np.tile(3600 * 10**9 * np.arange(3), 2) def construct(dtype): diff --git a/pandas/tests/indexes/datetimelike_/test_sort_values.py b/pandas/tests/indexes/datetimelike_/test_sort_values.py index 6b7ad79e8f76d..ab1c15f003d4d 100644 --- a/pandas/tests/indexes/datetimelike_/test_sort_values.py +++ b/pandas/tests/indexes/datetimelike_/test_sort_values.py @@ -136,7 +136,6 @@ def test_sort_values_with_freq_periodindex2(self, idx): self.check_sort_values_with_freq(idx) def check_sort_values_without_freq(self, idx, expected): - ordered = idx.sort_values(na_position="first") tm.assert_index_equal(ordered, expected) check_freq_nonmonotonic(ordered, idx) diff --git a/pandas/tests/indexes/datetimes/methods/test_astype.py b/pandas/tests/indexes/datetimes/methods/test_astype.py index 8cf1edf5c7bf3..94cf86b7fb9c5 100644 --- a/pandas/tests/indexes/datetimes/methods/test_astype.py +++ b/pandas/tests/indexes/datetimes/methods/test_astype.py @@ -50,7 +50,6 @@ def test_astype_uint(self): arr.astype("uint32") def test_astype_with_tz(self): - # with tz rng = date_range("1/1/2000", periods=10, tz="US/Eastern") msg = "Cannot use .astype to convert from timezone-aware" diff --git a/pandas/tests/indexes/datetimes/methods/test_insert.py b/pandas/tests/indexes/datetimes/methods/test_insert.py index 2478a3ba799ad..cedf8cd54b81e 100644 --- a/pandas/tests/indexes/datetimes/methods/test_insert.py +++ b/pandas/tests/indexes/datetimes/methods/test_insert.py @@ -137,7 +137,6 @@ def test_insert(self): Timestamp("2000-01-01 15:00", tz=tz), pytz.timezone(tz).localize(datetime(2000, 1, 1, 15)), ]: - result = idx.insert(6, d) tm.assert_index_equal(result, expected) assert result.name == expected.name diff --git a/pandas/tests/indexes/datetimes/methods/test_shift.py b/pandas/tests/indexes/datetimes/methods/test_shift.py index 5a47b36a2a8d0..65bdfc9053e5e 100644 --- a/pandas/tests/indexes/datetimes/methods/test_shift.py +++ b/pandas/tests/indexes/datetimes/methods/test_shift.py @@ -17,7 +17,6 @@ class TestDatetimeIndexShift: - # ------------------------------------------------------------- # DatetimeIndex.shift is used in integer addition diff --git a/pandas/tests/indexes/datetimes/methods/test_to_period.py b/pandas/tests/indexes/datetimes/methods/test_to_period.py index e8048e63afbf7..e4f8aef277f87 100644 --- a/pandas/tests/indexes/datetimes/methods/test_to_period.py +++ b/pandas/tests/indexes/datetimes/methods/test_to_period.py @@ -167,7 +167,6 @@ def test_to_period_tz_utc_offset_consistency(self, tz): # GH#22905 ts = date_range("1/1/2000", "2/1/2000", tz="Etc/GMT-1") with tm.assert_produces_warning(UserWarning): - result = ts.to_period()[0] expected = ts[0].to_period(ts.freq) assert result == expected diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 46bd9ea8af055..689e6cdb47058 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -151,7 +151,6 @@ def test_constructor_from_sparse_array(self): assert result.dtype == arr.dtype def test_construction_caching(self): - df = pd.DataFrame( { "dt": date_range("20130101", periods=3), @@ -692,7 +691,6 @@ def test_constructor_datetime64_tzformat(self, freq): tm.assert_numpy_array_equal(idx.asi8, expected_i8.asi8) def test_constructor_dtype(self): - # passing a dtype with a tz should localize idx = DatetimeIndex( ["2013-01-01", "2013-01-02"], dtype="datetime64[ns, US/Eastern]" diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index a41645f46314a..f13dfcd5c20bd 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -38,7 +38,6 @@ def test_datetimeindex_accessors(self): freq="D", start=datetime(1998, 1, 1), periods=365, tz="US/Eastern" ) for dti in [dti_naive, dti_tz]: - assert dti.year[0] == 1998 assert dti.month[0] == 1 assert dti.day[0] == 1 diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index b4ef62604d888..f030f4101512e 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -325,7 +325,6 @@ def test_partial_slicing_dataframe(self): df[ts_string] def test_partial_slicing_with_multiindex(self): - # GH 4758 # partial string indexing with a multi-index buggy df = DataFrame( diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index e3dc7f1dbade2..c1b74319e2679 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -78,7 +78,6 @@ def test_union(self, tz, sort): (rng2, other2, expected2, expected2_notsorted), (rng3, other3, expected3, expected3_notsorted), ]: - result_union = rng.union(other, sort=sort) tm.assert_index_equal(result_union, exp) @@ -226,7 +225,7 @@ def test_intersection(self, tz, sort): rng4 = date_range("7/1/2000", "7/31/2000", freq="D", name="idx") expected4 = DatetimeIndex([], freq="D", name="idx") - for (rng, expected) in [ + for rng, expected in [ (rng2, expected2), (rng3, expected3), (rng4, expected4), @@ -257,7 +256,7 @@ def test_intersection(self, tz, sort): expected4 = DatetimeIndex([], tz=tz, name="idx") assert expected4.freq is None - for (rng, expected) in [ + for rng, expected in [ (rng2, expected2), (rng3, expected3), (rng4, expected4), diff --git a/pandas/tests/indexes/datetimes/test_unique.py b/pandas/tests/indexes/datetimes/test_unique.py index c18bd99b67000..5319bf59f8a64 100644 --- a/pandas/tests/indexes/datetimes/test_unique.py +++ b/pandas/tests/indexes/datetimes/test_unique.py @@ -12,7 +12,6 @@ def test_unique(tz_naive_fixture): - idx = DatetimeIndex(["2017"] * 2, tz=tz_naive_fixture) expected = idx[:1] diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index 4b46c6d612bae..b7511a72e31da 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -105,7 +105,6 @@ def test_constructor_pass_closed(self, constructor, breaks): for dtype in (iv_dtype, str(iv_dtype)): with tm.assert_produces_warning(None): - result = constructor(dtype=dtype, closed="left", **result_kwargs) assert result.dtype.closed == "left" diff --git a/pandas/tests/indexes/interval/test_indexing.py b/pandas/tests/indexes/interval/test_indexing.py index c647226283b8d..e7db8076efa2b 100644 --- a/pandas/tests/indexes/interval/test_indexing.py +++ b/pandas/tests/indexes/interval/test_indexing.py @@ -28,7 +28,6 @@ class TestGetLoc: @pytest.mark.parametrize("side", ["right", "left", "both", "neither"]) def test_get_loc_interval(self, closed, side): - idx = IntervalIndex.from_tuples([(0, 1), (2, 3)], closed=closed) for bound in [[0, 1], [1, 2], [2, 3], [3, 4], [0, 2], [2.5, 3], [-1, 4]]: @@ -49,7 +48,6 @@ def test_get_loc_interval(self, closed, side): @pytest.mark.parametrize("scalar", [-0.5, 0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5]) def test_get_loc_scalar(self, closed, scalar): - # correct = {side: {query: answer}}. # If query is not in the dict, that query should raise a KeyError correct = { @@ -210,7 +208,6 @@ class TestGetIndexer: ], ) def test_get_indexer_with_interval(self, query, expected): - tuples = [(0, 2), (2, 4), (5, 7)] index = IntervalIndex.from_tuples(tuples, closed="right") @@ -239,7 +236,6 @@ def test_get_indexer_with_interval(self, query, expected): ], ) def test_get_indexer_with_int_and_float(self, query, expected): - tuples = [(0, 1), (1, 2), (3, 4)] index = IntervalIndex.from_tuples(tuples, closed="right") @@ -357,7 +353,6 @@ def test_get_indexer_errors(self, tuples, closed): ], ) def test_get_indexer_non_unique_with_int_and_float(self, query, expected): - tuples = [(0, 2.5), (1, 3), (2, 4)] index = IntervalIndex.from_tuples(tuples, closed="left") @@ -432,7 +427,6 @@ def test_get_indexer_interval_index(self, box): class TestSliceLocs: def test_slice_locs_with_interval(self): - # increasing monotonically index = IntervalIndex.from_tuples([(0, 2), (1, 3), (2, 4)]) @@ -511,7 +505,6 @@ def test_slice_locs_with_interval(self): assert index.slice_locs(start=Interval(2, 4), end=Interval(0, 2)) == (2, 2) def test_slice_locs_with_ints_and_floats_succeeds(self): - # increasing non-overlapping index = IntervalIndex.from_tuples([(0, 1), (1, 2), (3, 4)]) @@ -585,7 +578,6 @@ class TestContains: # .__contains__, not .contains def test_contains_dunder(self): - index = IntervalIndex.from_arrays([0, 1], [1, 2], closed="right") # __contains__ requires perfect matches to intervals. diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index dedc3fdd00e08..49e8df2b71f22 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -510,7 +510,6 @@ def test_contains_method(self): i.contains(Interval(0, 1)) def test_dropna(self, closed): - expected = IntervalIndex.from_tuples([(0.0, 1.0), (1.0, 2.0)], closed=closed) ii = IntervalIndex.from_tuples([(0, 1), (1, 2), np.nan], closed=closed) @@ -702,7 +701,6 @@ def test_datetime(self, tz): tm.assert_numpy_array_equal(actual, expected) def test_append(self, closed): - index1 = IntervalIndex.from_arrays([0, 1], [1, 2], closed=closed) index2 = IntervalIndex.from_arrays([1, 2], [2, 3], closed=closed) diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index 7d68ccc88cf44..7097aa2b61632 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -17,7 +17,6 @@ def test_infer_objects(idx): def test_shift(idx): - # GH8083 test the base class for shift msg = ( "This method is only implemented for DatetimeIndex, PeriodIndex and " @@ -160,7 +159,6 @@ def test_iter(idx): def test_sub(idx): - first = idx # - now raises (previously was set op difference) @@ -192,7 +190,6 @@ def test_map(idx): ], ) def test_map_dictlike(idx, mapper): - identity = mapper(idx.values, idx) # we don't infer to uint64 dtype for a dict diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py index 78b46e5a32a48..cabc2bfd61db6 100644 --- a/pandas/tests/indexes/multi/test_constructors.py +++ b/pandas/tests/indexes/multi/test_constructors.py @@ -497,7 +497,6 @@ def test_from_product_index_series_categorical(ordered, f): def test_from_product(): - first = ["foo", "bar", "buz"] second = ["a", "b", "c"] names = ["first", "second"] @@ -596,7 +595,6 @@ def test_from_product_readonly(): def test_create_index_existing_name(idx): - # GH11193, when an existing index is passed, and a new name is not # specified, the new index should inherit the previous object name index = idx @@ -809,7 +807,6 @@ def test_datetimeindex(): def test_constructor_with_tz(): - index = pd.DatetimeIndex( ["2013/01/01 09:00", "2013/01/02 09:00"], name="dt1", tz="US/Pacific" ) diff --git a/pandas/tests/indexes/multi/test_copy.py b/pandas/tests/indexes/multi/test_copy.py index e4126d22f247c..2e09a580f9528 100644 --- a/pandas/tests/indexes/multi/test_copy.py +++ b/pandas/tests/indexes/multi/test_copy.py @@ -45,7 +45,6 @@ def test_view(idx): @pytest.mark.parametrize("func", [copy, deepcopy]) def test_copy_and_deepcopy(func): - idx = MultiIndex( levels=[["foo", "bar"], ["fizz", "buzz"]], codes=[[0, 0, 0, 1], [0, 0, 1, 1]], diff --git a/pandas/tests/indexes/multi/test_get_level_values.py b/pandas/tests/indexes/multi/test_get_level_values.py index bab6481fe107f..84907f5279876 100644 --- a/pandas/tests/indexes/multi/test_get_level_values.py +++ b/pandas/tests/indexes/multi/test_get_level_values.py @@ -13,7 +13,6 @@ class TestGetLevelValues: def test_get_level_values_box_datetime64(self): - dates = date_range("1/1/2000", periods=4) levels = [dates, [0, 1]] codes = [[0, 0, 1, 1, 2, 2, 3, 3], [0, 1, 0, 1, 0, 1, 0, 1]] diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py index 0fb93eec14f42..a650f7f81a19f 100644 --- a/pandas/tests/indexes/multi/test_integrity.py +++ b/pandas/tests/indexes/multi/test_integrity.py @@ -16,7 +16,6 @@ def test_labels_dtypes(): - # GH 8456 i = MultiIndex.from_tuples([("A", 1), ("A", 2)]) assert i.codes[0].dtype == "int8" @@ -270,7 +269,6 @@ def test_memory_usage(idx): assert result3 > result2 else: - # we report 0 for no-length assert result == 0 diff --git a/pandas/tests/indexes/multi/test_missing.py b/pandas/tests/indexes/multi/test_missing.py index cd95802ac29c9..14ffc42fb4b59 100644 --- a/pandas/tests/indexes/multi/test_missing.py +++ b/pandas/tests/indexes/multi/test_missing.py @@ -85,7 +85,6 @@ def test_hasnans_isnans(idx): def test_nan_stays_float(): - # GH 7031 idx0 = MultiIndex(levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1]) idx1 = MultiIndex(levels=[["C"], ["D"]], codes=[[0], [0]], names=[0, 1]) diff --git a/pandas/tests/indexes/multi/test_names.py b/pandas/tests/indexes/multi/test_names.py index e9c65d32cbcd7..8ae643eb3626d 100644 --- a/pandas/tests/indexes/multi/test_names.py +++ b/pandas/tests/indexes/multi/test_names.py @@ -84,7 +84,6 @@ def test_copy_names(): def test_names(idx, index_names): - # names are assigned in setup assert index_names == ["first", "second"] level_names = [level.name for level in idx.levels] diff --git a/pandas/tests/indexes/multi/test_reshape.py b/pandas/tests/indexes/multi/test_reshape.py index af546a08d50ff..da9838d4a2ed3 100644 --- a/pandas/tests/indexes/multi/test_reshape.py +++ b/pandas/tests/indexes/multi/test_reshape.py @@ -180,7 +180,6 @@ def test_repeat(): def test_insert_base(idx): - result = idx[1:4] # test 0th element @@ -188,7 +187,6 @@ def test_insert_base(idx): def test_delete_base(idx): - expected = idx[1:] result = idx.delete(0) assert result.equals(expected) diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index de4d0e014be29..fd0928b82ecbf 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -131,7 +131,6 @@ def test_empty(idx): def test_difference(idx, sort): - first = idx result = first.difference(idx[-3:], sort=sort) vals = idx[:-3].values diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py index 3f364473270fb..2746c12b120ef 100644 --- a/pandas/tests/indexes/multi/test_sorting.py +++ b/pandas/tests/indexes/multi/test_sorting.py @@ -155,7 +155,6 @@ def test_unsortedindex_doc_examples(): def test_reconstruct_sort(): - # starts off lexsorted & monotonic mi = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) assert mi.is_monotonic_increasing diff --git a/pandas/tests/indexes/numeric/test_numeric.py b/pandas/tests/indexes/numeric/test_numeric.py index ed8071afe2ee2..284b7f782a3f2 100644 --- a/pandas/tests/indexes/numeric/test_numeric.py +++ b/pandas/tests/indexes/numeric/test_numeric.py @@ -108,7 +108,6 @@ def test_constructor_invalid(self): index_cls(0.0) def test_constructor_coerce(self, mixed_index, float_index): - self.check_coerce(mixed_index, Index([1.5, 2, 3, 4, 5])) self.check_coerce(float_index, Index(np.arange(5) * 2.5)) @@ -117,7 +116,6 @@ def test_constructor_coerce(self, mixed_index, float_index): self.check_coerce(float_index, result.astype("float64")) def test_constructor_explicit(self, mixed_index, float_index): - # these don't auto convert self.check_coerce( float_index, Index((np.arange(5) * 2.5), dtype=object), is_float_index=False @@ -170,7 +168,6 @@ def test_equals_numeric_other_index_type(self, other): ], ) def test_lookups_datetimelike_values(self, vals, dtype): - # If we have datetime64 or timedelta64 values, make sure they are # wrapped correctly GH#31163 ser = Series(vals, index=range(3, 6)) @@ -389,7 +386,6 @@ def test_constructor_corner(self, dtype): index = index_cls(arr, dtype=dtype) assert index.values.dtype == index.dtype if dtype == np.int64: - without_dtype = Index(arr) # as of 2.0 we do not infer a dtype when we get an object-dtype # ndarray of numbers, matching Series behavior @@ -407,7 +403,6 @@ def test_constructor_coercion_signed_to_unsigned( self, any_unsigned_int_numpy_dtype, ): - # see gh-15832 msg = "Trying to coerce negative values to unsigned integers" diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 228fd2829c5d9..b5b595d5cc8b5 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -219,7 +219,6 @@ def test_getitem_day(self, idx_range): "2013/02/01 09:00", ] for val in values: - # GH7116 # these show deprecations as we are trying # to slice with non-integer indexers diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index bac231ef0085d..22182416c79fd 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -128,7 +128,6 @@ def test_union(self, sort): (rng7, other7, expected7), (rng8, other8, expected8), ]: - result_union = rng.union(other, sort=sort) if sort is None: expected = expected.sort_values() @@ -193,7 +192,7 @@ def test_intersection_cases(self, sort): rng4 = period_range("7/1/2000", "7/31/2000", freq="D", name="idx") expected4 = PeriodIndex([], name="idx", freq="D") - for (rng, expected) in [ + for rng, expected in [ (rng2, expected2), (rng3, expected3), (rng4, expected4), @@ -227,7 +226,7 @@ def test_intersection_cases(self, sort): rng4 = period_range("7/1/2000", "7/31/2000", freq="D", name="idx") expected4 = PeriodIndex([], freq="D", name="idx") - for (rng, expected) in [ + for rng, expected in [ (rng2, expected2), (rng3, expected3), (rng4, expected4), diff --git a/pandas/tests/indexes/ranges/test_constructors.py b/pandas/tests/indexes/ranges/test_constructors.py index 74bcaa8529ffc..5e6f16075ae63 100644 --- a/pandas/tests/indexes/ranges/test_constructors.py +++ b/pandas/tests/indexes/ranges/test_constructors.py @@ -73,7 +73,6 @@ def test_constructor_invalid_args_wrong_type(self, args): RangeIndex(args) def test_constructor_same(self): - # pass thru w and w/o copy index = RangeIndex(1, 5, 2) result = RangeIndex(index, copy=False) @@ -97,7 +96,6 @@ def test_constructor_range_object(self): tm.assert_index_equal(result, expected, exact=True) def test_constructor_range(self): - result = RangeIndex.from_range(range(1, 5, 2)) expected = RangeIndex(1, 5, 2) tm.assert_index_equal(result, expected, exact=True) diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 8f658295d7dca..4edec0bf95982 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -98,7 +98,6 @@ def test_repr(self): tm.assert_index_equal(result, i, exact=True) def test_insert(self): - idx = RangeIndex(5, name="Foo") result = idx[1:4] @@ -139,7 +138,6 @@ def test_insert_middle_preserves_rangeindex(self): tm.assert_index_equal(result, expected, exact=True) def test_delete(self): - idx = RangeIndex(5, name="Foo") expected = idx[1:] result = idx.delete(0) @@ -371,7 +369,6 @@ def test_identical(self, simple_index): assert not index.copy(dtype=object).identical(index.copy(dtype="int64")) def test_nbytes(self): - # memory savings vs int index idx = RangeIndex(0, 1000) assert idx.nbytes < Index(idx._values).nbytes / 10 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 783cf76403059..665fad09f6d3c 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -402,7 +402,6 @@ def test_not_equals_object(self, comp): assert not Index(["a", "b", "c"]).equals(comp) def test_identical(self): - # index i1 = Index(["a", "b", "c"]) i2 = Index(["a", "b", "c"]) diff --git a/pandas/tests/indexes/test_engines.py b/pandas/tests/indexes/test_engines.py index a4b7ce6822b80..468c2240c8192 100644 --- a/pandas/tests/indexes/test_engines.py +++ b/pandas/tests/indexes/test_engines.py @@ -142,7 +142,6 @@ class TestObjectEngine: values = list("abc") def test_is_monotonic(self): - num = 1000 arr = np.array(["a"] * num + ["a"] * num + ["c"] * num, dtype=self.dtype) diff --git a/pandas/tests/indexes/test_indexing.py b/pandas/tests/indexes/test_indexing.py index d573ee9759112..52f09ac25873e 100644 --- a/pandas/tests/indexes/test_indexing.py +++ b/pandas/tests/indexes/test_indexing.py @@ -180,7 +180,6 @@ def test_get_loc_non_hashable(self, index): index.get_loc(slice(0, 1)) def test_get_loc_generator(self, index): - exc = KeyError if isinstance( index, @@ -209,7 +208,6 @@ def test_get_loc_masked_duplicated_na(self): class TestGetIndexer: def test_get_indexer_base(self, index): - if index._index_as_unique: expected = np.arange(index.size, dtype=np.intp) actual = index.get_indexer(index) diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 2a29e57678df9..788d03d5b7212 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -109,7 +109,6 @@ def test_numpy_ufuncs_other(index, func): # test ufuncs of numpy, see: # https://numpy.org/doc/stable/reference/ufuncs.html if isinstance(index, (DatetimeIndex, TimedeltaIndex)): - if func in (np.isfinite, np.isinf, np.isnan): # numpy 1.18 changed isinf and isnan to not raise on dt64/td64 result = func(index) diff --git a/pandas/tests/indexes/timedeltas/methods/test_insert.py b/pandas/tests/indexes/timedeltas/methods/test_insert.py index c2f22da9f3b7d..f8164102815f6 100644 --- a/pandas/tests/indexes/timedeltas/methods/test_insert.py +++ b/pandas/tests/indexes/timedeltas/methods/test_insert.py @@ -17,7 +17,6 @@ class TestTimedeltaIndexInsert: def test_insert(self): - idx = TimedeltaIndex(["4day", "1day", "2day"], name="idx") result = idx.insert(2, timedelta(days=5)) diff --git a/pandas/tests/indexes/timedeltas/methods/test_shift.py b/pandas/tests/indexes/timedeltas/methods/test_shift.py index 9864f7358018e..f49af73f9f499 100644 --- a/pandas/tests/indexes/timedeltas/methods/test_shift.py +++ b/pandas/tests/indexes/timedeltas/methods/test_shift.py @@ -8,7 +8,6 @@ class TestTimedeltaIndexShift: - # ------------------------------------------------------------- # TimedeltaIndex.shift is used by __add__/__sub__ diff --git a/pandas/tests/indexes/timedeltas/test_scalar_compat.py b/pandas/tests/indexes/timedeltas/test_scalar_compat.py index 16459f00dac3b..9f470b40d1f58 100644 --- a/pandas/tests/indexes/timedeltas/test_scalar_compat.py +++ b/pandas/tests/indexes/timedeltas/test_scalar_compat.py @@ -103,7 +103,7 @@ def test_round(self): t1c = TimedeltaIndex([1, 1, 1], unit="D") # note that negative times round DOWN! so don't give whole numbers - for (freq, s1, s2) in [ + for freq, s1, s2 in [ ("N", t1, t2), ("U", t1, t2), ( @@ -124,7 +124,6 @@ def test_round(self): ("H", t1c, TimedeltaIndex(["-1 days", "-1 days", "-1 days"])), ("d", t1c, TimedeltaIndex([-1, -1, -1], unit="D")), ]: - r1 = t1.round(freq) tm.assert_index_equal(r1, s1) r2 = t2.round(freq) diff --git a/pandas/tests/indexes/timedeltas/test_setops.py b/pandas/tests/indexes/timedeltas/test_setops.py index eff65fba773e4..cb6dce1e7ad80 100644 --- a/pandas/tests/indexes/timedeltas/test_setops.py +++ b/pandas/tests/indexes/timedeltas/test_setops.py @@ -14,7 +14,6 @@ class TestTimedeltaIndex: def test_union(self): - i1 = timedelta_range("1day", periods=5) i2 = timedelta_range("3day", periods=5) result = i1.union(i2) @@ -43,7 +42,6 @@ def test_union_sort_false(self): tm.assert_index_equal(result, expected) def test_union_coverage(self): - idx = TimedeltaIndex(["3d", "1d", "2d"]) ordered = TimedeltaIndex(idx.sort_values(), freq="infer") result = ordered.union(idx) @@ -54,7 +52,6 @@ def test_union_coverage(self): assert result.freq == ordered.freq def test_union_bug_1730(self): - rng_a = timedelta_range("1 day", periods=4, freq="3H") rng_b = timedelta_range("1 day", periods=4, freq="4H") @@ -63,7 +60,6 @@ def test_union_bug_1730(self): tm.assert_index_equal(result, exp) def test_union_bug_1745(self): - left = TimedeltaIndex(["1 day 15:19:49.695000"]) right = TimedeltaIndex( ["2 day 13:04:21.322000", "1 day 15:27:24.873000", "1 day 15:31:05.350000"] @@ -74,7 +70,6 @@ def test_union_bug_1745(self): tm.assert_index_equal(result, exp) def test_union_bug_4564(self): - left = timedelta_range("1 day", "30d") right = left + pd.offsets.Minute(15) @@ -231,7 +226,6 @@ def test_difference_freq(self, sort): tm.assert_attr_equal("freq", idx_diff, expected) def test_difference_sort(self, sort): - index = TimedeltaIndex( ["5 days", "3 days", "2 days", "4 days", "1 days", "0 days"] ) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py index 7d1f6aa2df11d..48dd1fd02d228 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta.py @@ -43,7 +43,6 @@ def test_shift(self): pass # this is handled in test_arithmetic.py def test_misc_coverage(self): - rng = timedelta_range("1 day", periods=5) result = rng.groupby(rng.days) assert isinstance(list(result.values())[0][0], Timedelta) @@ -59,7 +58,6 @@ def test_map(self): tm.assert_index_equal(result, exp) def test_pass_TimedeltaIndex_to_index(self): - rng = timedelta_range("1 days", "10 days") idx = Index(rng, dtype=object) @@ -124,7 +122,6 @@ def test_freq_conversion_always_floating(self): tm.assert_equal(res._values, expected._values._with_freq(None)) def test_freq_conversion(self, index_or_series): - # doc example scalar = Timedelta(days=31) diff --git a/pandas/tests/indexes/timedeltas/test_timedelta_range.py b/pandas/tests/indexes/timedeltas/test_timedelta_range.py index 4f0cab2a433f7..05fdddd7a4f4f 100644 --- a/pandas/tests/indexes/timedeltas/test_timedelta_range.py +++ b/pandas/tests/indexes/timedeltas/test_timedelta_range.py @@ -22,7 +22,6 @@ def test_timedelta_range_unit(self): tm.assert_numpy_array_equal(tdi.to_numpy(), exp_arr) def test_timedelta_range(self): - expected = to_timedelta(np.arange(5), unit="D") result = timedelta_range("0 days", periods=5, freq="D") tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexing/interval/test_interval.py b/pandas/tests/indexing/interval/test_interval.py index db3a569d3925b..717cb7de42021 100644 --- a/pandas/tests/indexing/interval/test_interval.py +++ b/pandas/tests/indexing/interval/test_interval.py @@ -16,7 +16,6 @@ def series_with_interval_index(self): return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) def test_getitem_with_scalar(self, series_with_interval_index, indexer_sl): - ser = series_with_interval_index.copy() expected = ser.iloc[:3] diff --git a/pandas/tests/indexing/interval/test_interval_new.py b/pandas/tests/indexing/interval/test_interval_new.py index 0d314cd73860a..62f44a363f5f0 100644 --- a/pandas/tests/indexing/interval/test_interval_new.py +++ b/pandas/tests/indexing/interval/test_interval_new.py @@ -20,7 +20,6 @@ def series_with_interval_index(self): return Series(np.arange(5), IntervalIndex.from_breaks(np.arange(6))) 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 @@ -51,7 +50,6 @@ def test_loc_with_interval(self, series_with_interval_index, indexer_sl): indexer_sl(ser)[Interval(5, 6)] 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 @@ -74,7 +72,6 @@ def test_loc_with_scalar(self, series_with_interval_index, indexer_sl): tm.assert_series_equal(expected, indexer_sl(ser)[ser >= 2]) def test_loc_with_slices(self, series_with_interval_index, indexer_sl): - # loc with slices: # - Interval objects: only works with exact matches # - scalars: only works for non-overlapping, monotonic intervals, @@ -129,7 +126,6 @@ def test_slice_interval_step(self, series_with_interval_index): ser[0 : 4 : Interval(0, 1)] def test_loc_with_overlap(self, indexer_sl): - idx = IntervalIndex.from_tuples([(1, 5), (3, 7)]) ser = Series(range(len(idx)), index=idx) @@ -176,7 +172,6 @@ def test_loc_with_overlap(self, indexer_sl): ser.loc[1:4] def test_non_unique(self, indexer_sl): - idx = IntervalIndex.from_tuples([(1, 3), (3, 7)]) ser = Series(range(len(idx)), index=idx) @@ -188,7 +183,6 @@ def test_non_unique(self, indexer_sl): tm.assert_series_equal(expected, result) def test_non_unique_moar(self, indexer_sl): - idx = IntervalIndex.from_tuples([(1, 3), (1, 3), (3, 7)]) ser = Series(range(len(idx)), index=idx) diff --git a/pandas/tests/indexing/multiindex/test_getitem.py b/pandas/tests/indexing/multiindex/test_getitem.py index 3790a6e9a5319..f8ce59527d4fc 100644 --- a/pandas/tests/indexing/multiindex/test_getitem.py +++ b/pandas/tests/indexing/multiindex/test_getitem.py @@ -24,7 +24,6 @@ [(0, Series([1], index=[0])), (1, Series([2, 3], index=[1, 2]))], ) def test_series_getitem_multiindex(access_method, level1_value, expected): - # GH 6018 # series regression getitem with a multi-index diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 8d242ba1e1b4d..d95b27574cd82 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -227,7 +227,6 @@ def test_loc_multiindex_too_many_dims_raises(self): s.loc["a", "d", "g", "j"] def test_loc_multiindex_indexer_none(self): - # GH6788 # multi-index indexer is None (meaning take all) attributes = ["Attribute" + str(i) for i in range(1)] @@ -251,7 +250,6 @@ def test_loc_multiindex_indexer_none(self): tm.assert_frame_equal(result, expected) def test_loc_multiindex_incomplete(self): - # GH 7399 # incomplete indexers s = Series( diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 3ca057b80e578..c890754d2d433 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -125,7 +125,6 @@ def test_setitem_multiindex3(self): # all NaNs -> doesn't work in the "split" path (also for BlockManager actually) @td.skip_array_manager_not_yet_implemented def test_multiindex_setitem(self): - # GH 3738 # setting with a multi-index right hand side arrays = [ @@ -149,7 +148,6 @@ def test_multiindex_setitem(self): 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( @@ -181,7 +179,6 @@ def test_multiindex_setitem2(self): tm.assert_frame_equal(df, expected) def test_multiindex_assignment(self): - # GH3777 part 2 # mixed dtype @@ -344,7 +341,6 @@ def test_frame_setitem_multi_column(self): tm.assert_frame_equal(cp["a"], cp["b"]) def test_frame_setitem_multi_column2(self): - # --------------------------------------- # GH#1803 columns = MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]) @@ -437,7 +433,6 @@ def test_nonunique_assignment_1750(self): assert (df.xs((1, 1))["C"] == "_").all() def test_astype_assignment_with_dups(self): - # GH 4686 # assignment with dups that has a dtype change cols = MultiIndex.from_tuples([("A", "1"), ("B", "1"), ("A", "2")]) diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index 96d631964ab65..6a78b2243f07e 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -22,7 +22,6 @@ class TestMultiIndexSlicers: def test_per_axis_per_level_getitem(self): - # GH6134 # example test case ix = MultiIndex.from_product( @@ -165,7 +164,6 @@ def test_per_axis_per_level_getitem(self): tm.assert_frame_equal(result, df.iloc[[1, 3], :]) def test_multiindex_slicers_non_unique(self): - # GH 7106 # non-unique mi index support df = ( @@ -250,7 +248,6 @@ def test_multiindex_slicers_non_unique(self): tm.assert_series_equal(result, expected) def test_multiindex_slicers_datetimelike(self): - # GH 7429 # buggy/inconsistent behavior when slicing with datetime-like dates = [datetime(2012, 1, 1, 12, 12, 12) + timedelta(days=i) for i in range(6)] @@ -386,7 +383,6 @@ def test_multiindex_slicers_edges(self): tm.assert_frame_equal(result, expected) def test_per_axis_per_level_doc_examples(self): - # test index maker idx = pd.IndexSlice @@ -462,7 +458,6 @@ def test_per_axis_per_level_doc_examples(self): df.loc(axis=0)[:, :, ["C1", "C3"]] = -10 def test_loc_axis_arguments(self): - index = MultiIndex.from_product( [_mklbl("A", 4), _mklbl("B", 2), _mklbl("C", 4), _mklbl("D", 2)] ) @@ -529,7 +524,6 @@ def test_loc_axis_arguments(self): df.loc(axis=i)[:, :, ["C1", "C3"]] def test_loc_axis_single_level_multi_col_indexing_multiindex_col_df(self): - # GH29519 df = DataFrame( np.arange(27).reshape(3, 9), @@ -541,7 +535,6 @@ def test_loc_axis_single_level_multi_col_indexing_multiindex_col_df(self): tm.assert_frame_equal(result, expected) def test_loc_axis_single_level_single_col_indexing_multiindex_col_df(self): - # GH29519 df = DataFrame( np.arange(27).reshape(3, 9), @@ -554,7 +547,6 @@ def test_loc_axis_single_level_single_col_indexing_multiindex_col_df(self): tm.assert_frame_equal(result, expected) def test_loc_ax_single_level_indexer_simple_df(self): - # GH29519 # test single level indexing on single index column data frame df = DataFrame(np.arange(9).reshape(3, 3), columns=["a", "b", "c"]) @@ -563,7 +555,6 @@ def test_loc_ax_single_level_indexer_simple_df(self): tm.assert_series_equal(result, expected) def test_per_axis_per_level_setitem(self): - # test index maker idx = pd.IndexSlice diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index b94323e975cd7..747e7972aacf1 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -131,7 +131,6 @@ def test_slicing(self): tm.assert_series_equal(result, expected) def test_slicing_and_getting_ops(self): - # systematically test the slicing operations: # for all slicing ops: # - returning a dataframe @@ -253,7 +252,6 @@ def test_slicing_and_getting_ops(self): assert is_categorical_dtype(res_df["cats"].dtype) def test_slicing_doc_examples(self): - # GH 7918 cats = Categorical( ["a", "b", "b", "b", "c", "c", "c"], categories=["a", "b", "c"] @@ -425,7 +423,6 @@ def test_ix_categorical_index(self): 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 5e7abeb86705b..12d7d04353d6f 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -33,10 +33,8 @@ def random_text(nobs=100): class TestCaching: def test_slice_consolidate_invalidate_item_cache(self, using_copy_on_write): - # this is chained assignment, but will 'work' with option_context("chained_assignment", None): - # #3970 df = DataFrame({"aa": np.arange(5), "bb": [2.2] * 5}) @@ -144,7 +142,6 @@ def test_altering_series_clears_parent_cache(self, using_copy_on_write): class TestChaining: def test_setitem_chained_setfault(self, using_copy_on_write): - # GH6026 data = ["right", "left", "left", "left", "right", "left", "timeout"] mdata = ["right", "left", "left", "left", "right", "left", "none"] @@ -205,7 +202,6 @@ def test_setitem_chained_setfault(self, using_copy_on_write): @pytest.mark.arm_slow def test_detect_chained_assignment(self, using_copy_on_write): - with option_context("chained_assignment", "raise"): # work with the chain expected = DataFrame([[-5, 1], [-6, 3]], columns=list("AB")) @@ -230,7 +226,6 @@ def test_detect_chained_assignment(self, using_copy_on_write): def test_detect_chained_assignment_raises( self, using_array_manager, using_copy_on_write ): - # test with the chaining df = DataFrame( { @@ -266,7 +261,6 @@ def test_detect_chained_assignment_raises( @pytest.mark.arm_slow def test_detect_chained_assignment_fails(self, using_copy_on_write): - # Using a copy (the chain), fails df = DataFrame( { @@ -284,7 +278,6 @@ def test_detect_chained_assignment_fails(self, using_copy_on_write): @pytest.mark.arm_slow def test_detect_chained_assignment_doc_example(self, using_copy_on_write): - # Doc example df = DataFrame( { @@ -307,7 +300,6 @@ def test_detect_chained_assignment_doc_example(self, using_copy_on_write): def test_detect_chained_assignment_object_dtype( self, using_array_manager, using_copy_on_write ): - expected = DataFrame({"A": [111, "bbb", "ccc"], "B": [1, 2, 3]}) df = DataFrame({"A": ["aaa", "bbb", "ccc"], "B": [1, 2, 3]}) df_original = df.copy() @@ -334,7 +326,6 @@ def test_detect_chained_assignment_object_dtype( @pytest.mark.arm_slow def test_detect_chained_assignment_is_copy_pickle(self): - # gh-5475: Make sure that is_copy is picked up reconstruction df = DataFrame({"A": [1, 2]}) assert df._is_copy is None @@ -347,7 +338,6 @@ def test_detect_chained_assignment_is_copy_pickle(self): @pytest.mark.arm_slow def test_detect_chained_assignment_setting_entire_column(self): - # gh-5597: a spurious raise as we are setting the entire column here df = random_text(100000) @@ -368,7 +358,6 @@ def test_detect_chained_assignment_setting_entire_column(self): @pytest.mark.arm_slow def test_detect_chained_assignment_implicit_take(self): - # Implicitly take df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) @@ -398,14 +387,12 @@ def test_detect_chained_assignment_implicit_take2(self, using_copy_on_write): @pytest.mark.arm_slow def test_detect_chained_assignment_str(self): - df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df.loc[indexer, "letters"] = df.loc[indexer, "letters"].apply(str.lower) @pytest.mark.arm_slow def test_detect_chained_assignment_is_copy(self): - # an identical take, so no copy df = DataFrame({"a": [1]}).dropna() assert df._is_copy is None @@ -413,7 +400,6 @@ def test_detect_chained_assignment_is_copy(self): @pytest.mark.arm_slow def test_detect_chained_assignment_sorting(self): - df = DataFrame(np.random.randn(10, 4)) ser = df.iloc[:, 0].sort_values() @@ -422,7 +408,6 @@ def test_detect_chained_assignment_sorting(self): @pytest.mark.arm_slow def test_detect_chained_assignment_false_positives(self): - # see gh-6025: false positives df = DataFrame({"column1": ["a", "a", "a"], "column2": [4, 8, 9]}) str(df) @@ -438,7 +423,6 @@ def test_detect_chained_assignment_false_positives(self): @pytest.mark.arm_slow def test_detect_chained_assignment_undefined_column(self, using_copy_on_write): - # from SO: # https://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc df = DataFrame(np.arange(0, 9), columns=["count"]) @@ -457,7 +441,6 @@ def test_detect_chained_assignment_undefined_column(self, using_copy_on_write): def test_detect_chained_assignment_changing_dtype( self, using_array_manager, using_copy_on_write ): - # Mixed type setting but same dtype & changing dtype df = DataFrame( { @@ -495,7 +478,6 @@ def test_detect_chained_assignment_changing_dtype( assert df.loc[2, "C"] == "foo" def test_setting_with_copy_bug(self, using_copy_on_write): - # operating on a copy df = DataFrame( {"a": list(range(4)), "b": list("ab.."), "c": ["a", "b", np.nan, "d"]} @@ -557,7 +539,6 @@ def test_detect_chained_assignment_warning_stacklevel( # TODO(ArrayManager) fast_xs with array-like scalars is not yet working @td.skip_array_manager_not_yet_implemented def test_chained_getitem_with_lists(self): - # GH6394 # Regression in chained getitem indexing with embedded list-like from # 0.12 diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 82950e7a1d1ae..86d6246437ea1 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -43,7 +43,6 @@ def has_test(combo): yield else: - for combo in combos: if not has_test(combo): raise AssertionError( @@ -54,7 +53,6 @@ def has_test(combo): class CoercionBase: - klasses = ["index", "series"] dtypes = [ "object", @@ -74,7 +72,6 @@ def method(self): class TestSetitemCoercion(CoercionBase): - method = "setitem" # disable comprehensiveness tests, as most of these have been moved to @@ -176,7 +173,6 @@ def test_setitem_index_period(self): class TestInsertIndexCoercion(CoercionBase): - klasses = ["index"] method = "insert" @@ -254,7 +250,6 @@ def test_insert_float_index( [pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), 1], ) def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value): - obj = pd.DatetimeIndex( ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz ) @@ -267,7 +262,6 @@ def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value): self._assert_insert_conversion(obj, fill_val, exp, exp_dtype) if fill_val.tz: - # mismatched tzawareness ts = pd.Timestamp("2012-01-01") result = obj.insert(1, ts) @@ -363,7 +357,6 @@ def test_insert_index_bool(self): class TestWhereCoercion(CoercionBase): - method = "where" _cond = np.array([True, False, True, False]) @@ -543,7 +536,6 @@ def test_where_index_period(self): class TestFillnaSeriesCoercion(CoercionBase): - # not indexing, but place here for consistency method = "fillna" @@ -730,7 +722,6 @@ def test_fillna_series_timedelta64(self): ], ) def test_fillna_series_period(self, index_or_series, fill_val): - pi = pd.period_range("2016-01-01", periods=4, freq="D").insert(1, pd.NaT) assert isinstance(pi.dtype, pd.PeriodDtype) obj = index_or_series(pi) @@ -750,7 +741,6 @@ def test_fillna_index_period(self): class TestReplaceSeriesCoercion(CoercionBase): - klasses = ["series"] method = "replace" @@ -849,7 +839,6 @@ def test_replace_series(self, how, to_key, from_key, replacer): if (from_key == "float64" and to_key in ("int64")) or ( from_key == "complex128" and to_key in ("int64", "float64") ): - if not IS64 or is_platform_windows(): pytest.skip(f"32-bit platform buggy: {from_key} -> {to_key}") diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index e21bc6a4850a3..15e1fae77d65b 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -29,7 +29,6 @@ def test_get_loc_naive_dti_aware_str_deprecated(self): dti.get_loc(key) def test_indexing_with_datetime_tz(self): - # GH#8260 # support datetime64 with tz @@ -100,7 +99,6 @@ def test_consistency_with_tz_aware_scalar(self): assert result == expected def test_indexing_with_datetimeindex_tz(self, indexer_sl): - # GH 12050 # indexing on a series with a datetimeindex with tz index = date_range("2015-01-01", periods=2, tz="utc") diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 77b2b622a8439..9cccd2c45c9e7 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -48,7 +48,6 @@ def check(self, result, original, indexer, getitem): ], ) def test_scalar_non_numeric(self, index_func, frame_or_series, indexer_sl): - # GH 4892 # float_indexers should raise exceptions # on appropriate Index types & accessors @@ -93,7 +92,6 @@ def test_scalar_non_numeric_series_fallback(self, index_func): s[3.0] def test_scalar_with_mixed(self, indexer_sl): - s2 = Series([1, 2, 3], index=["a", "b", "c"]) s3 = Series([1, 2, 3], index=["a", "b", 1.5]) @@ -175,7 +173,6 @@ def test_scalar_integer_contains_float(self, index_func, frame_or_series): assert 3.0 in obj def test_scalar_float(self, frame_or_series): - # scalar float indexers work on a float index index = Index(np.arange(5.0)) s = gen_obj(frame_or_series, index) @@ -221,7 +218,6 @@ def test_scalar_float(self, frame_or_series): ) @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) def test_slice_non_numeric(self, index_func, idx, frame_or_series, indexer_sli): - # GH 4892 # float_indexers should raise exceptions # on appropriate Index types & accessors @@ -254,7 +250,6 @@ def test_slice_non_numeric(self, index_func, idx, frame_or_series, indexer_sli): indexer_sli(s)[idx] = 0 def test_slice_integer(self): - # same as above, but for Integer based indexes # these coerce to a like integer # oob indicates if we are out of bounds @@ -264,13 +259,11 @@ def test_slice_integer(self): (RangeIndex(5), False), (Index(np.arange(5, dtype=np.int64) + 10), True), ]: - # s is an in-range index s = Series(range(5), index=index) # getitem for idx in [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]: - result = s.loc[idx] # these are all label indexing @@ -284,7 +277,6 @@ def test_slice_integer(self): # getitem out-of-bounds for idx in [slice(-6, 6), slice(-6.0, 6.0)]: - result = s.loc[idx] # these are all label indexing @@ -311,7 +303,6 @@ def test_slice_integer(self): (slice(2, 3.5), slice(2, 4)), (slice(2.5, 3.5), slice(3, 4)), ]: - result = s.loc[idx] if oob: res = slice(0, 0) @@ -353,7 +344,6 @@ def test_integer_positional_indexing(self, idx): @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) def test_slice_integer_frame_getitem(self, index_func): - # similar to above, but on the getitem dim (of a DataFrame) index = index_func(5) @@ -361,7 +351,6 @@ def test_slice_integer_frame_getitem(self, index_func): # getitem for idx in [slice(0.0, 1), slice(0, 1.0), slice(0.0, 1.0)]: - result = s.loc[idx] indexer = slice(0, 2) self.check(result, s, indexer, False) @@ -377,7 +366,6 @@ def test_slice_integer_frame_getitem(self, index_func): # getitem out-of-bounds for idx in [slice(-10, 10), slice(-10.0, 10.0)]: - result = s.loc[idx] self.check(result, s, slice(-10, 10), True) @@ -396,7 +384,6 @@ def test_slice_integer_frame_getitem(self, index_func): (slice(0, 0.5), slice(0, 1)), (slice(0.5, 1.5), slice(1, 2)), ]: - result = s.loc[idx] self.check(result, s, res, False) @@ -412,7 +399,6 @@ def test_slice_integer_frame_getitem(self, index_func): @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func): - # similar to above, but on the getitem dim (of a DataFrame) index = index_func(5) @@ -438,7 +424,6 @@ def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func): @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) def test_slice_float(self, idx, frame_or_series, indexer_sl): - # same as above, but for floats index = Index(np.arange(5.0)) + 0.1 s = gen_obj(frame_or_series, index) @@ -457,7 +442,6 @@ def test_slice_float(self, idx, frame_or_series, indexer_sl): assert (result == 0).all() def test_floating_index_doc_example(self): - index = Index([1.5, 2, 3, 4.5, 5]) s = Series(range(5), index=index) assert s[3] == 2 @@ -465,7 +449,6 @@ def test_floating_index_doc_example(self): assert s.iloc[3] == 3 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) diff --git a/pandas/tests/indexing/test_iat.py b/pandas/tests/indexing/test_iat.py index 916303884df88..40d3e0c3e9430 100644 --- a/pandas/tests/indexing/test_iat.py +++ b/pandas/tests/indexing/test_iat.py @@ -8,7 +8,6 @@ def test_iat(float_frame): - for i, row in enumerate(float_frame.index): for j, col in enumerate(float_frame.columns): result = float_frame.iat[i, j] diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 27dd16172b992..86510c7be257b 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -146,7 +146,6 @@ def test_is_scalar_access(self): assert df.iloc._is_scalar_access((1, 0)) def test_iloc_exceeds_bounds(self): - # GH6296 # iloc should allow indexers that exceed the bounds df = DataFrame(np.random.random_sample((20, 5)), columns=list("ABCDE")) @@ -275,7 +274,6 @@ def test_iloc_getitem_invalid_scalar(self, frame_or_series): obj.iloc["a"] def test_iloc_array_not_mutating_negative_indices(self): - # GH 21867 array_with_neg_numbers = np.array([1, 2, -1]) array_copy = array_with_neg_numbers.copy() @@ -399,7 +397,6 @@ def test_iloc_getitem_slice(self): tm.assert_frame_equal(result, expected) def test_iloc_getitem_slice_dups(self): - df1 = DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]) df2 = DataFrame( np.random.randint(0, 10, size=20).reshape(10, 2), columns=["A", "C"] @@ -457,7 +454,6 @@ def test_iloc_setitem_axis_argument(self): tm.assert_frame_equal(df, expected) def test_iloc_setitem_list(self): - # setitem with an iloc list df = DataFrame( np.arange(9).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"] @@ -486,7 +482,6 @@ def test_iloc_setitem_pandas_object(self): tm.assert_series_equal(s, expected) def test_iloc_setitem_dups(self): - # GH 6766 # iloc with a mask aligning from another iloc df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}]) @@ -623,7 +618,6 @@ def test_iloc_getitem_labelled_frame(self): df.iloc["j", "D"] def test_iloc_getitem_doc_issue(self, using_array_manager): - # multi axis slicing issue with single block # surfaced in GH 6059 @@ -698,7 +692,6 @@ def test_iloc_setitem_series(self): tm.assert_series_equal(result, expected) def test_iloc_setitem_list_of_lists(self): - # GH 7551 # list-of-list is set incorrectly in mixed vs. single dtyped frames df = DataFrame( @@ -729,7 +722,6 @@ def test_iloc_setitem_with_scalar_index(self, indexer, value): assert is_scalar(result) and result == "Z" def test_iloc_mask(self): - # GH 3631, iloc with a mask (of a series) should raise df = DataFrame(list(range(5)), index=list("ABCDE"), columns=["a"]) mask = df.a % 2 == 0 @@ -800,7 +792,6 @@ def test_iloc_mask(self): ) def test_iloc_non_unique_indexing(self): - # GH 4017, non-unique indexing (on the axis) df = DataFrame({"A": [0.1] * 3000, "B": [1] * 3000}) idx = np.arange(30) * 99 @@ -818,7 +809,6 @@ def test_iloc_non_unique_indexing(self): df2.loc[idx] def test_iloc_empty_list_indexer_is_ok(self): - df = tm.makeCustomDataframe(5, 2) # vertical empty tm.assert_frame_equal( @@ -1110,7 +1100,6 @@ def view(self): tm.assert_frame_equal(result, df) def test_iloc_getitem_with_duplicates(self): - df = DataFrame(np.random.rand(3, 3), columns=list("ABC"), index=list("aab")) result = df.iloc[0] @@ -1195,7 +1184,6 @@ def test_iloc_getitem_int_single_ea_block_view(self): assert ser[0] == arr[-1] def test_iloc_setitem_multicolumn_to_datetime(self): - # GH#20511 df = DataFrame({"A": ["2022-01-01", "2022-01-02"], "B": ["2021", "2022"]}) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 230605d2f3235..3d45b238017ca 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -171,7 +171,6 @@ def test_inf_upcast(self): tm.assert_index_equal(result, expected) def test_setitem_dtype_upcast(self): - # GH3216 df = DataFrame([{"a": 1}, {"a": 3, "b": 2}]) df["c"] = np.nan @@ -185,7 +184,6 @@ def test_setitem_dtype_upcast(self): @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), @@ -224,7 +222,6 @@ def test_setitem_dtype_upcast3(self): assert is_float_dtype(left["baz"]) def test_dups_fancy_indexing(self): - # GH 3455 df = tm.makeCustomDataframe(10, 3) @@ -234,7 +231,6 @@ def test_dups_fancy_indexing(self): 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() @@ -274,7 +270,6 @@ def test_dups_fancy_indexing_not_in_order(self): 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( @@ -287,14 +282,12 @@ def test_dups_fancy_indexing_only_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": vals}) with pytest.raises(KeyError, match="not in index"): 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="not in index"): @@ -309,7 +302,6 @@ def test_dups_fancy_indexing2(self): 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"] @@ -335,7 +327,6 @@ def test_duplicate_int_indexing(self, indexer_sl): tm.assert_series_equal(result, expected) def test_indexing_mixed_frame_bug(self): - # GH3492 df = DataFrame( {"a": {1: "aaa", 2: "bbb", 3: "ccc"}, "b": {1: 111, 2: 222, 3: 333}} @@ -359,7 +350,6 @@ def test_multitype_list_index_access(self): assert df[21].shape[0] == df.shape[0] def test_set_index_nan(self): - # GH 3586 df = DataFrame( { @@ -438,7 +428,6 @@ def test_set_index_nan(self): tm.assert_frame_equal(result, df) def test_multi_assign(self): - # GH 3626, an assignment of a sub-df to a df df = DataFrame( { @@ -505,7 +494,6 @@ def test_multi_assign_broadcasting_rhs(self): tm.assert_frame_equal(df, expected) def test_setitem_list(self): - # GH 6043 # iloc with a list df = DataFrame(index=[0, 1], columns=[0]) @@ -541,7 +529,6 @@ def test_string_slice_empty(self): df.loc["2011", 0] def test_astype_assignment(self): - # GH4312 (iloc) df_orig = DataFrame( [["1", "2", "3", ".4", 5, 6.0, "foo"]], columns=list("ABCDEFG") @@ -593,7 +580,6 @@ def test_astype_assignment_full_replacements(self): @pytest.mark.parametrize("indexer", [tm.getitem, tm.loc]) def test_index_type_coercion(self, indexer): - # GH 11836 # if we have an index type and set it with something that looks # to numpy like the same, but is actually, not @@ -602,7 +588,6 @@ def test_index_type_coercion(self, indexer): # integer indexes for s in [Series(range(5)), Series(range(5), index=range(1, 6))]: - assert is_integer_dtype(s.index) s2 = s.copy() @@ -622,7 +607,6 @@ def test_index_type_coercion(self, indexer): assert is_object_dtype(s2.index) for s in [Series(range(5), index=np.arange(5.0))]: - assert is_float_dtype(s.index) s2 = s.copy() diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 8aff76c0e1fee..2243879050c0c 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -64,14 +64,12 @@ def test_not_change_nan_loc(series, new_series, expected_ser): class TestLoc: @pytest.mark.parametrize("kind", ["series", "frame"]) def test_loc_getitem_int(self, kind, request): - # int label obj = request.getfixturevalue(f"{kind}_labels") check_indexing_smoketest_or_raises(obj, "loc", 2, fails=KeyError) @pytest.mark.parametrize("kind", ["series", "frame"]) def test_loc_getitem_label(self, kind, request): - # label obj = request.getfixturevalue(f"{kind}_empty") check_indexing_smoketest_or_raises(obj, "loc", "c", fails=KeyError) @@ -167,7 +165,6 @@ def test_loc_getitem_bool(self, kind, request): ) @pytest.mark.parametrize("kind", ["series", "frame"]) def test_loc_getitem_label_slice(self, slc, typs, axes, fails, kind, request): - # label slices (with ints) # real label slices @@ -312,7 +309,6 @@ def test_loc_getitem_dups(self): tm.assert_series_equal(result, expected) def test_loc_getitem_dups2(self): - # GH4726 # dup indexing with iloc/loc df = DataFrame( @@ -333,7 +329,6 @@ def test_loc_getitem_dups2(self): tm.assert_series_equal(result, expected) def test_loc_setitem_dups(self): - # GH 6541 df_orig = DataFrame( { @@ -432,7 +427,6 @@ def test_loc_getitem_int_slice(self): pass def test_loc_to_fail(self): - # GH3449 df = DataFrame( np.random.random((3, 3)), index=["a", "b", "c"], columns=["e", "f", "g"] @@ -537,7 +531,6 @@ def test_loc_index(self): tm.assert_frame_equal(result, expected) def test_loc_general(self): - df = DataFrame( np.random.rand(4, 4), columns=["A", "B", "C", "D"], @@ -932,7 +925,6 @@ def test_loc_setitem_missing_columns(self, index, box, expected): tm.assert_frame_equal(df, expected) def test_loc_coercion(self): - # GH#12411 df = DataFrame({"date": [Timestamp("20130101").tz_localize("UTC"), pd.NaT]}) expected = df.dtypes @@ -1016,7 +1008,6 @@ def test_loc_non_unique(self): @pytest.mark.arm_slow @pytest.mark.parametrize("length, l2", [[900, 100], [900000, 100000]]) def test_loc_non_unique_memory_error(self, length, l2): - # GH 4280 # non_unique index with a large selection triggers a memory error @@ -1061,7 +1052,6 @@ def test_loc_name(self): assert result == "index_name" def test_loc_empty_list_indexer_is_ok(self): - df = tm.makeCustomDataframe(5, 2) # vertical empty tm.assert_frame_equal( @@ -2925,7 +2915,6 @@ def test_loc_setitem_uint8_upcast(value): ], ) def test_loc_setitem_using_datetimelike_str_as_index(fill_val, exp_dtype): - data = ["2022-01-02", "2022-01-03", "2022-01-04", fill_val.date()] index = DatetimeIndex(data, tz=fill_val.tz, dtype=exp_dtype) df = DataFrame([10, 11, 12, 14], columns=["a"], index=index) @@ -3063,7 +3052,6 @@ def test_basic_setitem_with_labels(self, datetime_series): tm.assert_series_equal(cp, exp) def test_loc_setitem_listlike_of_ints(self): - # integer indexes, be careful ser = Series(np.random.randn(10), index=list(range(0, 20, 2))) inds = [0, 4, 6] diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 3217c1cf7a2ac..a2fcd18ba5bfe 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -72,7 +72,6 @@ def test_loc_setitem_zerolen_list_length_must_match_columns(self): tm.assert_frame_equal(df, exp) def test_partial_set_empty_frame(self): - # partially set with an empty object # frame df = DataFrame() @@ -229,7 +228,6 @@ def test_partial_set_empty_frame_empty_consistencies(self): class TestPartialSetting: def test_partial_setting(self): - # GH2578, allow ix and friends to partially set # series @@ -358,7 +356,6 @@ def test_partial_setting2(self): tm.assert_frame_equal(df, expected) def test_partial_setting_mixed_dtype(self): - # in a mixed dtype environment, try to preserve dtypes # by appending df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"]) @@ -533,7 +530,6 @@ def test_setitem_with_expansion_numeric_into_datetimeindex(self, key): tm.assert_frame_equal(df, expected) def test_partial_set_invalid(self): - # GH 4940 # allow only setting of 'valid' values diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index b1c3008b04d3e..1cb8c4f808fbd 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -73,7 +73,6 @@ def test_float_index_at_iat(self): assert ser.iat[i] == i + 1 def test_at_iat_coercion(self): - # as timestamp is not a tuple! dates = date_range("1/1/2000", periods=8) df = DataFrame(np.random.randn(8, 4), index=dates, columns=["A", "B", "C", "D"]) @@ -103,7 +102,6 @@ def test_iloc_iat_coercion_datelike(self, indexer_ial, ser, expected): assert result == expected def test_imethods_with_dups(self): - # GH6493 # iat/iloc with dups diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index d5702a545c0d8..f60c38c041fcf 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -394,7 +394,6 @@ def test_duplicate_ref_loc_failure(self): mgr.iget(1) def test_pickle(self, mgr): - mgr2 = tm.round_trip_pickle(mgr) tm.assert_frame_equal(DataFrame(mgr), DataFrame(mgr2)) @@ -471,7 +470,6 @@ def test_set_change_dtype(self, mgr): def test_copy(self, mgr): cp = mgr.copy(deep=False) for blk, cp_blk in zip(mgr.blocks, cp.blocks): - # view assertion tm.assert_equal(cp_blk.values, blk.values) if isinstance(blk.values, np.ndarray): @@ -485,7 +483,6 @@ def test_copy(self, mgr): mgr._consolidate_inplace() cp = mgr.copy(deep=True) for blk, cp_blk in zip(mgr.blocks, cp.blocks): - bvals = blk.values cpvals = cp_blk.values diff --git a/pandas/tests/internals/test_managers.py b/pandas/tests/internals/test_managers.py index 045c3cbb18ba6..75aa901fce910 100644 --- a/pandas/tests/internals/test_managers.py +++ b/pandas/tests/internals/test_managers.py @@ -14,7 +14,6 @@ def test_dataframe_creation(): - with pd.option_context("mode.data_manager", "block"): df_block = pd.DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3], "c": [4, 5, 6]}) assert isinstance(df_block._mgr, BlockManager) @@ -46,7 +45,6 @@ def test_dataframe_creation(): def test_series_creation(): - with pd.option_context("mode.data_manager", "block"): s_block = pd.Series([1, 2, 3], name="A", index=["a", "b", "c"]) assert isinstance(s_block._mgr, SingleBlockManager) diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index 2fac7ca0b3e00..b863e85cae457 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -98,7 +98,6 @@ def s3_base(worker_id): stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) as proc: - timeout = 5 while timeout > 0: try: diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index be0428a2b0fce..d28296ec2e380 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -251,7 +251,6 @@ def test_if_sheet_exists_raises(ext, if_sheet_exists, msg): def test_to_excel_with_openpyxl_engine(ext): # GH 29854 with tm.ensure_clean(ext) as filename: - df1 = DataFrame({"A": np.linspace(1, 10, 10)}) df2 = DataFrame({"B": np.linspace(1, 20, 10)}) df = pd.concat([df1, df2], axis=1) diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 3f2fecbfb48a6..5fdd0e4311d88 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -357,7 +357,6 @@ def test_usecols_wrong_type(self, read_ext): pd.read_excel("test1" + read_ext, usecols=["E1", 0]) def test_excel_stop_iterator(self, read_ext): - parsed = pd.read_excel("test2" + read_ext, sheet_name="Sheet1") expected = DataFrame([["aaaa", "bbbbb"]], columns=["Test", "Test1"]) tm.assert_frame_equal(parsed, expected) @@ -447,7 +446,6 @@ def test_reader_special_dtypes(self, request, read_ext): # GH8212 - support for converters and missing values def test_reader_converters(self, read_ext): - basename = "test_converters" expected = DataFrame.from_dict( @@ -609,7 +607,6 @@ def test_use_nullable_dtypes_string(self, read_ext, string_storage): import pyarrow as pa with pd.option_context("mode.string_storage", string_storage): - df = DataFrame( { "a": np.array(["a", "b"], dtype=np.object_), @@ -789,7 +786,6 @@ def test_sheet_name(self, request, read_ext, df_ref): tm.assert_frame_equal(df2, df_ref, check_names=False) def test_excel_read_buffer(self, read_ext): - pth = "test1" + read_ext expected = pd.read_excel(pth, sheet_name="Sheet1", index_col=0) with open(pth, "rb") as f: @@ -889,7 +885,6 @@ def test_read_from_s3_object(self, read_ext, s3_resource, s3so): @pytest.mark.slow def test_read_from_file_url(self, read_ext, datapath): - # FILE localtable = os.path.join(datapath("io", "data", "excel"), "test1" + read_ext) local_table = pd.read_excel(localtable) @@ -916,7 +911,6 @@ def test_read_from_pathlib_path(self, read_ext): @td.skip_if_no("py.path") @td.check_file_leaks def test_read_from_py_localpath(self, read_ext): - # GH12655 from py.path import local as LocalPath @@ -930,7 +924,6 @@ def test_read_from_py_localpath(self, read_ext): @td.check_file_leaks def test_close_from_py_localpath(self, read_ext): - # GH31467 str_path = os.path.join("test1" + read_ext) with open(str_path, "rb") as f: diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index f26df440d263b..b26d59b9bdebb 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -46,7 +46,6 @@ def test_styler_to_excel_unstyled(engine): openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl with contextlib.closing(openpyxl.load_workbook(path)) as wb: - for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns): assert len(col1) == len(col2) for cell1, cell2 in zip(col1, col2): @@ -141,7 +140,6 @@ def test_styler_to_excel_basic(engine, css, attrs, expected): openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test unstyled data cell does not have expected styles # test styled cell has expected styles u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) @@ -181,7 +179,6 @@ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected): openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test null styled index cells does not have expected styles # test styled cell has expected styles ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1) @@ -243,7 +240,6 @@ def test_styler_to_excel_border_style(engine, border_style): openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test unstyled data cell does not have expected styles # test styled cell has expected styles u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index ec6484c5c2149..f2df065571c6d 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -329,7 +329,6 @@ def test_multiindex_interval_datetimes(self, ext): @pytest.mark.usefixtures("set_engine") class TestExcelWriter: def test_excel_sheet_size(self, path): - # GH 26080 breaking_row_count = 2**20 + 1 breaking_col_count = 2**14 + 1 @@ -502,7 +501,6 @@ def test_inf_roundtrip(self, path): tm.assert_frame_equal(df, recons) def test_sheets(self, frame, tsframe, path): - # freq doesn't round-trip index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 75aa9fb253bbc..af117af0c8d3d 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -192,7 +192,6 @@ def test_eng_float_formatter(self, float_frame): ], ) def test_show_counts(self, row, columns, show_counts, result): - # Explicit cast to float to avoid implicit cast when setting nan df = DataFrame(1, columns=range(10), index=range(10)).astype({1: "float"}) df.iloc[1, 1] = np.nan @@ -731,7 +730,6 @@ def test_east_asian_unicode_false(self): def test_east_asian_unicode_true(self): # Enable Unicode option ----------------------------------------- with option_context("display.unicode.east_asian_width", True): - # mid col df = DataFrame( {"a": ["あ", "いいい", "う", "ええええええ"], "b": [1, 222, 33333, 4]}, @@ -847,7 +845,6 @@ def test_east_asian_unicode_true(self): # truncate with option_context("display.max_rows", 3, "display.max_columns", 3): - df = DataFrame( { "a": ["あああああ", "い", "う", "えええ"], @@ -984,7 +981,6 @@ def test_to_string_truncate_multilevel(self): assert has_doubly_truncated_repr(df) def test_truncate_with_different_dtypes(self): - # 11594, 12045 # when truncated the dtypes of the splits can differ @@ -1017,7 +1013,6 @@ def test_truncate_with_different_dtypes_multiindex(self): assert result.startswith(result2) def test_datetimelike_frame(self): - # GH 12211 df = DataFrame({"date": [Timestamp("20130101").tz_localize("UTC")] + [NaT] * 5}) @@ -1325,7 +1320,6 @@ def test_index_with_nan(self): assert result == expected def test_to_string(self): - # big mixed biggie = DataFrame( {"A": np.random.randn(200), "B": tm.makeStringIndex(200)}, @@ -1476,7 +1470,6 @@ def test_to_string_float_formatting(self): assert df_s == expected def test_to_string_float_format_no_fixed_width(self): - # GH 21625 df = DataFrame({"x": [0.19999]}) expected = " x\n0 0.200" @@ -1823,7 +1816,6 @@ def test_repr_html_long(self): def test_repr_html_float(self): with option_context("display.max_rows", 60): - max_rows = get_option("display.max_rows") h = max_rows - 1 df = DataFrame( @@ -2283,7 +2275,6 @@ def test_east_asian_unicode_series(self): # Enable Unicode option ----------------------------------------- with option_context("display.unicode.east_asian_width", True): - # unicode index s = Series(["a", "bb", "CCC", "D"], index=["あ", "いい", "ううう", "ええええ"]) expected = ( @@ -2408,7 +2399,6 @@ def test_float_trim_zeros(self): assert "+10" in line def test_datetimeindex(self): - index = date_range("20130102", periods=6) s = Series(1, index=index) result = s.to_string() @@ -2869,7 +2859,6 @@ def test_set_option_precision(self, value, expected): # Precision was incorrectly shown with option_context("display.precision", 0): - df_value = DataFrame(value) assert str(df_value) == expected @@ -3088,7 +3077,6 @@ def test_date_nanos(self): assert result[0].strip() == "1970-01-01 00:00:00.000000200" def test_dates_display(self): - # 10170 # make sure that we are consistently display date formatting x = Series(date_range("20130101 09:00:00", periods=5, freq="D")) @@ -3137,7 +3125,6 @@ def format_func(x): assert result == ["2016-01", "2016-02"] def test_datetime64formatter_hoursecond(self): - x = Series( pd.to_datetime(["10:10:10.100", "12:12:12.120"], format="%H:%M:%S.%f") ) diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py index a6a0b2781dc3b..974a2174cb03b 100644 --- a/pandas/tests/io/generate_legacy_storage_files.py +++ b/pandas/tests/io/generate_legacy_storage_files.py @@ -300,7 +300,6 @@ def platform_name(): def write_legacy_pickles(output_dir): - version = pandas.__version__ print( diff --git a/pandas/tests/io/json/test_compression.py b/pandas/tests/io/json/test_compression.py index ab97fb1740496..143d2431d4147 100644 --- a/pandas/tests/io/json/test_compression.py +++ b/pandas/tests/io/json/test_compression.py @@ -55,7 +55,6 @@ def test_with_s3_url(compression, s3_resource, s3so): def test_lines_with_compression(compression): - with tm.ensure_clean() as path: df = pd.read_json('{"a": [1, 2, 3], "b": [4, 5, 6]}') df.to_json(path, orient="records", lines=True, compression=compression) @@ -64,7 +63,6 @@ def test_lines_with_compression(compression): def test_chunksize_with_compression(compression): - with tm.ensure_clean() as path: df = pd.read_json('{"a": ["foo", "bar", "baz"], "b": [4, 5, 6]}') df.to_json(path, orient="records", lines=True, compression=compression) diff --git a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py index d9232a6bddf61..75845148f6581 100644 --- a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py +++ b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py @@ -143,7 +143,6 @@ def df(self, da, dc, sa, ia): ) def test_build_date_series(self, da): - s = Series(da, name="a") s.index.name = "id" result = s.to_json(orient="table", date_format="iso") @@ -169,7 +168,6 @@ def test_build_date_series(self, da): assert result == expected def test_build_decimal_series(self, dc): - s = Series(dc, name="a") s.index.name = "id" result = s.to_json(orient="table", date_format="iso") @@ -245,7 +243,6 @@ def test_build_int64_series(self, ia): assert result == expected def test_to_json(self, df): - df = df.copy() df.index.name = "idx" result = df.to_json(orient="table", date_format="iso") diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index bb72e36f8d6cc..4f025e84e2bd3 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -250,7 +250,6 @@ def test_nested_object_record_path(self): tm.assert_frame_equal(result, expected) def test_more_deeply_nested(self, deep_nested): - result = json_normalize( deep_nested, ["states", "cities"], meta=["country", ["states", "name"]] ) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index db839353934b0..7e2d123c72b01 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -242,7 +242,6 @@ def test_roundtrip_timestamp(self, orient, convert_axes, datetime_frame): @pytest.mark.parametrize("convert_axes", [True, False]) def test_roundtrip_mixed(self, orient, convert_axes): - index = pd.Index(["a", "b", "c", "d", "e"]) values = { "A": [0.0, 1.0, 2.0, 3.0, 4.0], @@ -721,13 +720,11 @@ def test_frame_from_json_precise_float(self): tm.assert_frame_equal(result, df) def test_typ(self): - s = Series(range(6), index=["a", "b", "c", "d", "e", "f"], dtype="int64") result = read_json(s.to_json(), typ=None) tm.assert_series_equal(result, s) def test_reconstruction_index(self): - df = DataFrame([[1, 2, 3], [4, 5, 6]]) result = read_json(df.to_json()) @@ -744,7 +741,6 @@ def test_path(self, float_frame, int_frame, datetime_frame): read_json(path) def test_axis_dates(self, datetime_series, datetime_frame): - # frame json = datetime_frame.to_json() result = read_json(json) @@ -757,7 +753,6 @@ def test_axis_dates(self, datetime_series, datetime_frame): assert result.name is None def test_convert_dates(self, datetime_series, datetime_frame): - # frame df = datetime_frame df["date"] = Timestamp("20130101") @@ -1920,7 +1915,6 @@ def test_read_json_nullable(self, string_storage, dtype_backend, orient, option) ) if dtype_backend == "pyarrow": - from pandas.arrays import ArrowExtensionArray expected = DataFrame( diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index 472b08963425b..6b635a4f46972 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -809,7 +809,6 @@ def test_0d_array(self): class TestPandasJSONTests: def test_dataframe(self, orient): - dtype = np.int64 df = DataFrame( diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py index b08ec8c1172bc..3f1d013c5471d 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -394,7 +394,6 @@ def test_context_manageri_user_provided(all_parsers, datapath): parser = all_parsers with open(datapath("io", "data", "csv", "iris.csv")) as path: - reader = parser.read_csv(path, chunksize=1) assert not reader.handles.handle.closed try: diff --git a/pandas/tests/io/parser/common/test_iterator.py b/pandas/tests/io/parser/common/test_iterator.py index 5966a2fd6e095..939ed0e73a5ee 100644 --- a/pandas/tests/io/parser/common/test_iterator.py +++ b/pandas/tests/io/parser/common/test_iterator.py @@ -30,7 +30,6 @@ def test_iterator(all_parsers): expected = parser.read_csv(StringIO(data), **kwargs) with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader: - first_chunk = reader.read(3) tm.assert_frame_equal(first_chunk, expected[:3]) diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py index 845b6e373edd7..f5a7eb4ccd2fa 100644 --- a/pandas/tests/io/parser/common/test_read_errors.py +++ b/pandas/tests/io/parser/common/test_read_errors.py @@ -54,7 +54,6 @@ def test_bad_stream_exception(all_parsers, csv_dir_path): with open(path, "rb") as handle, codecs.StreamRecoder( handle, utf8.encode, utf8.decode, codec.streamreader, codec.streamwriter ) as stream: - with pytest.raises(UnicodeDecodeError, match=msg): parser.read_csv(stream) diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py index bd5ebfeffca14..21fec973897c0 100644 --- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py +++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py @@ -452,7 +452,6 @@ def test_use_nullable_dtypes_string(all_parsers, string_storage): pa = pytest.importorskip("pyarrow") with pd.option_context("mode.string_storage", string_storage): - parser = all_parsers data = """a,b diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 0b16d1d9ec6b0..3768f37b65546 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -89,7 +89,6 @@ def tips_df(datapath): class TestS3: @td.skip_if_no("s3fs") def test_parse_public_s3_bucket(self, tips_df, s3so): - # more of an integration test due to the not-public contents portion # can probably mock this though. for ext, comp in [("", None), (".gz", "gzip"), (".bz2", "bz2")]: @@ -109,7 +108,6 @@ def test_parse_public_s3_bucket(self, tips_df, s3so): tm.assert_frame_equal(df, tips_df) def test_parse_public_s3n_bucket(self, tips_df, s3so): - # Read from AWS s3 as "s3n" URL df = read_csv("s3n://pandas-test/tips.csv", nrows=10, storage_options=s3so) assert isinstance(df, DataFrame) diff --git a/pandas/tests/io/pytables/common.py b/pandas/tests/io/pytables/common.py index 9446d9df3a038..ef90d97a5a98c 100644 --- a/pandas/tests/io/pytables/common.py +++ b/pandas/tests/io/pytables/common.py @@ -27,7 +27,6 @@ def safe_close(store): def ensure_clean_store( path, mode="a", complevel=None, complib=None, fletcher32=False ) -> Generator[HDFStore, None, None]: - with tempfile.TemporaryDirectory() as tmpdirname: tmp_path = pathlib.Path(tmpdirname, path) with HDFStore( diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index fdfb693ae0694..c37e68f537ebb 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -27,13 +27,10 @@ def test_append(setup_path): - with ensure_clean_store(setup_path) as store: - # this is allowed by almost always don't want to do it # tables.NaturalNameWarning): with catch_warnings(record=True): - df = tm.makeTimeDataFrame() _maybe_remove(store, "df1") store.append("df1", df[:10]) @@ -96,9 +93,7 @@ def test_append(setup_path): def test_append_series(setup_path): - with ensure_clean_store(setup_path) as store: - # basic ss = tm.makeStringSeries() ts = tm.makeTimeSeries() @@ -143,7 +138,6 @@ def test_append_series(setup_path): def test_append_some_nans(setup_path): - with ensure_clean_store(setup_path) as store: df = DataFrame( { @@ -190,9 +184,7 @@ def test_append_some_nans(setup_path): def test_append_all_nans(setup_path): - with ensure_clean_store(setup_path) as store: - df = DataFrame( {"A1": np.random.randn(20), "A2": np.random.randn(20)}, index=np.arange(20), @@ -276,7 +268,6 @@ def test_append_all_nans(setup_path): def test_append_frame_column_oriented(setup_path): with ensure_clean_store(setup_path) as store: - # column oriented df = tm.makeTimeDataFrame() df.index = df.index._with_freq(None) # freq doesn't round-trip @@ -305,12 +296,9 @@ def test_append_frame_column_oriented(setup_path): def test_append_with_different_block_ordering(setup_path): - # GH 4096; using same frames, but different block orderings with ensure_clean_store(setup_path) as store: - for i in range(10): - df = DataFrame(np.random.randn(10, 2), columns=list("AB")) df["index"] = range(10) df["index"] += i * 10 @@ -331,7 +319,6 @@ def test_append_with_different_block_ordering(setup_path): # test a different ordering but with more fields (like invalid # combinations) with ensure_clean_store(setup_path) as store: - df = DataFrame(np.random.randn(10, 2), columns=list("AB"), dtype="float64") df["int64"] = Series([1] * len(df), dtype="int64") df["int16"] = Series([1] * len(df), dtype="int16") @@ -355,7 +342,6 @@ def test_append_with_different_block_ordering(setup_path): def test_append_with_strings(setup_path): - with ensure_clean_store(setup_path) as store: with catch_warnings(record=True): @@ -434,7 +420,6 @@ def check_col(key, name, size): tm.assert_frame_equal(result, df) with ensure_clean_store(setup_path) as store: - df = DataFrame({"A": "foo", "B": "bar"}, index=range(10)) # a min_itemsize that creates a data_column @@ -473,9 +458,7 @@ def check_col(key, name, size): def test_append_with_empty_string(setup_path): - with ensure_clean_store(setup_path) as store: - # with all empty strings (GH 12242) df = DataFrame({"x": ["a", "b", "c", "d", "e", "f", ""]}) store.append("df", df[:-1], min_itemsize={"x": 1}) @@ -484,7 +467,6 @@ def test_append_with_empty_string(setup_path): def test_append_with_data_columns(setup_path): - with ensure_clean_store(setup_path) as store: df = tm.makeTimeDataFrame() df.iloc[0, df.columns.get_loc("B")] = 1.0 @@ -653,7 +635,6 @@ def test_append_hierarchical(tmp_path, setup_path, multiindex_dataframe_random_d def test_append_misc(setup_path): - with ensure_clean_store(setup_path) as store: df = tm.makeDataFrame() store.append("df", df, chunksize=1) @@ -684,7 +665,6 @@ def test_append_misc_chunksize(setup_path, chunksize): def test_append_misc_empty_frame(setup_path): # empty frame, GH4273 with ensure_clean_store(setup_path) as store: - # 0 len df_empty = DataFrame(columns=list("ABC")) store.append("df", df_empty) @@ -709,9 +689,7 @@ def test_append_misc_empty_frame(setup_path): # a datetime64 column no longer raising an error @td.skip_array_manager_not_yet_implemented def test_append_raise(setup_path): - with ensure_clean_store(setup_path) as store: - # test append with invalid input to get good error messages # list in column @@ -801,7 +779,6 @@ def test_append_with_timedelta(setup_path): df.loc[3:5, "C"] = np.nan with ensure_clean_store(setup_path) as store: - # table _maybe_remove(store, "df") store.append("df", df, data_columns=True) @@ -841,7 +818,6 @@ def test_append_to_multiple(setup_path): df = concat([df1, df2], axis=1) with ensure_clean_store(setup_path) as store: - # exceptions msg = "append_to_multiple requires a selector that is in passed dict" with pytest.raises(ValueError, match=msg): @@ -875,7 +851,6 @@ def test_append_to_multiple_dropna(setup_path): df = concat([df1, df2], axis=1) with ensure_clean_store(setup_path) as store: - # dropna=True should guarantee rows are synchronized store.append_to_multiple( {"df1": ["A", "B"], "df2": None}, df, selector="df1", dropna=True diff --git a/pandas/tests/io/pytables/test_categorical.py b/pandas/tests/io/pytables/test_categorical.py index 7c2ab9b4f6ec0..bb95762950d8e 100644 --- a/pandas/tests/io/pytables/test_categorical.py +++ b/pandas/tests/io/pytables/test_categorical.py @@ -20,9 +20,7 @@ def test_categorical(setup_path): - with ensure_clean_store(setup_path) as store: - # Basic _maybe_remove(store, "s") s = Series( @@ -143,7 +141,6 @@ def test_categorical(setup_path): def test_categorical_conversion(tmp_path, setup_path): - # GH13322 # Check that read_hdf with categorical columns doesn't return rows if # where criteria isn't met. diff --git a/pandas/tests/io/pytables/test_complex.py b/pandas/tests/io/pytables/test_complex.py index 870458e93689f..051221d165060 100644 --- a/pandas/tests/io/pytables/test_complex.py +++ b/pandas/tests/io/pytables/test_complex.py @@ -134,7 +134,6 @@ def test_complex_across_dimensions(tmp_path, setup_path): df = DataFrame({"A": s, "B": s}) with catch_warnings(record=True): - objs = [df] comps = [tm.assert_frame_equal] for obj, comp in zip(objs, comps): diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py index 7629e8ca7dfc2..295cce970889c 100644 --- a/pandas/tests/io/pytables/test_errors.py +++ b/pandas/tests/io/pytables/test_errors.py @@ -26,7 +26,6 @@ def test_pass_spec_to_storer(setup_path): - df = tm.makeDataFrame() with ensure_clean_store(setup_path) as store: @@ -57,9 +56,7 @@ def test_table_index_incompatible_dtypes(setup_path): def test_unimplemented_dtypes_table_columns(setup_path): - with ensure_clean_store(setup_path) as store: - dtypes = [("date", datetime.date(2001, 1, 2))] # currently not supported dtypes #### @@ -88,11 +85,8 @@ def test_unimplemented_dtypes_table_columns(setup_path): def test_invalid_terms(tmp_path, setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - df = tm.makeTimeDataFrame() df["string"] = "foo" df.loc[df.index[0:4], "string"] = "bar" diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py index 19a92163c6dd2..49190daa37442 100644 --- a/pandas/tests/io/pytables/test_file_handling.py +++ b/pandas/tests/io/pytables/test_file_handling.py @@ -30,7 +30,6 @@ @pytest.mark.parametrize("mode", ["r", "r+", "a", "w"]) def test_mode(setup_path, tmp_path, mode): - df = tm.makeTimeDataFrame() msg = r"[\S]* does not exist" path = tmp_path / setup_path @@ -88,7 +87,6 @@ def test_default_mode(tmp_path, setup_path): def test_reopen_handle(tmp_path, setup_path): - path = tmp_path / setup_path store = HDFStore(path, mode="a") @@ -141,9 +139,7 @@ def test_reopen_handle(tmp_path, setup_path): def test_open_args(setup_path): - with tm.ensure_clean(setup_path) as path: - df = tm.makeDataFrame() # create an in memory store @@ -163,7 +159,6 @@ def test_open_args(setup_path): def test_flush(setup_path): - with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() store.flush() @@ -243,7 +238,7 @@ def test_complibs(tmp_path, setup_path): all_levels = range(0, 10) all_tests = [(lib, lvl) for lib in all_complibs for lvl in all_levels] - for (lib, lvl) in all_tests: + for lib, lvl in all_tests: tmpfile = tmp_path / setup_path gname = "foo" @@ -266,7 +261,6 @@ def test_complibs(tmp_path, setup_path): not is_platform_little_endian(), reason="reason platform is not little endian" ) def test_encoding(setup_path): - with ensure_clean_store(setup_path) as store: df = DataFrame({"A": "foo", "B": "bar"}, index=range(5)) df.loc[2, "A"] = np.nan @@ -343,7 +337,6 @@ def test_multiple_open_close(tmp_path, setup_path): store1.close() else: - # multiples store1 = HDFStore(path) store2 = HDFStore(path) diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py index dff7e2144d3c2..0dcc9f7f1b9c2 100644 --- a/pandas/tests/io/pytables/test_keys.py +++ b/pandas/tests/io/pytables/test_keys.py @@ -14,7 +14,6 @@ def test_keys(setup_path): - with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() store["b"] = tm.makeStringSeries() @@ -62,12 +61,10 @@ def test_keys_illegal_include_keyword_value(setup_path): def test_keys_ignore_hdf_softlink(setup_path): - # GH 20523 # Puts a softlink into HDF file and rereads with ensure_clean_store(setup_path) as store: - df = DataFrame({"A": range(5), "B": range(5)}) store.put("df", df) diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 8cff9e65ce23b..d2b0519d6cf3d 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -49,7 +49,6 @@ def test_format_kwarg_in_constructor(tmp_path, setup_path): def test_api_default_format(tmp_path, setup_path): - # default_format option with ensure_clean_store(setup_path) as store: df = tm.makeDataFrame() @@ -92,9 +91,7 @@ def test_api_default_format(tmp_path, setup_path): def test_put(setup_path): - with ensure_clean_store(setup_path) as store: - ts = tm.makeTimeSeries() df = tm.makeTimeDataFrame() store["a"] = ts @@ -125,9 +122,7 @@ def test_put(setup_path): def test_put_string_index(setup_path): - with ensure_clean_store(setup_path) as store: - index = Index([f"I am a very long string index: {i}" for i in range(20)]) s = Series(np.arange(20), index=index) df = DataFrame({"A": s, "B": s}) @@ -153,7 +148,6 @@ def test_put_string_index(setup_path): def test_put_compression(setup_path): - with ensure_clean_store(setup_path) as store: df = tm.makeTimeDataFrame() @@ -171,7 +165,6 @@ def test_put_compression_blosc(setup_path): df = tm.makeTimeDataFrame() with ensure_clean_store(setup_path) as store: - # can't compress if format='fixed' msg = "Compression not supported on Fixed format stores" with pytest.raises(ValueError, match=msg): @@ -229,7 +222,6 @@ def test_store_index_types(setup_path, format, index): # test storing various index types with ensure_clean_store(setup_path) as store: - df = DataFrame(np.random.randn(10, 2), columns=list("AB")) df.index = index(len(df)) @@ -249,7 +241,6 @@ def test_column_multiindex(setup_path): expected = df.set_axis(df.index.to_numpy()) with ensure_clean_store(setup_path) as store: - store.put("df", df) tm.assert_frame_equal( store["df"], expected, check_index_type=True, check_column_type=True @@ -279,7 +270,6 @@ def test_column_multiindex(setup_path): expected = df.set_axis(df.index.to_numpy()) with ensure_clean_store(setup_path) as store: - store.put("df1", df, format="table") tm.assert_frame_equal( store["df1"], expected, check_index_type=True, check_column_type=True @@ -287,7 +277,6 @@ def test_column_multiindex(setup_path): def test_store_multiindex(setup_path): - # validate multi-index names # GH 5527 with ensure_clean_store(setup_path) as store: diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index cb0c1ce35c7c7..2f2190a352045 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -49,7 +49,6 @@ def test_read_missing_key_opened_store(tmp_path, setup_path): df.to_hdf(path, "k1") with HDFStore(path, "r") as store: - with pytest.raises(KeyError, match="'No object named k2 in the file'"): read_hdf(store, "k2") @@ -59,7 +58,6 @@ def test_read_missing_key_opened_store(tmp_path, setup_path): def test_read_column(setup_path): - df = tm.makeTimeDataFrame() with ensure_clean_store(setup_path) as store: @@ -288,7 +286,6 @@ def test_read_nokey_empty(tmp_path, setup_path): def test_read_from_pathlib_path(tmp_path, setup_path): - # GH11773 expected = DataFrame( np.random.rand(4, 5), index=list("abcd"), columns=list("ABCDE") @@ -304,7 +301,6 @@ def test_read_from_pathlib_path(tmp_path, setup_path): @td.skip_if_no("py.path") def test_read_from_py_localpath(tmp_path, setup_path): - # GH11773 from py.path import local as LocalPath diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py index 3043cd3604e58..67e864591626c 100644 --- a/pandas/tests/io/pytables/test_retain_attributes.py +++ b/pandas/tests/io/pytables/test_retain_attributes.py @@ -20,7 +20,6 @@ def test_retain_index_attributes(setup_path): - # GH 3499, losing frequency info on index recreation df = DataFrame( {"A": Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))} @@ -77,7 +76,6 @@ def test_retain_index_attributes2(tmp_path, setup_path): path = tmp_path / setup_path with catch_warnings(record=True): - df = DataFrame( {"A": Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))} ) @@ -96,7 +94,6 @@ def test_retain_index_attributes2(tmp_path, setup_path): assert read_hdf(path, "data").index.name == "foo" with catch_warnings(record=True): - idx2 = date_range("2001-1-1", periods=3, freq="H") idx2.name = "bar" df2 = DataFrame({"A": Series(range(3), index=idx2)}) diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index 4bb00ad7f4c81..163951a6ebc45 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -56,7 +56,6 @@ def roundtrip(key, obj, **kwargs): def test_long_strings(setup_path): - # GH6166 df = DataFrame( {"a": tm.rands_array(100, size=10)}, index=tm.rands_array(100, size=10) @@ -70,7 +69,6 @@ def test_long_strings(setup_path): def test_api(tmp_path, setup_path): - # GH4584 # API issue when to_hdf doesn't accept append AND format args path = tmp_path / setup_path @@ -117,7 +115,6 @@ def test_api_2(tmp_path, setup_path): tm.assert_frame_equal(read_hdf(path, "df"), df) with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() _maybe_remove(store, "df") @@ -173,7 +170,6 @@ def test_api_invalid(tmp_path, setup_path): def test_get(setup_path): - with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() left = store.get("a") @@ -195,7 +191,6 @@ def test_put_integer(setup_path): def test_table_values_dtypes_roundtrip(setup_path): - with ensure_clean_store(setup_path) as store: df1 = DataFrame({"a": [1, 2, 3]}, dtype="f8") store.append("df_f8", df1) @@ -262,7 +257,6 @@ def test_table_values_dtypes_roundtrip(setup_path): @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") def test_series(setup_path): - s = tm.makeStringSeries() _check_roundtrip(s, tm.assert_series_equal, path=setup_path) @@ -279,7 +273,6 @@ def test_series(setup_path): def test_float_index(setup_path): - # GH #454 index = np.random.randn(10) s = Series(np.random.randn(10), index=index) @@ -287,7 +280,6 @@ def test_float_index(setup_path): def test_tuple_index(setup_path): - # GH #492 col = np.arange(10) idx = [(0.0, 1.0), (2.0, 3.0), (4.0, 5.0)] @@ -351,7 +343,6 @@ def test_index_types(setup_path): def test_timeseries_preepoch(setup_path, request): - dr = bdate_range("1/1/1940", "1/1/1960") ts = Series(np.random.randn(len(dr)), index=dr) try: @@ -368,7 +359,6 @@ def test_timeseries_preepoch(setup_path, request): "compression", [False, pytest.param(True, marks=td.skip_if_windows)] ) def test_frame(compression, setup_path): - df = tm.makeDataFrame() # put in some random NAs @@ -419,7 +409,6 @@ def test_empty_series(dtype, setup_path): def test_can_serialize_dates(setup_path): - rng = [x.date() for x in bdate_range("1/1/2000", "1/30/2000")] frame = DataFrame(np.random.randn(len(rng), 4), index=rng) @@ -488,7 +477,6 @@ def _make_one(): def _check_roundtrip(obj, comparator, path, compression=False, **kwargs): - options = {} if compression: options["complib"] = _default_compressor @@ -512,7 +500,6 @@ def _check_roundtrip_table(obj, comparator, path, compression=False): def test_unicode_index(setup_path): - unicode_values = ["\u03c3", "\u03c3\u03c3"] # PerformanceWarning @@ -539,7 +526,6 @@ def test_unicode_longer_encoded(setup_path): def test_store_datetime_mixed(setup_path): - df = DataFrame({"a": [1, 2, 3], "b": [1.0, 2.0, 3.0], "c": ["a", "b", "c"]}) ts = tm.makeTimeSeries() df["d"] = ts.index[:3] diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py index efaa907ec98b9..447d56ac91b24 100644 --- a/pandas/tests/io/pytables/test_select.py +++ b/pandas/tests/io/pytables/test_select.py @@ -30,7 +30,6 @@ def test_select_columns_in_where(setup_path): - # GH 6169 # recreate multi-indexes when columns is passed # in the `where` argument @@ -59,7 +58,6 @@ def test_select_columns_in_where(setup_path): def test_select_with_dups(setup_path): - # single dtypes df = DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]) df.index = date_range("20130101 9:30", periods=10, freq="T") @@ -122,11 +120,8 @@ def test_select_with_dups(setup_path): def test_select(setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): - # select with columns= df = tm.makeTimeDataFrame() _maybe_remove(store, "df") @@ -163,7 +158,6 @@ def test_select(setup_path): def test_select_dtypes(setup_path): - with ensure_clean_store(setup_path) as store: # with a Timestamp data column (GH #2637) df = DataFrame( @@ -220,7 +214,6 @@ def test_select_dtypes(setup_path): tm.assert_frame_equal(expected, result) with ensure_clean_store(setup_path) as store: - # floats w/o NaN df = DataFrame({"cols": range(11), "values": range(11)}, dtype="float64") df["cols"] = (df["cols"] + 10).apply(str) @@ -270,9 +263,7 @@ def test_select_dtypes(setup_path): def test_select_with_many_inputs(setup_path): - with ensure_clean_store(setup_path) as store: - df = DataFrame( { "ts": bdate_range("2012-01-01", periods=300), @@ -320,10 +311,8 @@ def test_select_with_many_inputs(setup_path): def test_select_iterator(tmp_path, setup_path): - # single table with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame(500) _maybe_remove(store, "df") store.append("df", df) @@ -370,7 +359,6 @@ def test_select_iterator(tmp_path, setup_path): # multiple with ensure_clean_store(setup_path) as store: - df1 = tm.makeTimeDataFrame(500) store.append("df1", df1, data_columns=True) df2 = tm.makeTimeDataFrame(500).rename(columns="{}_2".format) @@ -389,14 +377,12 @@ def test_select_iterator(tmp_path, setup_path): def test_select_iterator_complete_8014(setup_path): - # GH 8014 # using iterator and where clause chunksize = 1e4 # no iterator with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "S") _maybe_remove(store, "df") store.append("df", expected) @@ -428,7 +414,6 @@ def test_select_iterator_complete_8014(setup_path): # with iterator, full range with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "S") _maybe_remove(store, "df") store.append("df", expected) @@ -461,14 +446,12 @@ def test_select_iterator_complete_8014(setup_path): def test_select_iterator_non_complete_8014(setup_path): - # GH 8014 # using iterator and where clause chunksize = 1e4 # with iterator, non complete range with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "S") _maybe_remove(store, "df") store.append("df", expected) @@ -499,7 +482,6 @@ def test_select_iterator_non_complete_8014(setup_path): # with iterator, empty where with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "S") _maybe_remove(store, "df") store.append("df", expected) @@ -513,7 +495,6 @@ def test_select_iterator_non_complete_8014(setup_path): def test_select_iterator_many_empty_frames(setup_path): - # GH 8014 # using iterator and where clause can return many empty # frames. @@ -521,7 +502,6 @@ def test_select_iterator_many_empty_frames(setup_path): # with iterator, range limited to the first chunk with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100000, "S") _maybe_remove(store, "df") store.append("df", expected) @@ -570,7 +550,6 @@ def test_select_iterator_many_empty_frames(setup_path): def test_frame_select(setup_path): - df = tm.makeTimeDataFrame() with ensure_clean_store(setup_path) as store: @@ -659,7 +638,6 @@ def test_frame_select_complex(setup_path): def test_frame_select_complex2(tmp_path): - pp = tmp_path / "params.hdf" hh = tmp_path / "hist.hdf" @@ -719,7 +697,6 @@ def test_frame_select_complex2(tmp_path): def test_invalid_filtering(setup_path): - # can't use more than one filter (atm) df = tm.makeTimeDataFrame() @@ -740,7 +717,6 @@ def test_invalid_filtering(setup_path): def test_string_select(setup_path): # GH 2973 with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() # test string ==/!= @@ -781,13 +757,11 @@ def test_string_select(setup_path): def test_select_as_multiple(setup_path): - df1 = tm.makeTimeDataFrame() df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) df2["foo"] = "bar" with ensure_clean_store(setup_path) as store: - msg = "keys must be a list/tuple" # no tables stored with pytest.raises(TypeError, match=msg): @@ -853,9 +827,7 @@ def test_select_as_multiple(setup_path): def test_nan_selection_bug_4858(setup_path): - with ensure_clean_store(setup_path) as store: - df = DataFrame({"cols": range(6), "values": range(6)}, dtype="float64") df["cols"] = (df["cols"] + 10).apply(str) df.iloc[0] = np.nan diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 06684f076aefe..7a5b6ddd40334 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -55,7 +55,6 @@ def test_context(setup_path): def test_no_track_times(tmp_path, setup_path): - # GH 32682 # enables to set track_times (see `pytables` `create_table` documentation) @@ -99,14 +98,12 @@ def create_h5_and_return_checksum(tmp_path, track_times): def test_iter_empty(setup_path): - with ensure_clean_store(setup_path) as store: # GH 12221 assert list(store) == [] def test_repr(setup_path): - with ensure_clean_store(setup_path) as store: repr(store) store.info() @@ -142,7 +139,6 @@ def test_repr(setup_path): # storers with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() store.append("df", df) @@ -152,7 +148,6 @@ def test_repr(setup_path): def test_contains(setup_path): - with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() store["b"] = tm.makeDataFrame() @@ -172,7 +167,6 @@ def test_contains(setup_path): def test_versioning(setup_path): - with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() store["b"] = tm.makeDataFrame() @@ -260,9 +254,7 @@ def test_walk(where, expected): def test_getattr(setup_path): - with ensure_clean_store(setup_path) as store: - s = tm.makeTimeSeries() store["a"] = s @@ -316,7 +308,6 @@ def test_store_dropna(tmp_path, setup_path): def test_to_hdf_with_min_itemsize(tmp_path, setup_path): - path = tmp_path / setup_path # min_itemsize in index with to_hdf (GH 10381) @@ -335,7 +326,6 @@ def test_to_hdf_with_min_itemsize(tmp_path, setup_path): @pytest.mark.parametrize("format", ["fixed", "table"]) def test_to_hdf_errors(tmp_path, format, setup_path): - data = ["\ud800foo"] ser = Series(data, index=Index(data)) path = tmp_path / setup_path @@ -347,9 +337,7 @@ def test_to_hdf_errors(tmp_path, format, setup_path): def test_create_table_index(setup_path): - with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): def col(t, column): @@ -382,7 +370,6 @@ def test_create_table_index_data_columns_argument(setup_path): # GH 28156 with ensure_clean_store(setup_path) as store: - with catch_warnings(record=True): def col(t, column): @@ -426,7 +413,6 @@ def test_mi_data_columns(setup_path): def test_table_mixed_dtypes(setup_path): - # frame df = tm.makeDataFrame() df["obj1"] = "foo" @@ -449,7 +435,6 @@ def test_table_mixed_dtypes(setup_path): def test_calendar_roundtrip_issue(setup_path): - # 8591 # doc example from tseries holiday section weekmask_egypt = "Sun Mon Tue Wed Thu" @@ -467,7 +452,6 @@ def test_calendar_roundtrip_issue(setup_path): s = Series(dts.weekday, dts).map(Series("Mon Tue Wed Thu Fri Sat Sun".split())) with ensure_clean_store(setup_path) as store: - store.put("fixed", s) result = store.select("fixed") tm.assert_series_equal(result, s) @@ -478,9 +462,7 @@ def test_calendar_roundtrip_issue(setup_path): def test_remove(setup_path): - with ensure_clean_store(setup_path) as store: - ts = tm.makeTimeSeries() df = tm.makeDataFrame() store["a"] = ts @@ -519,9 +501,7 @@ def test_remove(setup_path): def test_same_name_scoping(setup_path): - with ensure_clean_store(setup_path) as store: - df = DataFrame(np.random.randn(20, 2), index=date_range("20130101", periods=20)) store.put("df", df, format="table") expected = df[df.index > Timestamp("20130105")] @@ -585,7 +565,6 @@ def test_store_series_name(setup_path): def test_overwrite_node(setup_path): - with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeDataFrame() ts = tm.makeTimeSeries() @@ -598,7 +577,6 @@ def test_coordinates(setup_path): df = tm.makeTimeDataFrame() with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df") store.append("df", df) @@ -645,7 +623,6 @@ def test_coordinates(setup_path): # pass array/mask as the coordinates with ensure_clean_store(setup_path) as store: - df = DataFrame( np.random.randn(1000, 2), index=date_range("20000101", periods=1000) ) @@ -706,9 +683,7 @@ def test_coordinates(setup_path): def test_start_stop_table(setup_path): - with ensure_clean_store(setup_path) as store: - # table df = DataFrame({"A": np.random.rand(20), "B": np.random.rand(20)}) store.append("df", df) @@ -725,10 +700,8 @@ def test_start_stop_table(setup_path): def test_start_stop_multiple(setup_path): - # GH 16209 with ensure_clean_store(setup_path) as store: - df = DataFrame({"foo": [1, 2], "bar": [1, 2]}) store.append_to_multiple( @@ -742,9 +715,7 @@ def test_start_stop_multiple(setup_path): def test_start_stop_fixed(setup_path): - with ensure_clean_store(setup_path) as store: - # fixed, GH 8287 df = DataFrame( {"A": np.random.rand(20), "B": np.random.rand(20)}, @@ -783,7 +754,6 @@ def test_start_stop_fixed(setup_path): def test_select_filter_corner(setup_path): - df = DataFrame(np.random.randn(50, 100)) df.index = [f"{c:3d}" for c in df.index] df.columns = [f"{c:3d}" for c in df.columns] @@ -865,7 +835,6 @@ def reader(path): def test_copy(): - with catch_warnings(record=True): def do_copy(f, new_f=None, keys=None, propindexes=True, **kwargs): @@ -936,7 +905,6 @@ def test_preserve_timedeltaindex_type(setup_path): df.index = timedelta_range(start="0s", periods=10, freq="1s", name="example") with ensure_clean_store(setup_path) as store: - store["df"] = df tm.assert_frame_equal(store["df"], df) diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py index 6625984961c11..262f25e77b69c 100644 --- a/pandas/tests/io/pytables/test_time_series.py +++ b/pandas/tests/io/pytables/test_time_series.py @@ -14,7 +14,6 @@ def test_store_datetime_fractional_secs(setup_path): - with ensure_clean_store(setup_path) as store: dt = datetime.datetime(2012, 1, 2, 3, 4, 5, 123456) series = Series([0], [dt]) @@ -23,7 +22,6 @@ def test_store_datetime_fractional_secs(setup_path): def test_tseries_indices_series(setup_path): - with ensure_clean_store(setup_path) as store: idx = tm.makeDateIndex(10) ser = Series(np.random.randn(len(idx)), idx) @@ -45,7 +43,6 @@ def test_tseries_indices_series(setup_path): def test_tseries_indices_frame(setup_path): - with ensure_clean_store(setup_path) as store: idx = tm.makeDateIndex(10) df = DataFrame(np.random.randn(len(idx), 3), index=idx) diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 058eaa9d0529d..7589eb8e96a10 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -84,7 +84,6 @@ def test_append_with_timezones(setup_path, gettz): ) with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df_tz") store.append("df_tz", df_est, data_columns=["A"]) result = store["df_tz"] @@ -138,7 +137,6 @@ def test_append_with_timezones_as_index(setup_path, gettz): df = DataFrame({"A": Series(range(3), index=dti)}) with ensure_clean_store(setup_path) as store: - _maybe_remove(store, "df") store.put("df", df) result = store.select("df") @@ -210,7 +208,6 @@ def test_tseries_select_index_column(setup_path): def test_timezones_fixed_format_frame_non_empty(setup_path): with ensure_clean_store(setup_path) as store: - # index rng = date_range("1/1/2000", "1/30/2000", tz="US/Eastern") rng = rng._with_freq(None) # freq doesn't round-trip @@ -282,7 +279,6 @@ def test_store_timezone(setup_path): # original method with ensure_clean_store(setup_path) as store: - today = date(2013, 9, 10) df = DataFrame([1, 2, 3], index=[today, today, today]) store["obj1"] = df @@ -291,7 +287,6 @@ def test_store_timezone(setup_path): # with tz setting with ensure_clean_store(setup_path) as store: - with tm.set_timezone("EST5EDT"): today = date(2013, 9, 10) df = DataFrame([1, 2, 3], index=[today, today, today]) diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index df934a9d2555f..35970da211c31 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -33,7 +33,6 @@ def check_external_error_on_write(self, df): to_feather(df, path) def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs): - if expected is None: expected = df @@ -44,7 +43,6 @@ def check_round_trip(self, df, expected=None, write_kwargs={}, **read_kwargs): tm.assert_frame_equal(result, expected) def test_error(self): - msg = "feather only support IO with DataFrames" for obj in [ pd.Series([1, 2, 3]), @@ -56,7 +54,6 @@ def test_error(self): self.check_error_on_write(obj, ValueError, msg) def test_basic(self): - df = pd.DataFrame( { "string": list("abc"), @@ -92,14 +89,12 @@ def test_basic(self): self.check_round_trip(df) def test_duplicate_columns(self): - # https://github.com/wesm/feather/issues/53 # not currently able to handle duplicate columns df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy() self.check_external_error_on_write(df) def test_stringify_columns(self): - df = pd.DataFrame(np.arange(12).reshape(4, 3)).copy() msg = "feather must have string column names" self.check_error_on_write(df, ValueError, msg) @@ -124,7 +119,6 @@ def test_read_columns_different_order(self): self.check_round_trip(df, expected, columns=["B", "A"]) def test_unsupported_other(self): - # mixed python objects df = pd.DataFrame({"a": ["a", 1, 2.0]}) self.check_external_error_on_write(df) @@ -135,7 +129,6 @@ def test_rw_use_threads(self): self.check_round_trip(df, use_threads=False) def test_write_with_index(self): - df = pd.DataFrame({"A": [1, 2, 3]}) self.check_round_trip(df) @@ -151,7 +144,6 @@ def test_write_with_index(self): [1, 3, 4], pd.MultiIndex.from_tuples([("a", 1), ("a", 2), ("b", 1)]), ]: - df.index = index self.check_error_on_write(df, ValueError, msg) @@ -248,7 +240,6 @@ def test_read_json_nullable(self, string_storage, dtype_backend, option): ) if dtype_backend == "pyarrow": - from pandas.arrays import ArrowExtensionArray expected = pd.DataFrame( diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index d27aeeb94199c..47cff87834956 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -344,7 +344,6 @@ def test_header_and_index_with_types(self, spam_data): assert_framelist_equal(df1, df2) def test_infer_types(self, spam_data): - # 10892 infer_types removed df1 = self.read_html(spam_data, match=".*Water.*", index_col=0) df2 = self.read_html(spam_data, match="Unit", index_col=0) diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 7aba335040098..353dc4f1cbd8a 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -46,6 +46,7 @@ # TODO(ArrayManager) fastparquet relies on BlockManager internals + # setup engines & skips @pytest.fixture( params=[ @@ -424,7 +425,6 @@ def test_columns_dtypes_invalid(self, engine): @pytest.mark.parametrize("compression", [None, "gzip", "snappy", "brotli"]) def test_compression(self, engine, compression): - if compression == "snappy": pytest.importorskip("snappy") @@ -700,7 +700,6 @@ def test_read_empty_array(self, pa, dtype): class TestParquetPyArrow(Base): def test_basic(self, pa, df_full): - df = df_full # additional supported types for pyarrow @@ -784,7 +783,6 @@ def test_unsupported_float16_cleanup(self, pa, path_type): assert not os.path.isfile(path) def test_categorical(self, pa): - # supported in >= 0.7.0 df = pd.DataFrame() df["a"] = pd.Categorical(list("abcdef")) @@ -1073,7 +1071,6 @@ def test_basic(self, fp, df_full): check_round_trip(df, fp) def test_duplicate_columns(self, fp): - # not currently able to handle duplicate columns df = pd.DataFrame(np.arange(12).reshape(4, 3), columns=list("aaa")).copy() msg = "Cannot create parquet dataset with duplicate column names" @@ -1087,7 +1084,6 @@ def test_bool_with_none(self, fp): check_round_trip(df, fp, expected=expected, check_dtype=False) def test_unsupported(self, fp): - # period df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)}) # error from fastparquet -> don't check exact error message diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 2c3617b7f3995..6fbac21dc0590 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -203,7 +203,6 @@ def test_round_trip_current(current_pickle_data, pickle_writer, writer): data = current_pickle_data for typ, dv in data.items(): for dt, expected in dv.items(): - with tm.ensure_clean() as path: # test writing with each pickler pickle_writer(expected, path) @@ -248,7 +247,6 @@ def get_random_path(): class TestCompression: - _extension_to_compression = icom.extension_to_compression def compress_file(self, src_path, dest_path, compression): @@ -544,7 +542,6 @@ def test_pickle_timeseries_periodindex(): "name", [777, 777.0, "name", datetime.datetime(2001, 11, 11), (1, 2)] ) def test_pickle_preserve_name(name): - unpickled = tm.round_trip_pickle(tm.makeTimeSeries(name=name)) assert unpickled.name == name diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 7207ff2356a03..d5c6eccad4783 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1223,7 +1223,6 @@ def test_date_and_index(self): assert issubclass(df.IntDateCol.dtype.type, np.datetime64) def test_timedelta(self): - # see #6921 df = to_timedelta(Series(["00:00:01", "00:00:03"], name="foo")).to_frame() with tm.assert_produces_warning(UserWarning): @@ -1680,7 +1679,6 @@ def test_sql_open_close(self, test_frame3): # between the writing and reading (as in many real situations). with tm.ensure_clean() as name: - with closing(self.connect(name)) as conn: assert ( sql.to_sql(test_frame3, "test_frame3_legacy", conn, index=False) @@ -1732,14 +1730,12 @@ def test_get_schema2(self, test_frame1): assert "CREATE" in create_sql def _get_sqlite_column_type(self, schema, column): - for col in schema.split("\n"): if col.split()[0].strip('"') == column: return col.split()[1] raise ValueError(f"Column {column} not found") def test_sqlite_type_mapping(self): - # Test Timestamp objects (no datetime64 because of timezone) (GH9085) df = DataFrame( {"time": to_datetime(["2014-12-12 01:54", "2014-12-11 02:54"], utc=True)} @@ -1888,7 +1884,6 @@ def check(col): # check that a column is either datetime64[ns] # or datetime64[ns, UTC] if is_datetime64_dtype(col.dtype): - # "2000-01-01 00:00:00-08:00" should convert to # "2000-01-01 08:00:00" assert col[0] == Timestamp("2000-01-01 08:00:00") @@ -2521,7 +2516,6 @@ def nullable_data(self) -> DataFrame: ) def nullable_expected(self, storage, dtype_backend) -> DataFrame: - string_array: StringArray | ArrowStringArray string_array_na: StringArray | ArrowStringArray if storage == "python": diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 69b9cbb7d6a26..5393a15cff19b 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -87,7 +87,6 @@ def test_read_index_col_none(self, version): @pytest.mark.parametrize("file", ["stata1_114", "stata1_117"]) def test_read_dta1(self, file, datapath): - file = datapath("io", "data", "stata", f"{file}.dta") parsed = self.read_dta(file) @@ -105,7 +104,6 @@ def test_read_dta1(self, file, datapath): tm.assert_frame_equal(parsed, expected) def test_read_dta2(self, datapath): - expected = DataFrame.from_records( [ ( @@ -176,7 +174,6 @@ def test_read_dta2(self, datapath): "file", ["stata3_113", "stata3_114", "stata3_115", "stata3_117"] ) def test_read_dta3(self, file, datapath): - file = datapath("io", "data", "stata", f"{file}.dta") parsed = self.read_dta(file) @@ -192,7 +189,6 @@ def test_read_dta3(self, file, datapath): "file", ["stata4_113", "stata4_114", "stata4_115", "stata4_117"] ) def test_read_dta4(self, file, datapath): - file = datapath("io", "data", "stata", f"{file}.dta") parsed = self.read_dta(file) @@ -358,7 +354,6 @@ def test_write_preserves_original(self): @pytest.mark.parametrize("version", [114, 117, 118, 119, None]) def test_encoding(self, version, datapath): - # GH 4626, proper encoding handling raw = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta")) encoded = read_stata(datapath("io", "data", "stata", "stata1_encoding.dta")) @@ -481,7 +476,6 @@ def test_read_write_reread_dta14(self, file, parsed_114, version, datapath): "file", ["stata6_113", "stata6_114", "stata6_115", "stata6_117"] ) def test_read_write_reread_dta15(self, file, datapath): - expected = self.read_csv(datapath("io", "data", "stata", "stata6.csv")) expected["byte_"] = expected["byte_"].astype(np.int8) expected["int_"] = expected["int_"].astype(np.int16) @@ -2057,7 +2051,6 @@ def test_compression_roundtrip(compression): df.index.name = "index" with tm.ensure_clean() as path: - df.to_stata(path, compression=compression) reread = read_stata(path, compression=compression, index_col="index") tm.assert_frame_equal(df, reread) diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py index 39f4c77cc3a50..5203506683be7 100644 --- a/pandas/tests/io/xml/test_to_xml.py +++ b/pandas/tests/io/xml/test_to_xml.py @@ -739,7 +739,6 @@ def test_namespace_prefix(parser): def test_missing_prefix_in_nmsp(parser): with pytest.raises(KeyError, match=("doc is not included in namespaces")): - geom_df.to_xml( namespaces={"": "http://example.com"}, prefix="doc", parser=parser ) diff --git a/pandas/tests/libs/test_hashtable.py b/pandas/tests/libs/test_hashtable.py index d9d281a0759da..4a5d5e0c85a09 100644 --- a/pandas/tests/libs/test_hashtable.py +++ b/pandas/tests/libs/test_hashtable.py @@ -660,7 +660,6 @@ def test_unique_label_indices_intp(writable): def test_unique_label_indices(): - a = np.random.randint(1, 1 << 10, 1 << 15).astype(np.intp) left = ht.unique_label_indices(a) diff --git a/pandas/tests/libs/test_lib.py b/pandas/tests/libs/test_lib.py index 302dc21ec997c..383e1b81e17a7 100644 --- a/pandas/tests/libs/test_lib.py +++ b/pandas/tests/libs/test_lib.py @@ -13,7 +13,6 @@ class TestMisc: def test_max_len_string_array(self): - arr = a = np.array(["foo", "b", np.nan], dtype="object") assert libwriters.max_len_string_array(arr) == 3 diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index f1e40691059e2..921f2b3ef3368 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -186,7 +186,6 @@ def _check_colors( conv = self.colorconverter if linecolors is not None: - if mapping is not None: linecolors = self._get_colors_mapped(mapping, linecolors) linecolors = linecolors[: len(collections)] @@ -206,7 +205,6 @@ def _check_colors( assert result == expected if facecolors is not None: - if mapping is not None: facecolors = self._get_colors_mapped(mapping, facecolors) facecolors = facecolors[: len(collections)] @@ -472,7 +470,6 @@ def is_grid_on(): spndx = 1 for kind in kinds: - self.plt.subplot(1, 4 * len(kinds), spndx) spndx += 1 mpl.rc("axes", grid=False) diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index cc45b7eda7e27..16be54124bda3 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -252,7 +252,6 @@ def test_invalid_logscale(self, input_param): df.plot(**{input_param: "sm"}) def test_xcompat(self): - df = tm.makeTimeDataFrame() ax = df.plot(x_compat=True) lines = ax.get_lines() @@ -728,7 +727,6 @@ def test_plot_scatter_with_categorical_data(self, x, y): _check_plot_works(df.plot.scatter, x=x, y=y) def test_plot_scatter_with_c(self): - df = DataFrame( np.random.randint(low=0, high=100, size=(6, 4)), index=list(string.ascii_letters[:6]), @@ -1221,7 +1219,6 @@ def test_unordered_ts(self): def test_kind_both_ways(self): df = DataFrame({"x": [1, 2, 3]}) for kind in plotting.PlotAccessor._common_kinds: - df.plot(kind=kind) getattr(df.plot, kind)() for kind in ["scatter", "hexbin"]: @@ -1231,7 +1228,6 @@ def test_kind_both_ways(self): def test_all_invalid_plot_data(self): df = DataFrame(list("abcd")) for kind in plotting.PlotAccessor._common_kinds: - msg = "no numeric data to plot" with pytest.raises(TypeError, match=msg): df.plot(kind=kind) @@ -1784,7 +1780,6 @@ def test_memory_leak(self): """Check that every plot type gets properly collected.""" results = {} for kind in plotting.PlotAccessor._all_kinds: - args = {} if kind in ["hexbin", "scatter", "pie"]: df = DataFrame( @@ -1939,7 +1934,6 @@ def test_df_grid_settings(self): ) def test_plain_axes(self): - # supplied ax itself is a SubplotAxes, but figure contains also # a plain Axes object (GH11556) fig, ax = self.plt.subplots() diff --git a/pandas/tests/plotting/frame/test_frame_legend.py b/pandas/tests/plotting/frame/test_frame_legend.py index e11aeeccfd5fb..d759d753d4320 100644 --- a/pandas/tests/plotting/frame/test_frame_legend.py +++ b/pandas/tests/plotting/frame/test_frame_legend.py @@ -54,7 +54,6 @@ def test_df_legend_labels(self): df4 = DataFrame(np.random.rand(3, 3), columns=["j", "k", "l"]) for kind in kinds: - ax = df.plot(kind=kind, legend=True) self._check_legend_labels(ax, labels=df.columns) diff --git a/pandas/tests/plotting/frame/test_frame_subplots.py b/pandas/tests/plotting/frame/test_frame_subplots.py index 0f57ade453564..4f55f9504f0db 100644 --- a/pandas/tests/plotting/frame/test_frame_subplots.py +++ b/pandas/tests/plotting/frame/test_frame_subplots.py @@ -227,7 +227,6 @@ def test_subplots_layout_multi_column(self): def test_subplots_layout_single_column( self, kwargs, expected_axes_num, expected_layout, expected_shape ): - # GH 6667 df = DataFrame(np.random.rand(10, 1), index=list(string.ascii_letters[:10])) axes = df.plot(subplots=True, **kwargs) @@ -623,7 +622,6 @@ def _check_bar_alignment( width=0.5, position=0.5, ): - axes = df.plot( kind=kind, stacked=stacked, diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index f145c8d750e12..8fc4170a8562c 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -128,7 +128,6 @@ def test_tsplot(self): assert color == ax.get_lines()[0].get_color() def test_both_style_and_color(self): - ts = tm.makeTimeSeries() msg = ( "Cannot pass 'style' string with a color symbol and 'color' " @@ -648,7 +647,6 @@ def test_secondary_y_ts(self): @td.skip_if_no_scipy def test_secondary_kde(self): - ser = Series(np.random.randn(10)) fig, ax = self.plt.subplots() ax = ser.plot(secondary_y=True, kind="density", ax=ax) @@ -769,7 +767,6 @@ def test_mixed_freq_alignment(self): assert ax.lines[0].get_xdata()[0] == ax.lines[1].get_xdata()[0] def test_mixed_freq_lf_first(self): - idxh = date_range("1/1/1999", periods=365, freq="D") idxl = date_range("1/1/1999", periods=12, freq="M") high = Series(np.random.randn(len(idxh)), idxh) @@ -803,7 +800,6 @@ def test_mixed_freq_irreg_period(self): ps.plot(ax=ax) def test_mixed_freq_shared_ax(self): - # GH13341, using sharex=True idx1 = date_range("2015-01-01", periods=3, freq="M") idx2 = idx1[:1].union(idx1[2:]) @@ -836,7 +832,6 @@ def test_mixed_freq_shared_ax(self): # ax2.lines[0].get_xydata()[0, 0]) def test_nat_handling(self): - _, ax = self.plt.subplots() dti = DatetimeIndex(["2015-01-01", NaT, "2015-01-03"]) @@ -1338,7 +1333,6 @@ def test_plot_outofbounds_datetime(self): ax.plot(values) def test_format_timedelta_ticks_narrow(self): - expected_labels = [f"00:00:00.0000000{i:0>2d}" for i in np.arange(10)] rng = timedelta_range("0", periods=10, freq="ns") diff --git a/pandas/tests/plotting/test_groupby.py b/pandas/tests/plotting/test_groupby.py index d097e69c1415d..8cde3062d09f9 100644 --- a/pandas/tests/plotting/test_groupby.py +++ b/pandas/tests/plotting/test_groupby.py @@ -59,7 +59,6 @@ def test_plot_submethod_works(self): tm.close() def test_plot_kwargs(self): - df = DataFrame({"x": [1, 2, 3, 4, 5], "y": [1, 2, 3, 2, 1], "z": list("ababa")}) res = df.groupby("z").plot(kind="scatter", x="x", y="y") diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index 76211df501891..04228bde1c6b9 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -194,7 +194,6 @@ def test_hist_kwargs(self, ts): @pytest.mark.xfail(reason="Api changed in 3.6.0") @td.skip_if_no_scipy def test_hist_kde(self, ts): - _, ax = self.plt.subplots() ax = ts.plot.hist(logy=True, ax=ax) self._check_ax_scales(ax, yaxis="log") diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 3bb411afbaa3a..d21c42e3eeaf9 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -580,7 +580,6 @@ def test_errorbar_asymmetrical(self): @pytest.mark.slow def test_errorbar_plot(self): - s = Series(np.arange(10), name="x") s_err = np.abs(np.random.randn(10)) d_err = DataFrame( diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 88e62ea0bc79a..5fa341c9eb74a 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -251,7 +251,6 @@ def test_max_min_range(self, start, stop, step): assert isna(idx.min()) def test_minmax_timedelta64(self): - # monotonic idx1 = TimedeltaIndex(["1 days", "2 days", "3 days"]) assert idx1.is_monotonic_increasing @@ -478,7 +477,6 @@ def test_numpy_minmax_datetime64(self): np.argmax(dr, out=0) def test_minmax_period(self): - # monotonic idx1 = PeriodIndex([NaT, "2011-01-01", "2011-01-02", "2011-01-03"], freq="D") assert not idx1.is_monotonic_increasing @@ -528,7 +526,6 @@ def test_numpy_minmax_period(self): np.argmax(pr, out=0) def test_min_max_categorical(self): - ci = pd.CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) msg = ( r"Categorical is not ordered for operation min\n" @@ -675,7 +672,6 @@ def test_empty(self, method, unit, use_bottleneck, dtype): @pytest.mark.parametrize("method", ["mean", "var"]) @pytest.mark.parametrize("dtype", ["Float64", "Int64", "boolean"]) def test_ops_consistency_on_empty_nullable(self, method, dtype): - # GH#34814 # consistency for nullable dtypes on empty or ALL-NA mean @@ -691,7 +687,6 @@ def test_ops_consistency_on_empty_nullable(self, method, dtype): @pytest.mark.parametrize("method", ["mean", "median", "std", "var"]) def test_ops_consistency_on_empty(self, method): - # GH#7869 # consistency on empty @@ -723,7 +718,6 @@ def test_nansum_buglet(self): @pytest.mark.parametrize("use_bottleneck", [True, False]) @pytest.mark.parametrize("dtype", ["int32", "int64"]) def test_sum_overflow_int(self, use_bottleneck, dtype): - with pd.option_context("use_bottleneck", use_bottleneck): # GH#6915 # overflowing on the smaller int dtypes @@ -1026,7 +1020,6 @@ def test_any_all_datetimelike(self): assert not df.all().any() def test_timedelta64_analytics(self): - # index min/max dti = date_range("2012-1-1", periods=3, freq="D") td = Series(dti) - Timestamp("20120101") diff --git a/pandas/tests/reductions/test_stat_reductions.py b/pandas/tests/reductions/test_stat_reductions.py index 0dc68d78eebc9..dd6aef04a2e6a 100644 --- a/pandas/tests/reductions/test_stat_reductions.py +++ b/pandas/tests/reductions/test_stat_reductions.py @@ -94,7 +94,6 @@ class TestSeriesStatReductions: def _check_stat_op( self, name, alternate, string_series_, check_objects=False, check_allna=False ): - with pd.option_context("use_bottleneck", False): f = getattr(Series, name) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 13041a81dadcf..d7ee7744ebcd4 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -56,7 +56,6 @@ def unit(request): def test_custom_grouper(index, unit): - dti = index.as_unit(unit) s = Series(np.array([1] * len(dti)), index=dti, dtype="int64") @@ -394,7 +393,6 @@ def test_resample_basic_from_daily(unit): def test_resample_upsampling_picked_but_not_correct(unit): - # Test for issue #3020 dates = date_range("01-Jan-2014", "05-Jan-2014", freq="D").as_unit(unit) series = Series(1, index=dates) @@ -556,7 +554,6 @@ def test_resample_ohlc(series, unit): def test_resample_ohlc_result(unit): - # GH 12332 index = date_range("1-1-2000", "2-15-2000", freq="h").as_unit(unit) index = index.union(date_range("4-15-2000", "5-15-2000", freq="h").as_unit(unit)) @@ -636,7 +633,6 @@ def test_resample_ohlc_dataframe(unit): def test_resample_dup_index(): - # GH 4812 # dup columns with resample raising df = DataFrame( @@ -1010,7 +1006,6 @@ def test_resample_to_period_monthly_buglet(unit): def test_period_with_agg(): - # aggregate a period resampler with a lambda s2 = Series( np.random.randint(0, 5, 50), @@ -1043,7 +1038,6 @@ def test_resample_segfault(unit): def test_resample_dtype_preservation(unit): - # GH 12202 # validation tests for dtype preservation @@ -1063,7 +1057,6 @@ def test_resample_dtype_preservation(unit): def test_resample_dtype_coercion(unit): - pytest.importorskip("scipy.interpolate") # GH 16361 @@ -1274,7 +1267,6 @@ def test_resample_median_bug_1688(dtype): def test_how_lambda_functions(simple_date_range_series, unit): - ts = simple_date_range_series("1/1/2000", "4/1/2000") ts.index = ts.index.as_unit(unit) @@ -1314,7 +1306,6 @@ def test_resample_unequal_times(unit): def test_resample_consistency(unit): - # GH 6418 # resample with bfill / limit / reindex consistency @@ -1386,7 +1377,6 @@ def test_resample_timegrouper(dates): def test_resample_nunique(unit): - # GH 12352 df = DataFrame( { diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index e32708c4402e4..6d0a56a947065 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -233,7 +233,6 @@ def test_resample_count(self, freq, expected_vals): tm.assert_series_equal(result, expected) def test_resample_same_freq(self, resample_method): - # GH12770 series = Series(range(3), index=period_range(start="2000", periods=3, freq="M")) expected = series diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 1e54a4c03f4fc..7ce4f482b6414 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -27,7 +27,6 @@ def test_frame(): def test_str(): - r = test_series.resample("H") assert ( "DatetimeIndexResampler [freq=<Hour>, axis=0, closed=left, " @@ -42,7 +41,6 @@ def test_str(): def test_api(): - r = test_series.resample("H") result = r.mean() assert isinstance(result, Series) @@ -55,7 +53,6 @@ def test_api(): def test_groupby_resample_api(): - # GH 12448 # .groupby(...).resample(...) hitting warnings # when appropriate @@ -79,7 +76,6 @@ def test_groupby_resample_api(): def test_groupby_resample_on_api(): - # GH 15021 # .groupby(...).resample(on=...) results in an unexpected # keyword warning. @@ -138,7 +134,6 @@ def test_pipe(test_frame): def test_getitem(test_frame): - r = test_frame.resample("H") tm.assert_index_equal(r._selected_obj.columns, test_frame.columns) @@ -164,14 +159,12 @@ def test_select_bad_cols(key, test_frame): def test_attribute_access(test_frame): - r = test_frame.resample("H") tm.assert_series_equal(r.A.sum(), r["A"].sum()) @pytest.mark.parametrize("attr", ["groups", "ngroups", "indices"]) def test_api_compat_before_use(attr): - # make sure that we are setting the binner # on these attributes rng = date_range("1/1/2012", periods=100, freq="S") @@ -187,7 +180,6 @@ def test_api_compat_before_use(attr): def tests_raises_on_nuisance(test_frame): - df = test_frame df["D"] = "foo" r = df.resample("H") @@ -203,7 +195,6 @@ def tests_raises_on_nuisance(test_frame): def test_downsample_but_actually_upsampling(): - # this is reindex / asfreq rng = date_range("1/1/2012", periods=100, freq="S") ts = Series(np.arange(len(rng), dtype="int64"), index=rng) @@ -216,7 +207,6 @@ def test_downsample_but_actually_upsampling(): def test_combined_up_downsampling_of_irregular(): - # since we are really doing an operation like this # ts2.resample('2s').mean().ffill() # preserve these semantics @@ -296,7 +286,6 @@ def test_transform_frame(on): def test_fillna(): - # need to upsample here rng = date_range("1/1/2012", periods=10, freq="2S") ts = Series(np.arange(len(rng), dtype="int64"), index=rng) @@ -340,7 +329,6 @@ def test_apply_without_aggregation2(): def test_agg_consistency(): - # make sure that we are consistent across # similar aggregations with and w/o selection list df = DataFrame( @@ -588,7 +576,6 @@ def test_multi_agg_axis_1_raises(func): def test_agg_nested_dicts(): - np.random.seed(1234) index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") index.name = "date" @@ -612,7 +599,6 @@ def test_agg_nested_dicts(): t.aggregate({"r1": {"A": ["mean", "sum"]}, "r2": {"B": ["mean", "sum"]}}) for t in cases: - with pytest.raises(pd.errors.SpecificationError, match=msg): t[["A", "B"]].agg( {"A": {"ra": ["mean", "std"]}, "B": {"rb": ["mean", "std"]}} diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index c3717cee05f2b..2aa2b272547bc 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -45,7 +45,6 @@ async def test_tab_complete_ipython6_warning(ip): def test_deferred_with_groupby(): - # GH 12486 # support deferred resample ops with groupby data = [ @@ -103,7 +102,6 @@ def test_getitem(): def test_getitem_multiple(): - # GH 13174 # multiple calls after selection causing an issue with aliasing data = [{"id": 1, "buyer": "A"}, {"id": 2, "buyer": "B"}] @@ -176,7 +174,6 @@ def test_groupby_with_origin(): def test_nearest(): - # GH 17496 # Resample nearest index = date_range("1/1/2000", periods=3, freq="T") @@ -249,7 +246,6 @@ def test_methods_std_var(f): def test_apply(): - g = test_frame.groupby("A") r = g.resample("2s") @@ -329,7 +325,6 @@ def test_resample_groupby_with_label(): def test_consistency_with_window(): - # consistent return values with window df = test_frame expected = Index([1, 2, 3], name="A") diff --git a/pandas/tests/resample/test_timedelta.py b/pandas/tests/resample/test_timedelta.py index 5c9f61a4adc28..8b6e757c0a46a 100644 --- a/pandas/tests/resample/test_timedelta.py +++ b/pandas/tests/resample/test_timedelta.py @@ -46,7 +46,6 @@ def test_resample_as_freq_with_subperiod(): def test_resample_with_timedeltas(): - expected = DataFrame({"A": np.arange(1480)}) expected = expected.groupby(expected.index // 30).sum() expected.index = timedelta_range("0 days", freq="30T", periods=50) @@ -64,7 +63,6 @@ def test_resample_with_timedeltas(): def test_resample_single_period_timedelta(): - s = Series(list(range(5)), index=timedelta_range("1 day", freq="s", periods=5)) result = s.resample("2s").sum() expected = Series([1, 5, 4], index=timedelta_range("1 day", freq="2s", periods=3)) @@ -72,7 +70,6 @@ def test_resample_single_period_timedelta(): def test_resample_timedelta_idempotency(): - # GH 12072 index = timedelta_range("0", periods=9, freq="10L") series = Series(range(9), index=index) diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py index 0b1d1c4a3d346..b540cd514c0b5 100644 --- a/pandas/tests/reshape/concat/test_append.py +++ b/pandas/tests/reshape/concat/test_append.py @@ -244,7 +244,6 @@ def test_append_different_columns_types(self, df_columns, series_index): tm.assert_frame_equal(result, expected) def test_append_dtype_coerce(self, sort): - # GH 4993 # appending with datetime will incorrectly convert datetime64 diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py index f00d3b369a94d..14c559db4b0b5 100644 --- a/pandas/tests/reshape/concat/test_categorical.py +++ b/pandas/tests/reshape/concat/test_categorical.py @@ -50,7 +50,6 @@ def test_categorical_concat(self, sort): tm.assert_frame_equal(res, exp) def test_categorical_concat_dtypes(self): - # GH8143 index = ["cat", "obj", "num"] cat = Categorical(["a", "b", "c"]) @@ -93,7 +92,6 @@ def test_concat_categoricalindex(self): tm.assert_frame_equal(result, exp) def test_categorical_concat_preserve(self): - # GH 8641 series concat not preserving category dtype # GH 13524 can concat different categories s = Series(list("abc"), dtype="category") @@ -125,7 +123,6 @@ def test_categorical_concat_preserve(self): tm.assert_frame_equal(res, exp) def test_categorical_index_preserver(self): - a = Series(np.arange(6, dtype="int64")) b = Series(list("aabbca")) diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 73be92d1a5dcf..b08d0a33d08c6 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -267,7 +267,6 @@ def test_with_mixed_tuples(self, sort): concat([df1, df2], sort=sort) def test_concat_mixed_objs(self): - # concat mixed series/frames # G2385 @@ -336,7 +335,6 @@ def test_concat_mixed_objs(self): tm.assert_frame_equal(result, expected) def test_dtype_coerceion(self): - # 12411 df = DataFrame({"date": [pd.Timestamp("20130101").tz_localize("UTC"), pd.NaT]}) @@ -409,7 +407,6 @@ def test_concat_bug_2972(self): tm.assert_frame_equal(result, expected) def test_concat_bug_3602(self): - # GH 3602, duplicate columns df1 = DataFrame( { diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py index 1018fc2806fee..23a49c33099cb 100644 --- a/pandas/tests/reshape/concat/test_dataframe.py +++ b/pandas/tests/reshape/concat/test_dataframe.py @@ -13,7 +13,6 @@ class TestDataFrameConcat: def test_concat_multiple_frames_dtypes(self): - # GH#2759 df1 = DataFrame(data=np.ones((10, 2)), columns=["foo", "bar"], dtype=np.float64) df2 = DataFrame(data=np.ones((10, 2)), dtype=np.float32) diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py index 0d95d94782ecf..919bcb8b2e577 100644 --- a/pandas/tests/reshape/concat/test_empty.py +++ b/pandas/tests/reshape/concat/test_empty.py @@ -131,7 +131,6 @@ def test_concat_empty_series_dtypes_match_roundtrips(self, dtype): ["float64", "int8", "uint8", "m8[ns]", "M8[ns]"], ) def test_concat_empty_series_dtypes_roundtrips(self, dtype, dtype2): - # round-tripping with self & like self if dtype == dtype2: return @@ -172,7 +171,6 @@ def get_result_type(dtype, dtype2): assert result.kind == expected def test_concat_empty_series_dtypes_triple(self): - assert ( concat( [Series(dtype="M8[ns]"), Series(dtype=np.bool_), Series(dtype=np.int64)] @@ -245,7 +243,6 @@ def test_concat_inner_join_empty(self): tm.assert_frame_equal(result, expected) def test_empty_dtype_coerce(self): - # xref to #12411 # xref to #12045 # xref to #11594 diff --git a/pandas/tests/reshape/concat/test_invalid.py b/pandas/tests/reshape/concat/test_invalid.py index 920d31d1bc43a..a8c6ef97d1ccc 100644 --- a/pandas/tests/reshape/concat/test_invalid.py +++ b/pandas/tests/reshape/concat/test_invalid.py @@ -13,11 +13,9 @@ class TestInvalidConcat: def test_concat_invalid(self): - # trying to concat a ndframe with a non-ndframe df1 = tm.makeCustomDataframe(10, 2) for obj in [1, {}, [1, 2], (1, 2)]: - msg = ( f"cannot concatenate object of type '{type(obj)}'; " "only Series and DataFrame objs are valid" diff --git a/pandas/tests/reshape/concat/test_series.py b/pandas/tests/reshape/concat/test_series.py index 886ada409a91a..c5d3a8a7c74d1 100644 --- a/pandas/tests/reshape/concat/test_series.py +++ b/pandas/tests/reshape/concat/test_series.py @@ -15,7 +15,6 @@ class TestSeriesConcat: def test_concat_series(self): - ts = tm.makeTimeSeries() ts.name = "foo" diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 7008e1594712f..93bca0739298f 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -434,7 +434,6 @@ def test_join_hierarchical_mixed_raises(self): merge(new_df, other_df, left_index=True, right_index=True) def test_join_float64_float32(self): - a = DataFrame(np.random.randn(10, 2), columns=["a", "b"], dtype=np.float64) b = DataFrame(np.random.randn(10, 1), columns=["c"], dtype=np.float32) joined = a.join(b) @@ -616,7 +615,6 @@ def test_join_many_mixed(self): tm.assert_frame_equal(result, df) def test_join_dups(self): - # joining dups df = concat( [ @@ -746,7 +744,6 @@ def test_join_with_categorical_index(self): def _check_join(left, right, result, join_col, how="left", lsuffix="_x", rsuffix="_y"): - # some smoke tests for c in join_col: assert result[c].notna().all() @@ -933,7 +930,6 @@ def test_join_multiindex_not_alphabetical_categorical(categories, values): ], ) def test_join_empty(left_empty, how, exp): - left = DataFrame({"A": [2, 1], "B": [3, 4]}, dtype="int64").set_index("A") right = DataFrame({"A": [1], "C": [5]}, dtype="int64").set_index("A") diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index e52687e3cfbc2..ad90d5ae147c8 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -401,7 +401,6 @@ def test_no_overlap_more_informative_error(self): merge(df1, df2) def test_merge_non_unique_indexes(self): - dt = datetime(2012, 5, 1) dt2 = datetime(2012, 5, 2) dt3 = datetime(2012, 5, 3) @@ -793,7 +792,6 @@ def test_overlapping_columns_error_message(self): merge(df, df2) def test_merge_on_datetime64tz(self): - # GH11405 left = DataFrame( { @@ -1447,7 +1445,6 @@ class TestMergeDtypes: "right_vals", [["foo", "bar"], Series(["foo", "bar"]).astype("category")] ) def test_different(self, right_vals): - left = DataFrame( { "A": ["foo", "bar"], @@ -1469,7 +1466,6 @@ def test_different(self, right_vals): @pytest.mark.parametrize("d1", [np.int64, np.int32, np.int16, np.int8, np.uint8]) @pytest.mark.parametrize("d2", [np.int64, np.float64, np.float32, np.float16]) def test_join_multi_dtypes(self, d1, d2): - dtype1 = np.dtype(d1) dtype2 = np.dtype(d2) @@ -1758,7 +1754,6 @@ def test_merge_ea_with_string(self, join_type, string_dtype): ], ) def test_merge_empty(self, left_empty, how, exp): - left = DataFrame({"A": [2, 1], "B": [3, 4]}) right = DataFrame({"A": [1], "C": [5]}, dtype="int64") diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index 3b522eaa075f0..0aa9026cc0808 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -189,14 +189,12 @@ def test_examples4(self): tm.assert_frame_equal(result, expected) def test_basic(self, trades, asof, quotes): - expected = asof result = merge_asof(trades, quotes, on="time", by="ticker") tm.assert_frame_equal(result, expected) def test_basic_categorical(self, trades, asof, quotes): - expected = asof trades.ticker = trades.ticker.astype("category") quotes.ticker = quotes.ticker.astype("category") @@ -206,7 +204,6 @@ def test_basic_categorical(self, trades, asof, quotes): tm.assert_frame_equal(result, expected) def test_basic_left_index(self, trades, asof, quotes): - # GH14253 expected = asof trades = trades.set_index("time") @@ -221,7 +218,6 @@ def test_basic_left_index(self, trades, asof, quotes): tm.assert_frame_equal(result, expected) def test_basic_right_index(self, trades, asof, quotes): - expected = asof quotes = quotes.set_index("time") @@ -231,7 +227,6 @@ def test_basic_right_index(self, trades, asof, quotes): tm.assert_frame_equal(result, expected) def test_basic_left_index_right_index(self, trades, asof, quotes): - expected = asof.set_index("time") trades = trades.set_index("time") quotes = quotes.set_index("time") @@ -242,7 +237,6 @@ def test_basic_left_index_right_index(self, trades, asof, quotes): tm.assert_frame_equal(result, expected) def test_multi_index_left(self, trades, quotes): - # MultiIndex is prohibited trades = trades.set_index(["time", "price"]) quotes = quotes.set_index("time") @@ -250,7 +244,6 @@ def test_multi_index_left(self, trades, quotes): merge_asof(trades, quotes, left_index=True, right_index=True) def test_multi_index_right(self, trades, quotes): - # MultiIndex is prohibited trades = trades.set_index("time") quotes = quotes.set_index(["time", "bid"]) @@ -258,7 +251,6 @@ def test_multi_index_right(self, trades, quotes): merge_asof(trades, quotes, left_index=True, right_index=True) def test_on_and_index_left_on(self, trades, quotes): - # "on" parameter and index together is prohibited trades = trades.set_index("time") quotes = quotes.set_index("time") @@ -278,7 +270,6 @@ def test_on_and_index_right_on(self, trades, quotes): ) def test_basic_left_by_right_by(self, trades, asof, quotes): - # GH14253 expected = asof @@ -288,7 +279,6 @@ def test_basic_left_by_right_by(self, trades, asof, quotes): tm.assert_frame_equal(result, expected) def test_missing_right_by(self, trades, asof, quotes): - expected = asof q = quotes[quotes.ticker != "MSFT"] @@ -477,7 +467,6 @@ def test_multiby_indexed(self): ) def test_basic2(self, datapath): - expected = self.read_data(datapath, "asof2.csv") trades = self.read_data(datapath, "trades2.csv") quotes = self.read_data(datapath, "quotes2.csv", dedupe=True) @@ -501,7 +490,6 @@ def test_basic_no_by(self, trades, asof, quotes): tm.assert_frame_equal(result, expected) def test_valid_join_keys(self, trades, quotes): - msg = r"incompatible merge keys \[1\] .* must be the same type" with pytest.raises(MergeError, match=msg): @@ -514,7 +502,6 @@ def test_valid_join_keys(self, trades, quotes): merge_asof(trades, quotes, by="ticker") def test_with_duplicates(self, datapath, trades, quotes): - q = ( pd.concat([quotes, quotes]) .sort_values(["time", "ticker"]) @@ -525,7 +512,6 @@ def test_with_duplicates(self, datapath, trades, quotes): tm.assert_frame_equal(result, expected) def test_with_duplicates_no_on(self): - df1 = pd.DataFrame({"key": [1, 1, 3], "left_val": [1, 2, 3]}) df2 = pd.DataFrame({"key": [1, 2, 2], "right_val": [1, 2, 3]}) result = merge_asof(df1, df2, on="key") @@ -535,7 +521,6 @@ def test_with_duplicates_no_on(self): tm.assert_frame_equal(result, expected) def test_valid_allow_exact_matches(self, trades, quotes): - msg = "allow_exact_matches must be boolean, passed foo" with pytest.raises(MergeError, match=msg): @@ -544,7 +529,6 @@ def test_valid_allow_exact_matches(self, trades, quotes): ) def test_valid_tolerance(self, trades, quotes): - # dti merge_asof(trades, quotes, on="time", by="ticker", tolerance=Timedelta("1s")) @@ -591,7 +575,6 @@ def test_valid_tolerance(self, trades, quotes): ) def test_non_sorted(self, trades, quotes): - trades = trades.sort_values("time", ascending=False) quotes = quotes.sort_values("time", ascending=False) @@ -730,7 +713,6 @@ def test_index_tolerance(self, trades, quotes, tolerance): tm.assert_frame_equal(result, expected) def test_allow_exact_matches(self, trades, quotes, allow_exact_matches): - result = merge_asof( trades, quotes, on="time", by="ticker", allow_exact_matches=False ) @@ -770,7 +752,6 @@ def test_allow_exact_matches_nearest(self): def test_allow_exact_matches_and_tolerance( self, trades, quotes, allow_exact_matches_and_tolerance ): - result = merge_asof( trades, quotes, diff --git a/pandas/tests/reshape/merge/test_merge_index_as_string.py b/pandas/tests/reshape/merge/test_merge_index_as_string.py index c3e0a92850c07..b4271d4face4f 100644 --- a/pandas/tests/reshape/merge/test_merge_index_as_string.py +++ b/pandas/tests/reshape/merge/test_merge_index_as_string.py @@ -131,7 +131,6 @@ def compute_expected(df_left, df_right, on=None, left_on=None, right_on=None, ho ], ) def test_merge_indexes_and_columns_on(left_df, right_df, on, how): - # Construct expected result expected = compute_expected(left_df, right_df, on=on, how=how) @@ -152,7 +151,6 @@ def test_merge_indexes_and_columns_on(left_df, right_df, on, how): def test_merge_indexes_and_columns_lefton_righton( left_df, right_df, left_on, right_on, how ): - # Construct expected result expected = compute_expected( left_df, right_df, left_on=left_on, right_on=right_on, how=how @@ -165,7 +163,6 @@ def test_merge_indexes_and_columns_lefton_righton( @pytest.mark.parametrize("left_index", ["inner", ["inner", "outer"]]) def test_join_indexes_and_columns_on(df1, df2, left_index, join_type): - # Construct left_df left_df = df1.set_index(left_index) diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index 53932b044dc31..37ed45f0094ec 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -186,7 +186,6 @@ def test_merge_multiple_cols_with_mixed_cols_index(self): tm.assert_frame_equal(result, expected) def test_compress_group_combinations(self): - # ~ 40000000 possible unique groups key1 = tm.rands_array(10, 10000) key1 = np.tile(key1, 2) @@ -202,7 +201,6 @@ def test_compress_group_combinations(self): merge(df, df2, how="outer") def test_left_join_index_preserve_order(self): - on_cols = ["k1", "k2"] left = DataFrame( { @@ -644,7 +642,6 @@ def test_join_multi_levels_invalid(self, portfolio, household): portfolio2.join(portfolio, how="inner") def test_join_multi_levels2(self): - # some more advanced merges # GH6360 household = DataFrame( @@ -823,7 +820,6 @@ def test_join_multi_multi( def test_join_multi_empty_frames( self, left_multi, right_multi, join_type, on_cols_multi, idx_cols_multi ): - left_multi = left_multi.drop(columns=left_multi.columns) right_multi = right_multi.drop(columns=right_multi.columns) diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 55f1696ac776c..573f5d49afb89 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -264,7 +264,6 @@ def test_margin_dropna(self): tm.assert_frame_equal(actual, expected) def test_margin_dropna2(self): - df = DataFrame( {"a": [1, np.nan, np.nan, np.nan, 2, np.nan], "b": [3, np.nan, 4, 4, 4, 4]} ) @@ -275,7 +274,6 @@ def test_margin_dropna2(self): tm.assert_frame_equal(actual, expected) def test_margin_dropna3(self): - df = DataFrame( {"a": [1, np.nan, np.nan, np.nan, np.nan, 2], "b": [3, 3, 4, 4, 4, 4]} ) diff --git a/pandas/tests/reshape/test_from_dummies.py b/pandas/tests/reshape/test_from_dummies.py index ab80473725288..0c4c61e932033 100644 --- a/pandas/tests/reshape/test_from_dummies.py +++ b/pandas/tests/reshape/test_from_dummies.py @@ -117,7 +117,6 @@ def test_error_with_prefix_multiple_seperators(): def test_error_with_prefix_sep_wrong_type(dummies_basic): - with pytest.raises( TypeError, match=( diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index 792707dc080f8..ea9da4e87240b 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -228,7 +228,6 @@ def test_custom_value_name(self, df, value_name): tm.assert_frame_equal(result14, expected14) def test_custom_var_and_value_name(self, df, value_name, var_name): - result15 = df.melt(var_name=var_name, value_name=value_name) assert result15.columns.tolist() == ["var", "val"] diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 15c278bdc3859..93217fc4ce3b0 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -193,7 +193,6 @@ def test_pivot_table_dropna(self): tm.assert_index_equal(pv_ind.index, m) def test_pivot_table_categorical(self): - cat1 = Categorical( ["a", "a", "b", "b"], categories=["a", "b", "z"], ordered=True ) @@ -342,7 +341,6 @@ def test_pivot_table_multiple(self, data): tm.assert_frame_equal(table, expected) def test_pivot_dtypes(self): - # can convert dtypes f = DataFrame( { @@ -1106,7 +1104,6 @@ def test_pivot_no_level_overlap(self): tm.assert_frame_equal(table, expected) def test_pivot_columns_lexsorted(self): - n = 10000 dtype = np.dtype( diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 88b1bda6b645c..b8a0a8068ba31 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -131,7 +131,6 @@ def test_construction_from_timestamp_nanos(self): assert rt2.asm8 == dt64 def test_construction_bday(self): - # Biz day construction, roll forward if non-weekday i1 = Period("3/10/12", freq="B") i2 = Period("3/10/12", freq="D") @@ -149,7 +148,6 @@ def test_construction_bday(self): assert i1 == i2 def test_construction_quarter(self): - i1 = Period(year=2005, quarter=1, freq="Q") i2 = Period("1/1/2005", freq="Q") assert i1 == i2 @@ -185,7 +183,6 @@ def test_construction_quarter(self): assert i1 == lower def test_construction_month(self): - expected = Period("2007-01", freq="M") i1 = Period("200701", freq="M") assert i1 == expected @@ -1096,7 +1093,6 @@ def test_comparison_invalid_type(self): int_or_per = "'(Period|int)'" msg = f"not supported between instances of {int_or_per} and {int_or_per}" for left, right in [(jan, 1), (1, jan)]: - with pytest.raises(TypeError, match=msg): left > right with pytest.raises(TypeError, match=msg): @@ -1321,7 +1317,6 @@ def test_add_offset(self): np.timedelta64(365, "D"), timedelta(365), ]: - with pytest.raises(IncompatibleFrequency, match=msg): p + o with pytest.raises(IncompatibleFrequency, match=msg): diff --git a/pandas/tests/scalar/test_na_scalar.py b/pandas/tests/scalar/test_na_scalar.py index bdeb11dbb8f19..213fa1791838d 100644 --- a/pandas/tests/scalar/test_na_scalar.py +++ b/pandas/tests/scalar/test_na_scalar.py @@ -161,7 +161,6 @@ def test_unary_ops(): def test_logical_and(): - assert NA & True is NA assert True & NA is NA assert NA & False is False @@ -174,7 +173,6 @@ def test_logical_and(): def test_logical_or(): - assert NA | True is True assert True | NA is True assert NA | False is NA @@ -187,7 +185,6 @@ def test_logical_or(): def test_logical_xor(): - assert NA ^ True is NA assert True ^ NA is NA assert NA ^ False is NA diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 562f57c898582..d37a0c7976541 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -43,7 +43,6 @@ ], ) def test_nat_fields(nat, idx): - for field in idx._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime @@ -57,7 +56,6 @@ def test_nat_fields(nat, idx): assert np.isnan(result) for field in idx._bool_ops: - result = getattr(NaT, field) assert result is False diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index 01ec11c306dcd..d67d451e4fc6d 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -459,7 +459,6 @@ def test_td_div_timedeltalike_scalar(self): assert np.isnan(td / NaT) def test_td_div_td64_non_nano(self): - # truediv td = Timedelta("1 days 2 hours 3 ns") result = td / np.timedelta64(1, "D") @@ -1100,7 +1099,6 @@ def test_ops_error_str(): td = Timedelta("1 day") for left, right in [(td, "a"), ("a", td)]: - msg = "|".join( [ "unsupported operand type", diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index dc4399a4a38de..47ee81c506a87 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -167,7 +167,6 @@ def test_to_pytimedelta(self, td): def test_to_timedelta64(self, td, unit): for res in [td.to_timedelta64(), td.to_numpy(), td.asm8]: - assert isinstance(res, np.timedelta64) assert res.view("i8") == td._value if unit == NpyDatetimeUnit.NPY_FR_s.value: @@ -376,7 +375,6 @@ def test_total_seconds_scalar(self): assert np.isnan(rng.total_seconds()) def test_conversion(self): - for td in [Timedelta(10, unit="d"), Timedelta("1 days, 10:11:12.012345")]: pydt = td.to_pytimedelta() assert td == Timedelta(pydt) @@ -670,7 +668,6 @@ def test_to_numpy_alias(self): ], ) def test_round(self, freq, s1, s2): - t1 = Timedelta("1 days 02:34:56.789123456") t2 = Timedelta("-1 days 02:34:56.789123456") @@ -769,7 +766,6 @@ def test_round_non_nano(self, unit): assert res._creso == td._creso def test_identity(self): - td = Timedelta(10, unit="d") assert isinstance(td, Timedelta) assert isinstance(td, timedelta) @@ -855,7 +851,6 @@ def conv(v): Timedelta("- 1days, 00") def test_pickle(self): - v = Timedelta("1 days 10:11:12.0123456") v_p = tm.round_trip_pickle(v) assert v == v_p diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index c3e0f6df9c7d5..e7e5541cf499f 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -57,7 +57,6 @@ def test_comparison_dt64_ndarray(self): @pytest.mark.parametrize("reverse", [True, False]) def test_comparison_dt64_ndarray_tzaware(self, reverse, comparison_op): - ts = Timestamp("2021-01-01 00:00:00.00000", tz="UTC") arr = np.array([ts.asm8, ts.asm8], dtype="M8[ns]") diff --git a/pandas/tests/scalar/timestamp/test_rendering.py b/pandas/tests/scalar/timestamp/test_rendering.py index c2886f8f285f3..216a055120a46 100644 --- a/pandas/tests/scalar/timestamp/test_rendering.py +++ b/pandas/tests/scalar/timestamp/test_rendering.py @@ -7,7 +7,6 @@ class TestTimestampRendering: - timezones = ["UTC", "Asia/Tokyo", "US/Eastern", "dateutil/US/Pacific"] @pytest.mark.parametrize("tz", timezones) diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 1150e5985c181..855b8d52aa84d 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -381,7 +381,6 @@ def check(value, unit=None, h=1, s=1, us=0, ns=0): check(value, **check_kwargs) def test_roundtrip(self): - # test value to string and back conversions # further test accessors base = Timestamp("20140101 00:00:00").as_unit("ns") @@ -827,7 +826,6 @@ def test_to_period(self, dt64, ts): "td", [timedelta(days=4), Timedelta(days=4), np.timedelta64(4, "D")] ) def test_addsub_timedeltalike_non_nano(self, dt64, ts, td): - exp_reso = max(ts._creso, Timedelta(td)._creso) result = ts - td diff --git a/pandas/tests/scalar/timestamp/test_unary_ops.py b/pandas/tests/scalar/timestamp/test_unary_ops.py index be24fd7da8591..d37fb927bdd96 100644 --- a/pandas/tests/scalar/timestamp/test_unary_ops.py +++ b/pandas/tests/scalar/timestamp/test_unary_ops.py @@ -28,7 +28,6 @@ class TestTimestampUnaryOps: - # -------------------------------------------------------------- def test_round_divison_by_zero_raises(self): ts = Timestamp("2016-01-01") diff --git a/pandas/tests/series/accessors/test_cat_accessor.py b/pandas/tests/series/accessors/test_cat_accessor.py index c999a3efee31f..a2ed590640465 100644 --- a/pandas/tests/series/accessors/test_cat_accessor.py +++ b/pandas/tests/series/accessors/test_cat_accessor.py @@ -72,7 +72,6 @@ def test_cat_accessor_no_new_attributes(self): cat.cat.xlabel = "a" def test_categorical_delegations(self): - # invalid accessor msg = r"Can only use \.cat accessor with a 'category' dtype" with pytest.raises(AttributeError, match=msg): diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index a7e3cd43d1a6e..fa8e184285616 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -145,7 +145,6 @@ def test_dt_namespace_accessor_datetime64tz(self): dti = date_range("20130101", periods=5, tz="US/Eastern") ser = Series(dti, name="xxx") for prop in ok_for_dt: - # we test freq below if prop != "freq": self._compare(ser, prop) @@ -225,7 +224,6 @@ def test_dt_namespace_accessor_period(self): assert freq_result == PeriodIndex(ser.values).freq def test_dt_namespace_accessor_index_and_values(self): - # both index = date_range("20130101", periods=3, freq="D") dti = date_range("20140204", periods=3, freq="s") diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index 48cef368b387d..64da669343147 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -207,7 +207,6 @@ def test_getitem_setitem_datetimeindex(): def test_getitem_setitem_periodindex(): - N = 50 rng = period_range("1/1/1990", periods=N, freq="H") ts = Series(np.random.randn(N), index=rng) @@ -252,7 +251,6 @@ def test_getitem_setitem_periodindex(): def test_datetime_indexing(): - index = date_range("1/1/2000", "1/7/2000") index = index.repeat(3) @@ -369,7 +367,6 @@ def test_indexing_unordered(): ts2 = pd.concat([ts[0:4], ts[-4:], ts[4:-4]]) for t in ts.index: - expected = ts[t] result = ts2[t] assert expected == result @@ -400,7 +397,6 @@ def compare(slobj): def test_indexing_unordered2(): - # diff freq rng = date_range(datetime(2005, 1, 1), periods=20, freq="M") ts = Series(np.arange(len(rng)), index=rng) diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index a8290f472cd7c..f12d752a1a764 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -78,7 +78,6 @@ def test_basic_getitem_with_labels(datetime_series): def test_basic_getitem_dt64tz_values(): - # GH12089 # with tz for values ser = Series( diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py index 6ae978b22e24d..9d8a8320eb978 100644 --- a/pandas/tests/series/methods/test_asof.py +++ b/pandas/tests/series/methods/test_asof.py @@ -34,7 +34,6 @@ def test_asof_nanosecond_index_access(self): assert first_value == ser[Timestamp(expected_ts)] def test_basic(self): - # array or list or dates N = 50 rng = date_range("1/1/1990", periods=N, freq="53s") @@ -60,7 +59,6 @@ def test_basic(self): assert ts[ub] == val def test_scalar(self): - N = 30 rng = date_range("1/1/1990", periods=N, freq="53s") # Explicit cast to float avoid implicit cast when setting nan @@ -169,7 +167,6 @@ def test_periodindex(self): ts.asof(rng.asfreq("D")) def test_errors(self): - s = Series( [1, 2, 3], index=[Timestamp("20130101"), Timestamp("20130103"), Timestamp("20130102")], diff --git a/pandas/tests/series/methods/test_clip.py b/pandas/tests/series/methods/test_clip.py index b123e8a12a852..c88a42697dbdf 100644 --- a/pandas/tests/series/methods/test_clip.py +++ b/pandas/tests/series/methods/test_clip.py @@ -26,7 +26,6 @@ def test_clip(self, datetime_series): assert isinstance(expected, Series) def test_clip_types_and_nulls(self): - sers = [ Series([np.nan, 1.0, 2.0, 3.0]), Series([None, "a", "b", "c"]), diff --git a/pandas/tests/series/methods/test_combine_first.py b/pandas/tests/series/methods/test_combine_first.py index bd8f9df026e19..aac3d4986e8ee 100644 --- a/pandas/tests/series/methods/test_combine_first.py +++ b/pandas/tests/series/methods/test_combine_first.py @@ -68,7 +68,6 @@ def test_combine_first(self): tm.assert_series_equal(ser, result) def test_combine_first_dt64(self): - s0 = to_datetime(Series(["2010", np.NaN])) s1 = to_datetime(Series([np.NaN, "2011"])) rs = s0.combine_first(s1) diff --git a/pandas/tests/series/methods/test_copy.py b/pandas/tests/series/methods/test_copy.py index d681c0d02e0a2..5ebf45090d7b8 100644 --- a/pandas/tests/series/methods/test_copy.py +++ b/pandas/tests/series/methods/test_copy.py @@ -11,7 +11,6 @@ class TestCopy: @pytest.mark.parametrize("deep", ["default", None, False, True]) def test_copy(self, deep, using_copy_on_write): - ser = Series(np.arange(10), dtype="float64") # default deep is True diff --git a/pandas/tests/series/methods/test_count.py b/pandas/tests/series/methods/test_count.py index dfc531f63614f..16a8b06e1a170 100644 --- a/pandas/tests/series/methods/test_count.py +++ b/pandas/tests/series/methods/test_count.py @@ -20,7 +20,6 @@ def test_count(self, datetime_series): assert Series([pd.Timestamp("1990/1/1")]).count() == 1 def test_count_categorical(self): - ser = Series( Categorical( [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True diff --git a/pandas/tests/series/methods/test_describe.py b/pandas/tests/series/methods/test_describe.py index 21c0977e0f70d..ab4b8881d677d 100644 --- a/pandas/tests/series/methods/test_describe.py +++ b/pandas/tests/series/methods/test_describe.py @@ -38,7 +38,6 @@ def test_describe_bools(self): tm.assert_series_equal(result, expected) def test_describe_strs(self): - ser = Series(["a", "a", "b", "c", "d"], name="str_data") result = ser.describe() expected = Series( diff --git a/pandas/tests/series/methods/test_drop.py b/pandas/tests/series/methods/test_drop.py index 83d257605c487..5d9a469915cfb 100644 --- a/pandas/tests/series/methods/test_drop.py +++ b/pandas/tests/series/methods/test_drop.py @@ -24,7 +24,6 @@ def test_drop_unique_and_non_unique_index( data, index, axis, drop_labels, expected_data, expected_index ): - ser = Series(data=data, index=index) result = ser.drop(drop_labels, axis=axis) expected = Series(data=expected_data, index=expected_index) diff --git a/pandas/tests/series/methods/test_dropna.py b/pandas/tests/series/methods/test_dropna.py index ba2dd8f830bb1..1a7c27929d405 100644 --- a/pandas/tests/series/methods/test_dropna.py +++ b/pandas/tests/series/methods/test_dropna.py @@ -41,7 +41,6 @@ def test_dropna_no_nan(self): Series([1, 2, 3], name="x"), Series([False, True, False], name="x"), ]: - result = ser.dropna() tm.assert_series_equal(result, ser) assert result is not ser diff --git a/pandas/tests/series/methods/test_dtypes.py b/pandas/tests/series/methods/test_dtypes.py index abc0e5d13aaf7..82260bc2a65b9 100644 --- a/pandas/tests/series/methods/test_dtypes.py +++ b/pandas/tests/series/methods/test_dtypes.py @@ -3,6 +3,5 @@ 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_explode.py b/pandas/tests/series/methods/test_explode.py index 0dc3ef25a39a4..886152326cf3e 100644 --- a/pandas/tests/series/methods/test_explode.py +++ b/pandas/tests/series/methods/test_explode.py @@ -82,7 +82,6 @@ def test_non_object_dtype(s): def test_typical_usecase(): - df = pd.DataFrame( [{"var1": "a,b,c", "var2": 1}, {"var1": "d,e,f", "var2": 2}], columns=["var1", "var2"], diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 8897a0936b2c7..36967c5cad925 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -320,7 +320,6 @@ def test_timedelta_fillna(self, frame_or_series): tm.assert_equal(result, expected) def test_datetime64_fillna(self): - ser = Series( [ Timestamp("20130101"), @@ -794,7 +793,6 @@ def test_fillna_listlike_invalid(self): ser.fillna((1, 2)) def test_fillna_method_and_limit_invalid(self): - # related GH#9217, make sure limit is an int and greater than 0 ser = Series([1, 2, 3, None]) msg = "|".join( diff --git a/pandas/tests/series/methods/test_get_numeric_data.py b/pandas/tests/series/methods/test_get_numeric_data.py index 60dd64d7e1948..11dc6d5c57162 100644 --- a/pandas/tests/series/methods/test_get_numeric_data.py +++ b/pandas/tests/series/methods/test_get_numeric_data.py @@ -8,7 +8,6 @@ class TestGetNumericData: def test_get_numeric_data_preserve_dtype(self, using_copy_on_write): - # get the numeric data obj = Series([1, 2, 3]) result = obj._get_numeric_data() diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index 0f19bfc48e05b..6f4c4ba4dd69d 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -119,7 +119,6 @@ def test_interpolate_time_raises_for_non_timeseries(self): @td.skip_if_no_scipy def test_interpolate_cubicspline(self): - ser = Series([10, 11, 12, 13]) expected = Series( @@ -135,7 +134,6 @@ def test_interpolate_cubicspline(self): @td.skip_if_no_scipy def test_interpolate_pchip(self): - ser = Series(np.sort(np.random.uniform(size=100))) # interpolate at new_index @@ -148,7 +146,6 @@ def test_interpolate_pchip(self): @td.skip_if_no_scipy def test_interpolate_akima(self): - ser = Series([10, 11, 12, 13]) # interpolate at new_index where `der` is zero diff --git a/pandas/tests/series/methods/test_is_monotonic.py b/pandas/tests/series/methods/test_is_monotonic.py index 8d7769539ad82..b60c3cc8fcb5a 100644 --- a/pandas/tests/series/methods/test_is_monotonic.py +++ b/pandas/tests/series/methods/test_is_monotonic.py @@ -8,7 +8,6 @@ class TestIsMonotonic: def test_is_monotonic_numeric(self): - ser = Series(np.random.randint(0, 10, size=1000)) assert not ser.is_monotonic_increasing ser = Series(np.arange(1000)) @@ -18,7 +17,6 @@ def test_is_monotonic_numeric(self): assert ser.is_monotonic_decreasing is True def test_is_monotonic_dt64(self): - ser = Series(date_range("20130101", periods=10)) assert ser.is_monotonic_increasing is True assert ser.is_monotonic_increasing is True diff --git a/pandas/tests/series/methods/test_nlargest.py b/pandas/tests/series/methods/test_nlargest.py index 4f07257038bc9..146ba2c42e0be 100644 --- a/pandas/tests/series/methods/test_nlargest.py +++ b/pandas/tests/series/methods/test_nlargest.py @@ -125,7 +125,6 @@ def test_nsmallest_nlargest(self, s_main_dtypes_split): tm.assert_series_equal(ser.nlargest(len(ser) + 1), ser.iloc[[4, 0, 1, 3, 2]]) def test_nlargest_misc(self): - ser = Series([3.0, np.nan, 1, 2, 5]) result = ser.nlargest() expected = ser.iloc[[4, 0, 3, 2, 1]] @@ -159,7 +158,6 @@ def test_nlargest_misc(self): @pytest.mark.parametrize("n", range(1, 5)) def test_nlargest_n(self, n): - # GH 13412 ser = Series([1, 4, 3, 2], index=[0, 0, 1, 1]) result = ser.nlargest(n) diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py index 0ef1e63f742db..190cdf5f57ea3 100644 --- a/pandas/tests/series/methods/test_quantile.py +++ b/pandas/tests/series/methods/test_quantile.py @@ -14,7 +14,6 @@ class TestSeriesQuantile: def test_quantile(self, datetime_series): - q = datetime_series.quantile(0.1) assert q == np.percentile(datetime_series.dropna(), 10) @@ -45,7 +44,6 @@ def test_quantile(self, datetime_series): datetime_series.quantile(invalid) def test_quantile_multi(self, datetime_series): - qs = [0.1, 0.9] result = datetime_series.quantile(qs) expected = Series( @@ -99,7 +97,6 @@ def test_quantile_interpolation_dtype(self): assert is_integer(q) def test_quantile_nan(self): - # GH 13098 s = Series([1, 2, 3, 4, np.nan]) result = s.quantile(0.5) @@ -187,7 +184,6 @@ def test_quantile_sparse(self, values, dtype): tm.assert_series_equal(result, expected) def test_quantile_empty(self): - # floats s = Series([], dtype="float64") diff --git a/pandas/tests/series/methods/test_sort_index.py b/pandas/tests/series/methods/test_sort_index.py index 4df6f52e0fff4..e0dde50bfdc7f 100644 --- a/pandas/tests/series/methods/test_sort_index.py +++ b/pandas/tests/series/methods/test_sort_index.py @@ -100,7 +100,6 @@ def test_sort_index_level(self): @pytest.mark.parametrize("level", ["A", 0]) # GH#21052 def test_sort_index_multiindex(self, level): - mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list("ABC")) s = Series([1, 2], mi) backwards = s.iloc[[1, 0]] diff --git a/pandas/tests/series/methods/test_sort_values.py b/pandas/tests/series/methods/test_sort_values.py index 6ca08c32dcfe7..c1579dbbbc21a 100644 --- a/pandas/tests/series/methods/test_sort_values.py +++ b/pandas/tests/series/methods/test_sort_values.py @@ -11,7 +11,6 @@ class TestSeriesSortValues: def test_sort_values(self, datetime_series, using_copy_on_write): - # check indexes are reordered corresponding with the values ser = Series([3, 2, 4, 1], ["A", "B", "C", "D"]) expected = Series([1, 2, 3, 4], ["D", "B", "A", "C"]) @@ -93,7 +92,6 @@ def test_sort_values(self, datetime_series, using_copy_on_write): s.sort_values(inplace=True) def test_sort_values_categorical(self): - c = Categorical(["a", "b", "b", "a"], ordered=False) cat = Series(c.copy()) diff --git a/pandas/tests/series/methods/test_to_csv.py b/pandas/tests/series/methods/test_to_csv.py index 7827483644634..990c3698a5036 100644 --- a/pandas/tests/series/methods/test_to_csv.py +++ b/pandas/tests/series/methods/test_to_csv.py @@ -66,7 +66,6 @@ def test_from_csv(self, datetime_series, string_series): tm.assert_series_equal(check_series, series) def test_to_csv(self, datetime_series): - with tm.ensure_clean() as path: datetime_series.to_csv(path, header=False) @@ -89,7 +88,6 @@ def test_to_csv_unicode_index(self): tm.assert_series_equal(s, s2) def test_to_csv_float_format(self): - with tm.ensure_clean() as filename: ser = Series([0.123456, 0.234567, 0.567567]) ser.to_csv(filename, float_format="%.2f", header=False) @@ -128,9 +126,7 @@ def test_to_csv_path_is_none(self): ], ) def test_to_csv_compression(self, s, encoding, compression): - with tm.ensure_clean() as filename: - s.to_csv(filename, compression=compression, encoding=encoding, header=True) # test the round trip - to_csv -> read_csv result = pd.read_csv( diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index 6b096a7fcf3eb..c2b1569d3f391 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -79,7 +79,6 @@ def test_tz_localize_nonexistent(self, warsaw, method, exp): df = ser.to_frame() if method == "raise": - with tm.external_error_raised(pytz.NonExistentTimeError): dti.tz_localize(tz, nonexistent=method) with tm.external_error_raised(pytz.NonExistentTimeError): diff --git a/pandas/tests/series/methods/test_unstack.py b/pandas/tests/series/methods/test_unstack.py index 980fcbc141822..6e1c76bd170c6 100644 --- a/pandas/tests/series/methods/test_unstack.py +++ b/pandas/tests/series/methods/test_unstack.py @@ -133,7 +133,6 @@ def test_unstack_mixed_type_name_in_multiindex( def test_unstack_multi_index_categorical_values(): - mi = tm.makeTimeDataFrame().stack().index.rename(["major", "minor"]) ser = Series(["foo"] * len(mi), index=mi, name="category", dtype="category") diff --git a/pandas/tests/series/methods/test_update.py b/pandas/tests/series/methods/test_update.py index 3e347604f7351..afcf07489c002 100644 --- a/pandas/tests/series/methods/test_update.py +++ b/pandas/tests/series/methods/test_update.py @@ -62,7 +62,6 @@ def test_update(self, using_copy_on_write): ], ) def test_update_dtypes(self, other, dtype, expected): - ser = Series([10, 11, 12], dtype=dtype) other = Series(other, index=[1, 3]) ser.update(other) diff --git a/pandas/tests/series/methods/test_view.py b/pandas/tests/series/methods/test_view.py index 22902c8648fc5..a9b29c9329193 100644 --- a/pandas/tests/series/methods/test_view.py +++ b/pandas/tests/series/methods/test_view.py @@ -45,7 +45,6 @@ def test_view_tz(self): ) @pytest.mark.parametrize("box", [Series, Index, array]) def test_view_between_datetimelike(self, first, second, box): - dti = date_range("2016-01-01", periods=3) orig = box(dti) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 5c3dfd246e9aa..dcb28001777d2 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -118,7 +118,6 @@ def test_class_axis(self): assert pydoc.getdoc(Series.index) def test_ndarray_compat(self): - # test numpy compat with Series as sub-class of NDFrame tsdf = DataFrame( np.random.randn(1000, 3), diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 08fdad5ff1edd..e4044feab1cbd 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -302,7 +302,6 @@ def test_alignment_categorical(self): tm.assert_series_equal(result, expected) def test_arithmetic_with_duplicate_index(self): - # GH#8363 # integer ops with a non-unique index index = [2, 2, 3, 3, 4] diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 951c9df0f6e99..bb1926ca9bfb7 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -140,7 +140,6 @@ def test_invalid_compound_dtype(self): Series(cdt_arr, index=["A", "B"]) def test_scalar_conversion(self): - # Pass in scalar is disabled scalar = Series(0.5) assert not isinstance(scalar, float) @@ -310,7 +309,6 @@ def test_constructor_single_str(self): tm.assert_series_equal(result, expected) def test_constructor_list_like(self): - # make sure that we are coercing different # list-likes to standard dtypes and not # platform specific @@ -897,7 +895,6 @@ def test_constructor_dtype_no_cast(self, using_copy_on_write): assert s[1] == 5 def test_constructor_datelike_coercion(self): - # GH 9477 # incorrectly inferring on dateimelike looking when object dtype is # specified @@ -938,7 +935,6 @@ def test_constructor_datetimes_with_nulls(self): assert result.dtype == "M8[ns]" def test_constructor_dtype_datetime64(self): - s = Series(iNaT, dtype="M8[ns]", index=range(5)) assert isna(s).all() @@ -1098,7 +1094,6 @@ def test_constructor_dtype_datetime64_2(self): assert "NaN" in str(s) def test_constructor_with_datetime_tz(self): - # 8260 # support datetime64 with tz @@ -1259,7 +1254,6 @@ def test_constructor_interval_mixed_closed(self, data_constructor): assert result.tolist() == data def test_construction_consistency(self): - # make sure that we are not re-localizing upon construction # GH 14928 ser = Series(date_range("20130101", periods=3, tz="US/Eastern")) @@ -1461,7 +1455,6 @@ def test_fromDict(self): assert series.dtype == np.float64 def test_fromValue(self, datetime_series): - nans = Series(np.NaN, index=datetime_series.index, dtype=np.float64) assert nans.dtype == np.float_ assert len(nans) == len(datetime_series) @@ -1484,7 +1477,6 @@ def test_fromValue(self, datetime_series): tm.assert_series_equal(categorical, expected) def test_constructor_dtype_timedelta64(self): - # basic td = Series([timedelta(days=i) for i in range(3)]) assert td.dtype == "timedelta64[ns]" @@ -1642,7 +1634,6 @@ def test_convert_non_ns(self): ids=lambda x: type(x).__name__, ) def test_constructor_cant_cast_datetimelike(self, index): - # floats are not ok # strip Index to convert PeriodIndex -> Period # We don't care whether the error message says diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 81e1e4c205cf7..017721b8a4ee0 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -18,7 +18,6 @@ class TestSeriesMissingData: def test_categorical_nan_handling(self): - # NaNs are represented as -1 in labels s = Series(Categorical(["a", "b", np.nan, "a"])) tm.assert_index_equal(s.cat.categories, Index(["a", "b"])) @@ -37,7 +36,6 @@ def test_isna_for_inf(self): tm.assert_series_equal(dr, de) def test_timedelta64_nan(self): - td = Series([timedelta(days=i) for i in range(10)]) # nan ops on timedeltas diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index b3f1a1be903e5..f143155bc07da 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -290,7 +290,6 @@ def test_multiply(self, values_for_np_reduce, box_with_array, request): expected = obj._values.prod() assert result == expected else: - expected = obj.prod() assert result == expected else: diff --git a/pandas/tests/strings/test_api.py b/pandas/tests/strings/test_api.py index 7a6c7e69047bc..088affcb0506f 100644 --- a/pandas/tests/strings/test_api.py +++ b/pandas/tests/strings/test_api.py @@ -12,7 +12,6 @@ def test_api(any_string_dtype): - # GH 6106, GH 9322 assert Series.str is strings.StringMethods assert isinstance(Series([""], dtype=any_string_dtype).str, strings.StringMethods) diff --git a/pandas/tests/strings/test_extract.py b/pandas/tests/strings/test_extract.py index 04c355c6c78c5..e9193113d0220 100644 --- a/pandas/tests/strings/test_extract.py +++ b/pandas/tests/strings/test_extract.py @@ -320,7 +320,6 @@ def test_extract_series(name, any_string_dtype): def test_extract_optional_groups(any_string_dtype): - # two normal groups, one non-capturing group s = Series(["A11", "B22", "C33"], dtype=any_string_dtype) result = s.str.extract("([AB])([123])(?:[123])", expand=True) @@ -603,7 +602,6 @@ def test_extractall_stringindex(any_string_dtype): Index(["a1a2", "b1", "c1"]), Index(["a1a2", "b1", "c1"], name="xxx"), ]: - result = idx.str.extractall(r"[ab](?P<digit>\d)") tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index a9335e156d9db..9340fea14f801 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -296,7 +296,6 @@ def test_len_mixed(): ], ) def test_index(method, sub, start, end, index_or_series, any_string_dtype, expected): - obj = index_or_series( ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype ) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index d96109ecd960c..b00b28f1e6033 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -106,7 +106,6 @@ def test_series_factorize_use_na_sentinel_false(self): tm.assert_index_equal(uniques, expected_uniques) def test_basic(self): - codes, uniques = algos.factorize(["a", "b", "b", "a", "a", "c", "c", "c"]) tm.assert_numpy_array_equal(uniques, np.array(["a", "b", "c"], dtype=object)) @@ -147,7 +146,6 @@ def test_basic(self): tm.assert_numpy_array_equal(uniques, exp) def test_mixed(self): - # doc example reshaping.rst x = Series(["A", "A", np.nan, "B", 3.14, np.inf]) codes, uniques = algos.factorize(x) @@ -164,7 +162,6 @@ def test_mixed(self): tm.assert_index_equal(uniques, exp) def test_datelike(self): - # M8 v1 = Timestamp("20130101 09:00:00.00004") v2 = Timestamp("20130101") @@ -551,7 +548,6 @@ def test_object_refcount_bug(self): len(algos.unique(lst)) def test_on_index_object(self): - mindex = MultiIndex.from_arrays( [np.arange(5).repeat(5), np.tile(np.arange(5), 5)] ) @@ -676,7 +672,6 @@ def test_nan_in_object_array(self): tm.assert_numpy_array_equal(result, expected) def test_categorical(self): - # we are expecting to return in the order # of appearance expected = Categorical(list("bac")) @@ -891,7 +886,6 @@ def test_nunique_ints(index_or_series_or_array): class TestIsin: def test_invalid(self): - msg = ( r"only list-like objects are allowed to be passed to isin\(\), " r"you passed a \[int\]" @@ -904,7 +898,6 @@ def test_invalid(self): algos.isin([1], 1) def test_basic(self): - result = algos.isin([1, 2], [1]) expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) @@ -942,7 +935,6 @@ def test_basic(self): tm.assert_numpy_array_equal(result, expected) def test_i8(self): - arr = date_range("20130101", periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) @@ -1504,7 +1496,6 @@ def test_numeric_object_likes(self, case): tm.assert_series_equal(res_false, Series(exp_false)) def test_datetime_likes(self): - dt = [ "2011-01-01", "2011-01-02", @@ -1770,7 +1761,6 @@ def test_pct_max_many_rows(self): def test_pad_backfill_object_segfault(): - old = np.array([], dtype="O") new = np.array([datetime(2010, 12, 31)], dtype="O") diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index fea10075a0ace..b17dce234043c 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -35,7 +35,6 @@ def df(): def test_dask(df): - # dask sets "compute.use_numexpr" to False, so catch the current value # and ensure to reset it afterwards to avoid impacting other tests olduse = pd.get_option("compute.use_numexpr") @@ -101,7 +100,6 @@ def test_construct_dask_float_array_int_dtype_match_ndarray(): def test_xarray(df): - xarray = import_module("xarray") # noqa:F841 assert df.to_xarray() is not None @@ -144,7 +142,6 @@ def test_oo_optimized_datetime_index_unpickle(): @pytest.mark.network @tm.network def test_statsmodels(): - statsmodels = import_module("statsmodels") # noqa:F841 import statsmodels.api as sm import statsmodels.formula.api as smf @@ -154,7 +151,6 @@ def test_statsmodels(): def test_scikit_learn(): - sklearn = import_module("sklearn") # noqa:F841 from sklearn import ( datasets, @@ -170,7 +166,6 @@ def test_scikit_learn(): @pytest.mark.network @tm.network def test_seaborn(): - seaborn = import_module("seaborn") tips = seaborn.load_dataset("tips") seaborn.stripplot(x="day", y="total_bill", data=tips) @@ -190,13 +185,11 @@ def test_pandas_gbq(): "variable or through the environmental variable QUANDL_API_KEY", ) def test_pandas_datareader(): - pandas_datareader = import_module("pandas_datareader") pandas_datareader.DataReader("F", "quandl", "2017-01-01", "2017-02-01") def test_pyarrow(df): - pyarrow = import_module("pyarrow") table = pyarrow.Table.from_pandas(df) result = table.to_pandas() diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index a627f3172f0c6..c241603fd7ff9 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -211,7 +211,6 @@ def test_binary_ops(self, request, opname, op_str, left_fix, right_fix): right = request.getfixturevalue(right_fix) def testit(): - if opname == "pow": # TODO: get this working return diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index d6deafb9012ff..909ae22410d73 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -280,7 +280,6 @@ def check_results(self, targ, res, axis, check_dtype=True): try: tm.assert_almost_equal(targ, res, check_dtype=check_dtype) except AssertionError: - # handle timedelta dtypes if hasattr(targ, "dtype") and targ.dtype == "m8[ns]": raise @@ -365,7 +364,6 @@ def check_fun_data( def check_fun( self, testfunc, targfunc, testar, skipna, empty_targfunc=None, **kwargs ): - targar = testar if testar.endswith("_nan") and hasattr(self, testar[:-4]): targar = testar[:-4] @@ -935,7 +933,6 @@ def test_non_convertable_values(self): class TestNanvarFixedValues: - # xref GH10242 # Samples from a normal distribution. @pytest.fixture @@ -1053,7 +1050,6 @@ def prng(self): class TestNanskewFixedValues: - # xref GH 11974 # Test data + skewness value (computed with scipy.stats.skew) @pytest.fixture @@ -1105,7 +1101,6 @@ def prng(self): class TestNankurtFixedValues: - # xref GH 11974 # Test data + kurtosis value (computed with scipy.stats.kurtosis) @pytest.fixture @@ -1198,9 +1193,7 @@ def test_nanmean_skipna_false(self, constructor, unit): def test_use_bottleneck(): - if nanops._BOTTLENECK_INSTALLED: - with pd.option_context("use_bottleneck", True): assert pd.get_option("use_bottleneck") diff --git a/pandas/tests/test_register_accessor.py b/pandas/tests/test_register_accessor.py index f0f330cc741b7..a1a74dda4bd6f 100644 --- a/pandas/tests/test_register_accessor.py +++ b/pandas/tests/test_register_accessor.py @@ -98,7 +98,6 @@ def test_overwrite_warns(): def test_raises_attribute_error(): - with ensure_removed(pd.Series, "bad"): @pd.api.extensions.register_series_accessor("bad") diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 71f2cae49fe41..dc8b7ce0996a9 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -424,7 +424,6 @@ def test_non_exact_doesnt_parse_whole_string(self, cache, format, expected): ], ) def test_parse_nanoseconds_with_formula(self, cache, arg): - # GH8989 # truncating the nanoseconds when a format was provided expected = to_datetime(arg, cache=cache) @@ -1110,7 +1109,6 @@ def test_out_of_bounds_errors_ignore(self): assert result == expected def test_to_datetime_tz(self, cache): - # xref 8260 # uniform returns a DatetimeIndex arr = [ @@ -1248,7 +1246,6 @@ def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): @td.skip_if_no("psycopg2") def test_to_datetime_tz_psycopg2(self, request, cache): - # xref 8260 import psycopg2 @@ -1946,7 +1943,6 @@ def test_to_datetime_unit_with_nulls(self, null): tm.assert_series_equal(result, expected) def test_to_datetime_unit_fractional_seconds(self): - # GH13834 epoch = 1370745748 ser = Series([epoch + t for t in np.arange(0, 2, 0.25)] + [iNaT]).astype(float) @@ -2024,7 +2020,6 @@ def df(self): ) def test_dataframe(self, df, cache): - result = to_datetime( {"year": df["year"], "month": df["month"], "day": df["day"]}, cache=cache ) @@ -2992,7 +2987,6 @@ class TestDatetimeParsingWrappers: ], ) def test_parsers(self, date_str, expected, warning, cache): - # dateutil >= 2.5.0 defaults to yearfirst=True # https://github.com/dateutil/dateutil/issues/217 yearfirst = True @@ -3262,7 +3256,6 @@ def test_julian_round_trip(self): to_datetime(1, origin="julian", unit="D") def test_invalid_unit(self, units, julian_dates): - # checking for invalid combination of origin='julian' and unit != D if units != "D": msg = "unit must be 'D' for origin='julian'" @@ -3271,14 +3264,12 @@ def test_invalid_unit(self, units, julian_dates): @pytest.mark.parametrize("unit", ["ns", "D"]) def test_invalid_origin(self, unit): - # need to have a numeric specified msg = "it must be numeric with a unit specified" with pytest.raises(ValueError, match=msg): to_datetime("2005-01-01", origin="1960-01-01", unit=unit) def test_epoch(self, units, epochs, epoch_1960, units_from_epochs): - expected = Series( [pd.Timedelta(x, unit=units) + epoch_1960 for x in units_from_epochs] ) @@ -3296,7 +3287,6 @@ def test_epoch(self, units, epochs, epoch_1960, units_from_epochs): ], ) def test_invalid_origins(self, origin, exc, units, units_from_epochs): - msg = "|".join( [ f"origin {origin} is Out of Bounds", @@ -3443,7 +3433,6 @@ def test_nullable_integer_to_datetime(): @pytest.mark.parametrize("klass", [np.array, list]) def test_na_to_datetime(nulls_fixture, klass): - if isinstance(nulls_fixture, Decimal): with pytest.raises(TypeError, match="not convertible to datetime"): to_datetime(klass([nulls_fixture])) diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index 6be499b6dc474..b27a0db4dfe98 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -98,7 +98,6 @@ def test_to_timedelta_dataframe(self, arg, errors): to_timedelta(arg, errors=errors) def test_to_timedelta_invalid_errors(self): - # bad value for errors parameter msg = "errors must be one of" with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/tseries/offsets/test_business_day.py b/pandas/tests/tseries/offsets/test_business_day.py index 82cc28ef44a34..7db1921369023 100644 --- a/pandas/tests/tseries/offsets/test_business_day.py +++ b/pandas/tests/tseries/offsets/test_business_day.py @@ -80,7 +80,6 @@ def test_with_offset(self, dt, offset): ids=lambda x: type(x), ) def test_with_offset_index(self, td, dt, offset): - dti = DatetimeIndex([dt]) expected = DatetimeIndex([datetime(2008, 1, 2, 2)]) diff --git a/pandas/tests/tseries/offsets/test_dst.py b/pandas/tests/tseries/offsets/test_dst.py index 347c91a67ebb5..e00b7d0b78059 100644 --- a/pandas/tests/tseries/offsets/test_dst.py +++ b/pandas/tests/tseries/offsets/test_dst.py @@ -43,7 +43,6 @@ def get_utc_offset_hours(ts): class TestDST: - # one microsecond before the DST transition ts_pre_fallback = "2013-11-03 01:59:59.999999" ts_pre_springfwd = "2013-03-10 01:59:59.999999" diff --git a/pandas/tests/tseries/offsets/test_fiscal.py b/pandas/tests/tseries/offsets/test_fiscal.py index 26937c348d9c8..7f8c34bc6832e 100644 --- a/pandas/tests/tseries/offsets/test_fiscal.py +++ b/pandas/tests/tseries/offsets/test_fiscal.py @@ -510,7 +510,6 @@ def test_get_weeks(self): class TestFY5253NearestEndMonthQuarter: - offset_nem_sat_aug_4 = makeFY5253NearestEndMonthQuarter( 1, startingMonth=8, weekday=WeekDay.SAT, qtr_with_extra_week=4 ) diff --git a/pandas/tests/tseries/offsets/test_month.py b/pandas/tests/tseries/offsets/test_month.py index e1bed2285bcdc..fc12510369245 100644 --- a/pandas/tests/tseries/offsets/test_month.py +++ b/pandas/tests/tseries/offsets/test_month.py @@ -524,7 +524,6 @@ def test_vectorized_offset_addition(self, klass): class TestMonthBegin: - offset_cases = [] # NOTE: I'm not entirely happy with the logic here for Begin -ss # see thread 'offset conventions' on the ML diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 57a783d601a50..289045a3c4efd 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -219,7 +219,6 @@ def test_offset_freqstr(self, offset_types): assert offset.rule_code == code def _check_offsetfunc_works(self, offset, funcname, dt, expected, normalize=False): - if normalize and issubclass(offset, Tick): # normalize=True disallowed for Tick subclasses GH#21427 return diff --git a/pandas/tests/tslibs/test_api.py b/pandas/tests/tslibs/test_api.py index 264662a7e93cd..a596d4a85074e 100644 --- a/pandas/tests/tslibs/test_api.py +++ b/pandas/tests/tslibs/test_api.py @@ -4,7 +4,6 @@ def test_namespace(): - submodules = [ "base", "ccalendar", diff --git a/pandas/tests/util/test_assert_almost_equal.py b/pandas/tests/util/test_assert_almost_equal.py index d5c334c87315d..987af3ee1e78e 100644 --- a/pandas/tests/util/test_assert_almost_equal.py +++ b/pandas/tests/util/test_assert_almost_equal.py @@ -335,7 +335,6 @@ def test_assert_almost_equal_value_mismatch(): [(np.array([1]), 1, "ndarray", "int"), (1, np.array([1]), "int", "ndarray")], ) def test_assert_almost_equal_class_mismatch(a, b, klass1, klass2): - msg = f"""numpy array are different numpy array classes are different diff --git a/pandas/tests/util/test_assert_index_equal.py b/pandas/tests/util/test_assert_index_equal.py index b7a68ab3960a1..f7d41ed536a40 100644 --- a/pandas/tests/util/test_assert_index_equal.py +++ b/pandas/tests/util/test_assert_index_equal.py @@ -187,7 +187,6 @@ def test_index_equal_level_values_mismatch(check_exact, rtol): [(None, "x"), ("x", "x"), (np.nan, np.nan), (NaT, NaT), (np.nan, NaT)], ) def test_index_equal_names(name1, name2): - idx1 = Index([1, 2, 3], name=name1) idx2 = Index([1, 2, 3], name=name2) diff --git a/pandas/tests/window/test_api.py b/pandas/tests/window/test_api.py index 6180d4a5f8e17..68b3f2b9f8e77 100644 --- a/pandas/tests/window/test_api.py +++ b/pandas/tests/window/test_api.py @@ -48,7 +48,6 @@ def test_select_bad_cols(): def test_attribute_access(): - df = DataFrame([[1, 2]], columns=["A", "B"]) r = df.rolling(window=5) tm.assert_series_equal(r.A.sum(), r["A"].sum()) @@ -58,7 +57,6 @@ def test_attribute_access(): def tests_skip_nuisance(step): - df = DataFrame({"A": range(5), "B": range(5, 10), "C": "foo"}) r = df.rolling(window=3, step=step) result = r[["A", "B"]].sum() @@ -137,7 +135,6 @@ def test_multi_axis_1_raises(func): def test_agg_apply(raw): - # passed lambda df = DataFrame({"A": range(5), "B": range(0, 10, 2)}) @@ -151,7 +148,6 @@ def test_agg_apply(raw): def test_agg_consistency(step): - df = DataFrame({"A": range(5), "B": range(0, 10, 2)}) r = df.rolling(window=3, step=step) @@ -169,7 +165,6 @@ def test_agg_consistency(step): def test_agg_nested_dicts(): - # API change for disallowing these types of nested dicts df = DataFrame({"A": range(5), "B": range(0, 10, 2)}) r = df.rolling(window=3) @@ -348,7 +343,6 @@ def test_dont_modify_attributes_after_methods( def test_centered_axis_validation(step): - # ok Series(np.ones(10)).rolling(window=3, center=True, axis=0, step=step).mean() diff --git a/pandas/tests/window/test_dtypes.py b/pandas/tests/window/test_dtypes.py index b975a28273337..4007320b5de33 100644 --- a/pandas/tests/window/test_dtypes.py +++ b/pandas/tests/window/test_dtypes.py @@ -160,7 +160,6 @@ def test_series_nullable_int(any_signed_int_ea_dtype, step): ], ) def test_dataframe_dtypes(method, expected_data, dtypes, min_periods, step): - df = DataFrame(np.arange(10).reshape((5, 2)), dtype=get_dtype(dtypes)) rolled = df.rolling(2, min_periods=min_periods, step=step) diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index 205a02dcb051b..9870c02692a7f 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -11,14 +11,12 @@ def test_doc_string(): - df = DataFrame({"B": [0, 1, 2, np.nan, 4]}) df df.ewm(com=0.5).mean() def test_constructor(frame_or_series): - c = frame_or_series(range(5)).ewm # valid diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index 64e732e89a0dc..638df10fa6d50 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -14,7 +14,6 @@ def test_doc_string(): - df = DataFrame({"B": [0, 1, 2, np.nan, 4]}) df df.expanding(2).sum() @@ -186,7 +185,7 @@ def test_iter_expanding_dataframe(df, expected, min_periods): # GH 11704 expected = [DataFrame(values, index=index) for (values, index) in expected] - for (expected, actual) in zip(expected, df.expanding(min_periods)): + for expected, actual in zip(expected, df.expanding(min_periods)): tm.assert_frame_equal(actual, expected) @@ -205,7 +204,7 @@ def test_iter_expanding_series(ser, expected, min_periods): # GH 11704 expected = [Series(values, index=index) for (values, index) in expected] - for (expected, actual) in zip(expected, ser.expanding(min_periods)): + for expected, actual in zip(expected, ser.expanding(min_periods)): tm.assert_series_equal(actual, expected) @@ -428,7 +427,6 @@ def test_expanding_min_periods_apply(engine_and_raw): ], ) def test_moment_functions_zero_length_pairwise(f): - df1 = DataFrame() df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) df2["a"] = df2["a"].astype("float64") diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py index 194a3ab2db239..eb4fc06aa523e 100644 --- a/pandas/tests/window/test_groupby.py +++ b/pandas/tests/window/test_groupby.py @@ -47,7 +47,6 @@ def roll_frame(): class TestRolling: def test_groupby_unsupported_argument(self, roll_frame): - msg = r"groupby\(\) got an unexpected keyword argument 'foo'" with pytest.raises(TypeError, match=msg): roll_frame.groupby("A", foo=1) @@ -71,7 +70,6 @@ def test_getitem(self, roll_frame): tm.assert_series_equal(result, expected) def test_getitem_multiple(self, roll_frame): - # GH 13174 g = roll_frame.groupby("A") r = g.rolling(2, min_periods=0) @@ -933,7 +931,6 @@ def test_groupby_rolling_non_monotonic(self): df.groupby("c").rolling(on="t", window="3s") def test_groupby_monotonic(self): - # GH 15130 # we don't need to validate monotonicity when grouping diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index cca0ab3a0a9bb..dbafcf12513e0 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -103,7 +103,6 @@ def test_numba_vs_cython_rolling_methods( arithmetic_numba_supported_operators, step, ): - method, kwargs = arithmetic_numba_supported_operators engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} @@ -121,7 +120,6 @@ def test_numba_vs_cython_rolling_methods( def test_numba_vs_cython_expanding_methods( self, data, nogil, parallel, nopython, arithmetic_numba_supported_operators ): - method, kwargs = arithmetic_numba_supported_operators engine_kwargs = {"nogil": nogil, "parallel": parallel, "nopython": nopython} diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py index 2b656a5d4e7b9..695627668b80b 100644 --- a/pandas/tests/window/test_pairwise.py +++ b/pandas/tests/window/test_pairwise.py @@ -168,7 +168,6 @@ def test_rolling_corr_diff_length(): ], ) def test_rolling_functions_window_non_shrinkage_binary(f): - # corr/cov return a MI DataFrame df = DataFrame( [[1, 5], [3, 2], [3, 9], [-1, 0]], @@ -192,7 +191,6 @@ def test_rolling_functions_window_non_shrinkage_binary(f): ], ) def test_moment_functions_zero_length_pairwise(f): - df1 = DataFrame() df2 = DataFrame(columns=Index(["a"], name="foo"), index=Index([], name="bar")) df2["a"] = df2["a"].astype("float64") @@ -212,11 +210,9 @@ def test_moment_functions_zero_length_pairwise(f): class TestPairwise: - # GH 7738 @pytest.mark.parametrize("f", [lambda x: x.cov(), lambda x: x.corr()]) def test_no_flex(self, pairwise_frames, pairwise_target_frame, f): - # DataFrame methods (which do not call flex_binary_moment()) result = f(pairwise_frames) @@ -242,7 +238,6 @@ def test_no_flex(self, pairwise_frames, pairwise_target_frame, f): ], ) def test_pairwise_with_self(self, pairwise_frames, pairwise_target_frame, f): - # DataFrame with itself, pairwise=True # note that we may construct the 1st level of the MI # in a non-monotonic way, so compare accordingly @@ -275,7 +270,6 @@ def test_pairwise_with_self(self, pairwise_frames, pairwise_target_frame, f): ], ) def test_no_pairwise_with_self(self, pairwise_frames, pairwise_target_frame, f): - # DataFrame with itself, pairwise=False result = f(pairwise_frames) tm.assert_index_equal(result.index, pairwise_frames.index) @@ -302,7 +296,6 @@ def test_no_pairwise_with_self(self, pairwise_frames, pairwise_target_frame, f): def test_pairwise_with_other( self, pairwise_frames, pairwise_target_frame, pairwise_other_frame, f ): - # DataFrame with another DataFrame, pairwise=True result = f(pairwise_frames, pairwise_other_frame) tm.assert_index_equal( @@ -332,7 +325,6 @@ def test_pairwise_with_other( ], ) def test_no_pairwise_with_other(self, pairwise_frames, pairwise_other_frame, f): - # DataFrame with another DataFrame, pairwise=False result = ( f(pairwise_frames, pairwise_other_frame) @@ -367,7 +359,6 @@ def test_no_pairwise_with_other(self, pairwise_frames, pairwise_other_frame, f): ], ) def test_pairwise_with_series(self, pairwise_frames, pairwise_target_frame, f): - # DataFrame with a Series result = f(pairwise_frames, Series([1, 1, 3, 8])) tm.assert_index_equal(result.index, pairwise_frames.index) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index f6c96375407e0..e8533b3ca2619 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -32,7 +32,6 @@ def test_doc_string(): - df = DataFrame({"B": [0, 1, 2, np.nan, 4]}) df df.rolling(2).sum() @@ -516,7 +515,6 @@ def test_missing_minp_zero_variable(): def test_multi_index_names(): - # GH 16789, 16825 cols = MultiIndex.from_product([["A", "B"], ["C", "D", "E"]], names=["1", "2"]) df = DataFrame(np.ones((10, 6)), columns=cols) @@ -798,9 +796,7 @@ def test_iter_rolling_dataframe(df, expected, window, min_periods): # GH 11704 expected = [DataFrame(values, index=index) for (values, index) in expected] - for (expected, actual) in zip( - expected, df.rolling(window, min_periods=min_periods) - ): + for expected, actual in zip(expected, df.rolling(window, min_periods=min_periods)): tm.assert_frame_equal(actual, expected) @@ -846,7 +842,7 @@ def test_iter_rolling_on_dataframe(expected, window): expected = [ DataFrame(values, index=df.loc[index, "C"]) for (values, index) in expected ] - for (expected, actual) in zip(expected, df.rolling(window, on="C")): + for expected, actual in zip(expected, df.rolling(window, on="C")): tm.assert_frame_equal(actual, expected) @@ -896,9 +892,7 @@ def test_iter_rolling_series(ser, expected, window, min_periods): # GH 11704 expected = [Series(values, index=index) for (values, index) in expected] - for (expected, actual) in zip( - expected, ser.rolling(window, min_periods=min_periods) - ): + for expected, actual in zip(expected, ser.rolling(window, min_periods=min_periods)): tm.assert_series_equal(actual, expected) @@ -948,7 +942,7 @@ def test_iter_rolling_datetime(expected, expected_index, window): Series(values, index=idx) for (values, idx) in zip(expected, expected_index) ] - for (expected, actual) in zip(expected, ser.rolling(window)): + for expected, actual in zip(expected, ser.rolling(window)): tm.assert_series_equal(actual, expected) diff --git a/pandas/tests/window/test_rolling_functions.py b/pandas/tests/window/test_rolling_functions.py index bb6faf4f4eb22..c4519701da7ab 100644 --- a/pandas/tests/window/test_rolling_functions.py +++ b/pandas/tests/window/test_rolling_functions.py @@ -384,7 +384,6 @@ def test_rolling_max_gh6297(step): def test_rolling_max_resample(step): - indices = [datetime(1975, 1, i) for i in range(1, 6)] # So that we can have 3 datapoints on last day (4, 10, and 20) indices.append(datetime(1975, 1, 5, 1)) @@ -422,7 +421,6 @@ def test_rolling_max_resample(step): def test_rolling_min_resample(step): - indices = [datetime(1975, 1, i) for i in range(1, 6)] # So that we can have 3 datapoints on last day (4, 10, and 20) indices.append(datetime(1975, 1, 5, 1)) @@ -443,7 +441,6 @@ def test_rolling_min_resample(step): def test_rolling_median_resample(): - indices = [datetime(1975, 1, i) for i in range(1, 6)] # So that we can have 3 datapoints on last day (4, 10, and 20) indices.append(datetime(1975, 1, 5, 1)) diff --git a/pandas/tests/window/test_rolling_skew_kurt.py b/pandas/tests/window/test_rolling_skew_kurt.py index 8f162f376c863..43db772251219 100644 --- a/pandas/tests/window/test_rolling_skew_kurt.py +++ b/pandas/tests/window/test_rolling_skew_kurt.py @@ -177,7 +177,6 @@ def test_center_reindex_frame(frame, roll_func): def test_rolling_skew_edge_cases(step): - expected = Series([np.NaN] * 4 + [0.0])[::step] # yields all NaN (0 variance) d = Series([1] * 5) @@ -199,7 +198,6 @@ def test_rolling_skew_edge_cases(step): def test_rolling_kurt_edge_cases(step): - expected = Series([np.NaN] * 4 + [-3.0])[::step] # yields all NaN (0 variance) diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index f33dfb2ca94ec..0de4b863183df 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -36,12 +36,10 @@ def ragged(): class TestRollingTS: - # rolling time-series friendly # xref GH13327 def test_doc_string(self): - df = DataFrame( {"B": [0, 1, 2, np.nan, 4]}, index=[ @@ -56,7 +54,6 @@ def test_doc_string(self): df.rolling("2s").sum() def test_invalid_window_non_int(self, regular): - # not a valid freq msg = "passed window foobar is not compatible with a datetimelike index" with pytest.raises(ValueError, match=msg): @@ -68,7 +65,6 @@ def test_invalid_window_non_int(self, regular): @pytest.mark.parametrize("freq", ["2MS", offsets.MonthBegin(2)]) def test_invalid_window_nonfixed(self, freq, regular): - # non-fixed freqs msg = "\\<2 \\* MonthBegins\\> is a non-fixed frequency" with pytest.raises(ValueError, match=msg): @@ -89,7 +85,6 @@ def test_invalid_minp(self, minp, regular): regular.rolling(window="1D", min_periods=minp) def test_on(self, regular): - df = regular # not a valid column @@ -114,7 +109,6 @@ def test_on(self, regular): df.rolling(window="2d", on="C").B.sum() def test_monotonic_on(self): - # on/index must be monotonic df = DataFrame( {"A": date_range("20130101", periods=5, freq="s"), "B": range(5)} @@ -153,7 +147,6 @@ def test_non_monotonic_on(self): df.rolling("2s", on="A").sum() def test_frame_on(self): - df = DataFrame( {"B": range(5), "C": date_range("20130101 09:00:00", periods=5, freq="3s")} ) @@ -186,7 +179,6 @@ def test_frame_on(self): tm.assert_frame_equal(result, expected) def test_frame_on2(self): - # using multiple aggregation columns df = DataFrame( { @@ -223,7 +215,6 @@ def test_frame_on2(self): tm.assert_frame_equal(result, expected) def test_basic_regular(self, regular): - df = regular.copy() df.index = date_range("20130101", periods=5, freq="D") @@ -245,7 +236,6 @@ def test_basic_regular(self, regular): tm.assert_frame_equal(result, expected) def test_min_periods(self, regular): - # compare for min_periods df = regular @@ -259,7 +249,6 @@ def test_min_periods(self, regular): tm.assert_frame_equal(result, expected) def test_closed(self, regular): - # xref GH13965 df = DataFrame( @@ -303,7 +292,6 @@ def test_closed(self, regular): tm.assert_frame_equal(result, expected) def test_ragged_sum(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).sum() expected = df.copy() @@ -346,7 +334,6 @@ def test_ragged_sum(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_mean(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).mean() expected = df.copy() @@ -359,7 +346,6 @@ def test_ragged_mean(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_median(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).median() expected = df.copy() @@ -372,7 +358,6 @@ def test_ragged_median(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_quantile(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).quantile(0.5) expected = df.copy() @@ -385,7 +370,6 @@ def test_ragged_quantile(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_std(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).std(ddof=0) expected = df.copy() @@ -408,7 +392,6 @@ def test_ragged_std(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_var(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).var(ddof=0) expected = df.copy() @@ -431,7 +414,6 @@ def test_ragged_var(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_skew(self, ragged): - df = ragged result = df.rolling(window="3s", min_periods=1).skew() expected = df.copy() @@ -444,7 +426,6 @@ def test_ragged_skew(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_kurt(self, ragged): - df = ragged result = df.rolling(window="3s", min_periods=1).kurt() expected = df.copy() @@ -457,7 +438,6 @@ def test_ragged_kurt(self, ragged): tm.assert_frame_equal(result, expected) def test_ragged_count(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).count() expected = df.copy() @@ -479,7 +459,6 @@ def test_ragged_count(self, ragged): tm.assert_frame_equal(result, expected) def test_regular_min(self): - df = DataFrame( {"A": date_range("20130101", periods=5, freq="s"), "B": [0.0, 1, 2, 3, 4]} ).set_index("A") @@ -504,7 +483,6 @@ def test_regular_min(self): tm.assert_frame_equal(result, expected) def test_ragged_min(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).min() @@ -523,7 +501,6 @@ def test_ragged_min(self, ragged): tm.assert_frame_equal(result, expected) def test_perf_min(self): - N = 10000 dfp = DataFrame( @@ -538,7 +515,6 @@ def test_perf_min(self): assert ((result - expected) < 0.01).all().bool() def test_ragged_max(self, ragged): - df = ragged result = df.rolling(window="1s", min_periods=1).max() @@ -604,7 +580,6 @@ def test_freqs_ops(self, freq, op, result_data): ], ) def test_all(self, f, regular): - # simple comparison of integer vs time-based windowing df = regular * 2 er = df.rolling(window=1) diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index 0583b714ea101..9f1e166cd6afb 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -347,7 +347,6 @@ def _apply_rule(self, dates): else: offsets = self.offset for offset in offsets: - # if we are adding a non-vectorized value # ignore the PerformanceWarnings: with warnings.catch_warnings(): diff --git a/pandas/util/version/__init__.py b/pandas/util/version/__init__.py index a6eccf2941342..0b5e1d149daaa 100644 --- a/pandas/util/version/__init__.py +++ b/pandas/util/version/__init__.py @@ -269,7 +269,6 @@ def _parse_version_parts(s: str) -> Iterator[str]: def _legacy_cmpkey(version: str) -> LegacyCmpKey: - # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch # greater than or equal to 0. This will effectively put the LegacyVersion, # which uses the defacto standard originally implemented by setuptools, @@ -330,11 +329,9 @@ def _legacy_cmpkey(version: str) -> LegacyCmpKey: class Version(_BaseVersion): - _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE) def __init__(self, version: str) -> None: - # Validate the version and parse it into pieces match = self._regex.search(version) if not match: @@ -468,7 +465,6 @@ def micro(self) -> int: def _parse_letter_version( letter: str, number: str | bytes | SupportsInt ) -> tuple[str, int] | None: - if letter: # We consider there to be an implicit 0 in a pre-release if there is # not a numeral associated with it. @@ -524,7 +520,6 @@ def _cmpkey( dev: tuple[str, int] | None, local: tuple[SubLocalType] | None, ) -> CmpKey: - # When we compare a release version, we want to compare it with all of the # trailing zeros removed. So we'll use a reverse the list, drop all the now # leading zeros until we come to something non zero, then take the rest diff --git a/pyproject.toml b/pyproject.toml index 56c16de0b06b4..8cd0155aca09e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -174,6 +174,7 @@ environment = { IS_32_BIT="true" } [tool.black] target-version = ['py38', 'py39'] +required-version = '23.1.0' exclude = ''' ( asv_bench/env diff --git a/requirements-dev.txt b/requirements-dev.txt index 6d9bd1c93ded0..a06cff7cd2ccd 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -52,7 +52,7 @@ seaborn moto flask asv>=0.5.1 -black==22.10.0 +black==23.1.0 cpplint flake8==6.0.0 isort>=5.2.1 diff --git a/setup.py b/setup.py index f8fa048757289..87ef0b6029a64 100755 --- a/setup.py +++ b/setup.py @@ -393,6 +393,7 @@ def run(self): # ---------------------------------------------------------------------- # Specification of Dependencies + # TODO(cython#4518): Need to check to see if e.g. `linetrace` has changed and # possibly re-compile. def maybe_cythonize(extensions, *args, **kwargs):
gonna have to do this eventually... I'm trying to tell if it changed anything other than just deleting newlines, any `git` masters know how to do that?
https://api.github.com/repos/pandas-dev/pandas/pulls/51348
2023-02-12T19:19:19Z
2023-02-14T21:07:21Z
2023-02-14T21:07:21Z
2023-02-14T21:08:04Z
PERF: ArrowExtensionArray.to_numpy(dtype=object)
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 07c7120a8f6c1..cda8c72e6b773 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1124,7 +1124,7 @@ Performance improvements - Performance improvement in :meth:`~arrays.ArrowExtensionArray.factorize` (:issue:`49177`) - Performance improvement in :meth:`~arrays.ArrowExtensionArray.__setitem__` (:issue:`50248`, :issue:`50632`) - Performance improvement in :class:`~arrays.ArrowExtensionArray` comparison methods when array contains NA (:issue:`50524`) -- Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`49973`) +- Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`49973`, :issue:`51227`) - Performance improvement when parsing strings to :class:`BooleanDtype` (:issue:`50613`) - Performance improvement in :meth:`DataFrame.join` when joining on a subset of a :class:`MultiIndex` (:issue:`48611`) - Performance improvement for :meth:`MultiIndex.intersection` (:issue:`48604`) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 16cfb6d7c396b..14718711727b0 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -864,12 +864,15 @@ def to_numpy( na_value = self.dtype.na_value pa_type = self._data.type - if ( - is_object_dtype(dtype) - or pa.types.is_timestamp(pa_type) - or pa.types.is_duration(pa_type) - ): + if pa.types.is_temporal(pa_type) and not pa.types.is_date(pa_type): + # temporal types with units and/or timezones currently + # require pandas/python scalars to pass all tests + # TODO: improve performance (this is slow) result = np.array(list(self), dtype=dtype) + elif is_object_dtype(dtype) and self._hasna: + result = np.empty(len(self), dtype=object) + mask = ~self.isna() + result[mask] = np.asarray(self[mask]._data) else: result = np.asarray(self._data, dtype=dtype) if copy or self._hasna: diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 9406c7c2f59c6..bfad33f3857e7 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -1518,6 +1518,16 @@ def test_to_numpy_with_defaults(data): tm.assert_numpy_array_equal(result, expected) +def test_to_numpy_int_with_na(): + # GH51227: ensure to_numpy does not convert int to float + data = [1, None] + arr = pd.array(data, dtype="int64[pyarrow]") + result = arr.to_numpy() + expected = np.array([1, pd.NA], dtype=object) + assert isinstance(result[0], int) + tm.assert_numpy_array_equal(result, expected) + + def test_setitem_null_slice(data): # GH50248 orig = data.copy()
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. redo of #51227 which had to be reverted. cc @mroeschke @phofl
https://api.github.com/repos/pandas-dev/pandas/pulls/51347
2023-02-12T03:01:30Z
2023-02-16T16:42:13Z
2023-02-16T16:42:13Z
2023-02-23T01:38:59Z
ENH: Index set operations with sort=True
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 29f360e050548..a393e0dca4c79 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -312,6 +312,7 @@ Other enhancements - Added new argument ``dtype`` to :func:`read_sql` to be consistent with :func:`read_sql_query` (:issue:`50797`) - Added new argument ``engine`` to :func:`read_json` to support parsing JSON with pyarrow by specifying ``engine="pyarrow"`` (:issue:`48893`) - Added support for SQLAlchemy 2.0 (:issue:`40686`) +- :class:`Index` set operations :meth:`Index.union`, :meth:`Index.intersection`, :meth:`Index.difference`, and :meth:`Index.symmetric_difference` now support ``sort=True``, which will always return a sorted result, unlike the default ``sort=None`` which does not sort in some cases (:issue:`25151`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 363bfe76d40fb..c0b280c760db4 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -3023,10 +3023,10 @@ def _get_reconciled_name_object(self, other): @final def _validate_sort_keyword(self, sort): - if sort not in [None, False]: + if sort not in [None, False, True]: raise ValueError( "The 'sort' keyword only takes the values of " - f"None or False; {sort} was passed." + f"None, True, or False; {sort} was passed." ) @final @@ -3070,6 +3070,7 @@ def union(self, other, sort=None): A RuntimeWarning is issued in this case. * False : do not sort the result. + * True : Sort the result (which may raise TypeError). Returns ------- @@ -3154,10 +3155,16 @@ def union(self, other, sort=None): elif not len(other) or self.equals(other): # NB: whether this (and the `if not len(self)` check below) come before # or after the is_dtype_equal check above affects the returned dtype - return self._get_reconciled_name_object(other) + result = self._get_reconciled_name_object(other) + if sort is True: + return result.sort_values() + return result elif not len(self): - return other._get_reconciled_name_object(self) + result = other._get_reconciled_name_object(self) + if sort is True: + return result.sort_values() + return result result = self._union(other, sort=sort) @@ -3258,12 +3265,13 @@ def intersection(self, other, sort: bool = False): Parameters ---------- other : Index or array-like - sort : False or None, default False + sort : True, False or None, default False Whether to sort the resulting index. - * False : do not sort the result. * None : sort the result, except when `self` and `other` are equal or when the values cannot be compared. + * False : do not sort the result. + * True : Sort the result (which may raise TypeError). Returns ------- @@ -3285,8 +3293,12 @@ def intersection(self, other, sort: bool = False): if self.equals(other): if self.has_duplicates: - return self.unique()._get_reconciled_name_object(other) - return self._get_reconciled_name_object(other) + result = self.unique()._get_reconciled_name_object(other) + else: + result = self._get_reconciled_name_object(other) + if sort is True: + result = result.sort_values() + return result if len(self) == 0 or len(other) == 0: # fastpath; we need to be careful about having commutativity @@ -3403,7 +3415,7 @@ def difference(self, other, sort=None): Parameters ---------- other : Index or array-like - sort : False or None, default None + sort : bool or None, default None Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. @@ -3411,6 +3423,7 @@ def difference(self, other, sort=None): * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. + * True : Sort the result (which may raise TypeError). Returns ------- @@ -3439,11 +3452,17 @@ def difference(self, other, sort=None): if len(other) == 0: # Note: we do not (yet) sort even if sort=None GH#24959 - return self.rename(result_name) + result = self.rename(result_name) + if sort is True: + return result.sort_values() + return result if not self._should_compare(other): # Nothing matches -> difference is everything - return self.rename(result_name) + result = self.rename(result_name) + if sort is True: + return result.sort_values() + return result result = self._difference(other, sort=sort) return self._wrap_difference_result(other, result) @@ -3479,7 +3498,7 @@ def symmetric_difference(self, other, result_name=None, sort=None): ---------- other : Index or array-like result_name : str - sort : False or None, default None + sort : bool or None, default None Whether to sort the resulting index. By default, the values are attempted to be sorted, but any TypeError from incomparable elements is caught by pandas. @@ -3487,6 +3506,7 @@ def symmetric_difference(self, other, result_name=None, sort=None): * None : Attempt to sort the result, but catch any TypeErrors from comparing incomparable elements. * False : Do not sort the result. + * True : Sort the result (which may raise TypeError). Returns ------- @@ -7161,10 +7181,12 @@ def unpack_nested_dtype(other: _IndexT) -> _IndexT: def _maybe_try_sort(result, sort): - if sort is None: + if sort is not False: try: result = algos.safe_sort(result) except TypeError as err: + if sort is True: + raise warnings.warn( f"{err}, sort order is undefined for incomparable objects.", RuntimeWarning, diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 95f35eabb342e..a4df2acf0ab45 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -3560,10 +3560,12 @@ def _union(self, other, sort) -> MultiIndex: else: result = self._get_reconciled_name_object(other) - if sort is None: + if sort is not False: try: result = result.sort_values() except TypeError: + if sort is True: + raise warnings.warn( "The values in the array are unorderable. " "Pass `sort=False` to suppress this warning.", diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index ca34fcfc7a625..670b97adf7c36 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -688,7 +688,7 @@ def _difference(self, other, sort=None): if not isinstance(other, RangeIndex): return super()._difference(other, sort=sort) - if sort is None and self.step < 0: + if sort is not False and self.step < 0: return self[::-1]._difference(other) res_name = ops.get_op_result_name(self, other) diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py index 87ffe99896199..21d1630af9de2 100644 --- a/pandas/tests/indexes/base_class/test_setops.py +++ b/pandas/tests/indexes/base_class/test_setops.py @@ -16,12 +16,15 @@ class TestIndexSetOps: @pytest.mark.parametrize( "method", ["union", "intersection", "difference", "symmetric_difference"] ) - def test_setops_disallow_true(self, method): + def test_setops_sort_validation(self, method): idx1 = Index(["a", "b"]) idx2 = Index(["b", "c"]) with pytest.raises(ValueError, match="The 'sort' keyword only takes"): - getattr(idx1, method)(idx2, sort=True) + getattr(idx1, method)(idx2, sort=2) + + # sort=True is supported as of GH#?? + getattr(idx1, method)(idx2, sort=True) def test_setops_preserve_object_dtype(self): idx = Index([1, 2, 3], dtype=object) @@ -88,17 +91,12 @@ def test_union_sort_other_incomparable(self): result = idx.union(idx[:1], sort=False) tm.assert_index_equal(result, idx) - @pytest.mark.xfail(reason="GH#25151 need to decide on True behavior") def test_union_sort_other_incomparable_true(self): - # TODO(GH#25151): decide on True behaviour - # sort=True idx = Index([1, pd.Timestamp("2000")]) with pytest.raises(TypeError, match=".*"): idx.union(idx[:1], sort=True) - @pytest.mark.xfail(reason="GH#25151 need to decide on True behavior") def test_intersection_equal_sort_true(self): - # TODO(GH#25151): decide on True behaviour idx = Index(["c", "a", "b"]) sorted_ = Index(["a", "b", "c"]) tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_) diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index 4979e461f4cf0..de4d0e014be29 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -204,7 +204,6 @@ def test_difference_sort_special(): tm.assert_index_equal(result, idx) -@pytest.mark.xfail(reason="Not implemented.") def test_difference_sort_special_true(): # TODO(GH#25151): decide on True behaviour idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) @@ -233,8 +232,10 @@ def test_difference_sort_incomparable_true(): idx = MultiIndex.from_product([[1, pd.Timestamp("2000"), 2], ["a", "b"]]) other = MultiIndex.from_product([[3, pd.Timestamp("2000"), 4], ["c", "d"]]) - msg = "The 'sort' keyword only takes the values of None or False; True was passed." - with pytest.raises(ValueError, match=msg): + # TODO: this is raising in constructing a Categorical when calling + # algos.safe_sort. Should we catch and re-raise with a better message? + msg = "'values' is not ordered, please explicitly specify the categories order " + with pytest.raises(TypeError, match=msg): idx.difference(other, sort=True) @@ -344,12 +345,11 @@ def test_intersect_equal_sort(): tm.assert_index_equal(idx.intersection(idx, sort=None), idx) -@pytest.mark.xfail(reason="Not implemented.") def test_intersect_equal_sort_true(): - # TODO(GH#25151): decide on True behaviour idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) - sorted_ = MultiIndex.from_product([[0, 1], ["a", "b"]]) - tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_) + expected = MultiIndex.from_product([[0, 1], ["a", "b"]]) + result = idx.intersection(idx, sort=True) + tm.assert_index_equal(result, expected) @pytest.mark.parametrize("slice_", [slice(None), slice(0)]) @@ -366,7 +366,6 @@ def test_union_sort_other_empty(slice_): tm.assert_index_equal(idx.union(other, sort=False), idx) -@pytest.mark.xfail(reason="Not implemented.") def test_union_sort_other_empty_sort(): # TODO(GH#25151): decide on True behaviour # # sort=True @@ -391,12 +390,10 @@ def test_union_sort_other_incomparable(): tm.assert_index_equal(result, idx) -@pytest.mark.xfail(reason="Not implemented.") def test_union_sort_other_incomparable_sort(): - # TODO(GH#25151): decide on True behaviour - # # sort=True idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]]) - with pytest.raises(TypeError, match="Cannot compare"): + msg = "'<' not supported between instances of 'Timestamp' and 'int'" + with pytest.raises(TypeError, match=msg): idx.union(idx[:1], sort=True) @@ -435,12 +432,15 @@ def test_union_multiindex_empty_rangeindex(): @pytest.mark.parametrize( "method", ["union", "intersection", "difference", "symmetric_difference"] ) -def test_setops_disallow_true(method): +def test_setops_sort_validation(method): idx1 = MultiIndex.from_product([["a", "b"], [1, 2]]) idx2 = MultiIndex.from_product([["b", "c"], [1, 2]]) with pytest.raises(ValueError, match="The 'sort' keyword only takes"): - getattr(idx1, method)(idx2, sort=True) + getattr(idx1, method)(idx2, sort=2) + + # sort=True is supported as of GH#? + getattr(idx1, method)(idx2, sort=True) @pytest.mark.parametrize("val", [pd.NA, 100]) diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py index 3e3de14960f4e..2276b10db1fe3 100644 --- a/pandas/tests/indexes/numeric/test_setops.py +++ b/pandas/tests/indexes/numeric/test_setops.py @@ -143,11 +143,8 @@ def test_union_sort_other_special(self, slice_): # sort=False tm.assert_index_equal(idx.union(other, sort=False), idx) - @pytest.mark.xfail(reason="Not implemented") @pytest.mark.parametrize("slice_", [slice(None), slice(0)]) def test_union_sort_special_true(self, slice_): - # TODO(GH#25151): decide on True behaviour - # sort=True idx = Index([1, 0, 2]) # default, sort=None other = idx[slice_] diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 001efe07b5d2b..dd27470d82111 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -836,16 +836,14 @@ def test_difference_incomparable(self, opname): 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(GH#25151): 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"): + msg = "'<' not supported between instances of 'Timestamp' and 'int'" + with pytest.raises(TypeError, match=msg): op(a) def test_symmetric_difference_mi(self, sort):
- [x] closes #25151 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51346
2023-02-12T01:21:26Z
2023-02-13T18:38:53Z
2023-02-13T18:38:52Z
2023-02-13T18:44:35Z
PERF: remove categories
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index fb953e601735e..bcf1ded63314e 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -73,7 +73,6 @@ from pandas.core.dtypes.missing import ( is_valid_na_for_dtype, isna, - notna, ) from pandas.core import ( @@ -1135,14 +1134,17 @@ def remove_categories(self, removals): [NaN, 'c', 'b', 'c', NaN] Categories (2, object): ['b', 'c'] """ + from pandas import Index + if not is_list_like(removals): removals = [removals] - removals = {x for x in set(removals) if notna(x)} + removals = Index(removals).unique().dropna() new_categories = self.dtype.categories.difference(removals) not_included = removals.difference(self.dtype.categories) if len(not_included) != 0: + not_included = set(not_included) raise ValueError(f"removals must all be in old categories: {not_included}") return self.set_categories(new_categories, ordered=self.ordered, rename=False)
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. cc @phofl, per https://github.com/pandas-dev/pandas/pull/50857#issuecomment-1426898195 I dont think we should revert #50857 as that fixed a few bugs. I think this gets most of the perf back though. No whatsnew as this was a slowdown on main only. ``` from asv_bench.benchmarks.categoricals import RemoveCategories b = RemoveCategories() b.setup() %timeit b.time_remove_categories() # 66.4 ms ± 1.92 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) <- main # 45.2 ms ± 1.57 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/51344
2023-02-12T01:17:01Z
2023-02-13T20:58:48Z
2023-02-13T20:58:48Z
2023-02-23T01:38:54Z
add typehint for None pct_change
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5d2a0fe66cc1d..f9afb50e1189a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10814,7 +10814,7 @@ def describe( def pct_change( self: NDFrameT, periods: int = 1, - fill_method: Literal["backfill", "bfill", "pad", "ffill"] = "pad", + fill_method: Literal["backfill", "bfill", "pad", "ffill"] | None = "pad", limit=None, freq=None, **kwargs,
- [x ] closes #51269 - [x ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) I've added a typehint for None. It looks like supplying `None` as an argument to `fill_method` is tested for dataframes under `pandas/tests/series/methods`. Let me know if another test should be written, e.g for dataframes.
https://api.github.com/repos/pandas-dev/pandas/pulls/51343
2023-02-12T01:04:43Z
2023-02-13T21:20:10Z
2023-02-13T21:20:10Z
2023-02-13T21:20:11Z
PERF: Fix performance regression in get_loc of IntervalIndex
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 6805d32049d34..482909d195bd0 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -675,7 +675,6 @@ def _shallow_copy(self: IntervalArrayT, left, right) -> IntervalArrayT: """ dtype = IntervalDtype(left.dtype, closed=self.closed) left, right, dtype = self._ensure_simple_new_inputs(left, right, dtype=dtype) - self._validate(left, right, dtype=dtype) return self._simple_new(left, right, dtype=dtype) @@ -727,7 +726,11 @@ def __getitem__( if np.ndim(left) > 1: # GH#30588 multi-dimensional indexer disallowed raise ValueError("multi-dimensional indexing not allowed") - return self._shallow_copy(left, right) + # Argument 2 to "_simple_new" of "IntervalArray" has incompatible type + # "Union[Period, Timestamp, Timedelta, NaTType, DatetimeArray, TimedeltaArray, + # ndarray[Any, Any]]"; expected "Union[Union[DatetimeArray, TimedeltaArray], + # ndarray[Any, Any]]" + return self._simple_new(left, right, dtype=self.dtype) # type: ignore[arg-type] def __setitem__(self, key, value) -> None: value_left, value_right = self._validate_setitem_value(value)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. caused in https://github.com/pandas-dev/pandas/commit/184e1674 No need to call validate here https://asv-runner.github.io/asv-collection/pandas/#indexing.IntervalIndexing.time_loc_list
https://api.github.com/repos/pandas-dev/pandas/pulls/51339
2023-02-12T00:08:02Z
2023-02-14T11:26:22Z
2023-02-14T11:26:22Z
2023-02-14T21:00:25Z
ENH: support addition with pyarrow string dtypes
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 894dc75e351a4..efd44b1bca3f2 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -1,6 +1,7 @@ from __future__ import annotations from copy import deepcopy +import operator import re from typing import ( TYPE_CHECKING, @@ -51,6 +52,7 @@ ) from pandas.core.dtypes.missing import isna +from pandas.core import roperator from pandas.core.arraylike import OpsMixin from pandas.core.arrays.base import ExtensionArray import pandas.core.common as com @@ -459,6 +461,29 @@ def _cmp_method(self, other, op): return BooleanArray(values, mask) def _evaluate_op_method(self, other, op, arrow_funcs): + pa_type = self._data.type + if (pa.types.is_string(pa_type) or pa.types.is_binary(pa_type)) and op in [ + operator.add, + roperator.radd, + ]: + length = self._data.length() + + seps: list[str] | list[bytes] + if pa.types.is_string(pa_type): + seps = [""] * length + else: + seps = [b""] * length + + if is_scalar(other): + other = [other] * length + elif isinstance(other, type(self)): + other = other._data + if op is operator.add: + result = pc.binary_join_element_wise(self._data, other, seps) + else: + result = pc.binary_join_element_wise(other, self._data, seps) + return type(self)(result) + pc_func = arrow_funcs[op.__name__] if pc_func is NotImplemented: raise NotImplementedError(f"{op.__name__} not implemented.") diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 8f9bf83881d3e..adb86b568e891 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -96,15 +96,7 @@ def test_astype_roundtrip(dtype): tm.assert_series_equal(result, ser) -def test_add(dtype, request): - if dtype.storage == "pyarrow": - reason = ( - "unsupported operand type(s) for +: 'ArrowStringArray' and " - "'ArrowStringArray'" - ) - mark = pytest.mark.xfail(raises=NotImplementedError, reason=reason) - request.node.add_marker(mark) - +def test_add(dtype): a = pd.Series(["a", "b", "c", None, None], dtype=dtype) b = pd.Series(["x", "y", None, "z", None], dtype=dtype) @@ -140,12 +132,7 @@ def test_add_2d(dtype, request): s + b -def test_add_sequence(dtype, request): - if dtype.storage == "pyarrow": - reason = "unsupported operand type(s) for +: 'ArrowStringArray' and 'list'" - mark = pytest.mark.xfail(raises=NotImplementedError, reason=reason) - request.node.add_marker(mark) - +def test_add_sequence(dtype): a = pd.array(["a", "b", None, None], dtype=dtype) other = ["x", None, "y", None] diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 1b1cbc8130e4d..2140a2e71eda9 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -1013,6 +1013,10 @@ def _get_scalar_exception(self, opname, pa_dtype): exc = NotImplementedError elif arrow_temporal_supported: exc = None + elif opname in ["__add__", "__radd__"] and ( + pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype) + ): + exc = None elif not (pa.types.is_floating(pa_dtype) or pa.types.is_integer(pa_dtype)): exc = pa.ArrowNotImplementedError else: @@ -1187,9 +1191,7 @@ def test_add_series_with_extension_array(self, data, request): return if (pa_version_under8p0 and pa.types.is_duration(pa_dtype)) or ( - pa.types.is_binary(pa_dtype) - or pa.types.is_string(pa_dtype) - or pa.types.is_boolean(pa_dtype) + pa.types.is_boolean(pa_dtype) ): request.node.add_marker( pytest.mark.xfail( diff --git a/pandas/tests/strings/test_api.py b/pandas/tests/strings/test_api.py index 88d928ceecc43..c439a5f006922 100644 --- a/pandas/tests/strings/test_api.py +++ b/pandas/tests/strings/test_api.py @@ -6,7 +6,6 @@ MultiIndex, Series, _testing as tm, - get_option, ) from pandas.core.strings.accessor import StringMethods @@ -124,16 +123,8 @@ def test_api_per_method( method(*args, **kwargs) -def test_api_for_categorical(any_string_method, any_string_dtype, request): +def test_api_for_categorical(any_string_method, any_string_dtype): # https://github.com/pandas-dev/pandas/issues/10661 - - 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=NotImplementedError, reason="Not Implemented") - request.node.add_marker(mark) - s = Series(list("aabb"), dtype=any_string_dtype) s = s + " " + s c = s.astype("category")
@mroeschke it wouldn't surprise me if you say you prefer to explicitly _not_ support addition this way, but this seems like a pretty big use case, and the _libs.ops functions are a pretty great fit.
https://api.github.com/repos/pandas-dev/pandas/pulls/51338
2023-02-11T23:23:27Z
2023-02-17T22:05:05Z
2023-02-17T22:05:05Z
2023-02-17T22:12:27Z
DOC: fix EX02 errors in docstrings III
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 3ad8a685c8ed3..7f1f216ee36db 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -579,10 +579,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then MSG='Partially validate docstrings (EX02)' ; echo $MSG $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX02 --ignore_functions \ pandas.DataFrame.plot.line \ - pandas.Period.strftime \ - pandas.Series.floordiv \ pandas.Series.plot.line \ - pandas.Series.rfloordiv \ pandas.Series.sparse.density \ pandas.Series.sparse.npoints \ pandas.Series.sparse.sp_values \ diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index bd56773cddb18..b8cb20467a3c0 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -2474,6 +2474,7 @@ cdef class _Period(PeriodMixin): Examples -------- + >>> from pandas import Period >>> a = Period(freq='Q-JUL', year=2006, quarter=1) >>> a.strftime('%F-Q%q') '2006-Q1' diff --git a/pandas/core/ops/docstrings.py b/pandas/core/ops/docstrings.py index cfb3ab5b893c2..cdf1c120719e9 100644 --- a/pandas/core/ops/docstrings.py +++ b/pandas/core/ops/docstrings.py @@ -156,8 +156,8 @@ def make_flex_doc(op_name: str, typ: str) -> str: + """ >>> a.floordiv(b, fill_value=0) a 1.0 -b NaN -c NaN +b inf +c inf d 0.0 e NaN dtype: float64
Related to the issue #51236 This PR enables functions: `pandas.Period.strftime \` `pandas.Series.floordiv \` `pandas.Series.rfloordiv \`
https://api.github.com/repos/pandas-dev/pandas/pulls/51337
2023-02-11T23:20:38Z
2023-02-12T09:06:18Z
2023-02-12T09:06:18Z
2023-02-12T09:06:19Z
ENH: Add lazy copy to where
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 3058603f77e43..7e8ce776801fa 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -227,6 +227,7 @@ Copy-on-Write improvements - :meth:`DataFrame.interpolate` / :meth:`Series.interpolate` - :meth:`DataFrame.ffill` / :meth:`Series.ffill` - :meth:`DataFrame.bfill` / :meth:`Series.bfill` + - :meth:`DataFrame.where` / :meth:`Series.where` - :meth:`DataFrame.infer_objects` / :meth:`Series.infer_objects` - :meth:`DataFrame.astype` / :meth:`Series.astype` - :meth:`DataFrame.convert_dtypes` / :meth:`Series.convert_dtypes` diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index db5cb4a70c8f1..4ad19d015454b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1070,7 +1070,9 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: res_blocks.extend(rbs) return res_blocks - def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: + def where( + self, other, cond, _downcast: str | bool = "infer", using_cow: bool = False + ) -> list[Block]: """ evaluate the block; return result block(s) from the result @@ -1101,6 +1103,8 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: icond, noop = validate_putmask(values, ~cond) if noop: # GH-39595: Always return a copy; short-circuit up/downcasting + if using_cow: + return [self.copy(deep=False)] return [self.copy()] if other is lib.no_default: @@ -1120,8 +1124,10 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: # no need to split columns block = self.coerce_to_target_dtype(other) - blocks = block.where(orig_other, cond) - return self._maybe_downcast(blocks, downcast=_downcast) + blocks = block.where(orig_other, cond, using_cow=using_cow) + return self._maybe_downcast( + blocks, downcast=_downcast, using_cow=using_cow + ) else: # since _maybe_downcast would split blocks anyway, we @@ -1138,7 +1144,9 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: oth = other[:, i : i + 1] submask = cond[:, i : i + 1] - rbs = nb.where(oth, submask, _downcast=_downcast) + rbs = nb.where( + oth, submask, _downcast=_downcast, using_cow=using_cow + ) res_blocks.extend(rbs) return res_blocks @@ -1527,7 +1535,9 @@ def setitem(self, indexer, value, using_cow: bool = False): else: return self - def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: + def where( + self, other, cond, _downcast: str | bool = "infer", using_cow: bool = False + ) -> list[Block]: # _downcast private bc we only specify it when calling from fillna arr = self.values.T @@ -1545,6 +1555,8 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: if noop: # GH#44181, GH#45135 # Avoid a) raising for Interval/PeriodDtype and b) unnecessary object upcast + if using_cow: + return [self.copy(deep=False)] return [self.copy()] try: @@ -1556,15 +1568,19 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: if is_interval_dtype(self.dtype): # TestSetitemFloatIntervalWithIntIntervalValues blk = self.coerce_to_target_dtype(orig_other) - nbs = blk.where(orig_other, orig_cond) - return self._maybe_downcast(nbs, downcast=_downcast) + nbs = blk.where(orig_other, orig_cond, using_cow=using_cow) + return self._maybe_downcast( + nbs, downcast=_downcast, using_cow=using_cow + ) elif isinstance(self, NDArrayBackedExtensionBlock): # NB: not (yet) the same as # isinstance(values, NDArrayBackedExtensionArray) blk = self.coerce_to_target_dtype(orig_other) - nbs = blk.where(orig_other, orig_cond) - return self._maybe_downcast(nbs, downcast=_downcast) + nbs = blk.where(orig_other, orig_cond, using_cow=using_cow) + return self._maybe_downcast( + nbs, downcast=_downcast, using_cow=using_cow + ) else: raise @@ -1582,7 +1598,7 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: n = orig_other[:, i : i + 1] submask = orig_cond[:, i : i + 1] - rbs = nb.where(n, submask) + rbs = nb.where(n, submask, using_cow=using_cow) res_blocks.extend(rbs) return res_blocks diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 9de801b732544..04f731a6b35ac 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -341,6 +341,7 @@ def where(self: T, other, cond, align: bool) -> T: align_keys=align_keys, other=other, cond=cond, + using_cow=using_copy_on_write(), ) def setitem(self: T, indexer, value) -> T: diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 91419ba415fda..0a668ca4bf90e 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1309,6 +1309,54 @@ def test_putmask_dont_copy_some_blocks(using_copy_on_write, val, exp): assert view.iloc[0, 0] == 5 +@pytest.mark.parametrize("dtype", ["int64", "Int64"]) +def test_where_noop(using_copy_on_write, dtype): + ser = Series([1, 2, 3], dtype=dtype) + ser_orig = ser.copy() + + result = ser.where(ser > 0, 10) + + if using_copy_on_write: + assert np.shares_memory(get_array(ser), get_array(result)) + else: + assert not np.shares_memory(get_array(ser), get_array(result)) + + result.iloc[0] = 10 + if using_copy_on_write: + assert not np.shares_memory(get_array(ser), get_array(result)) + tm.assert_series_equal(ser, ser_orig) + + +@pytest.mark.parametrize("dtype", ["int64", "Int64"]) +def test_where(using_copy_on_write, dtype): + ser = Series([1, 2, 3], dtype=dtype) + ser_orig = ser.copy() + + result = ser.where(ser < 0, 10) + + assert not np.shares_memory(get_array(ser), get_array(result)) + tm.assert_series_equal(ser, ser_orig) + + +@pytest.mark.parametrize("dtype, val", [("int64", 10.5), ("Int64", 10)]) +def test_where_noop_on_single_column(using_copy_on_write, dtype, val): + df = DataFrame({"a": [1, 2, 3], "b": [-4, -5, -6]}, dtype=dtype) + df_orig = df.copy() + + result = df.where(df < 0, val) + + if using_copy_on_write: + assert np.shares_memory(get_array(df, "b"), get_array(result, "b")) + assert not np.shares_memory(get_array(df, "a"), get_array(result, "a")) + else: + assert not np.shares_memory(get_array(df, "b"), get_array(result, "b")) + + result.iloc[0, 1] = 10 + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "b"), get_array(result, "b")) + tm.assert_frame_equal(df, df_orig) + + def test_asfreq_noop(using_copy_on_write): df = DataFrame( {"a": [0.0, None, 2.0, 3.0]}, diff --git a/pandas/tests/copy_view/util.py b/pandas/tests/copy_view/util.py index ba9b0ecdebb58..1c6b5b51fa265 100644 --- a/pandas/tests/copy_view/util.py +++ b/pandas/tests/copy_view/util.py @@ -11,7 +11,10 @@ def get_array(obj, col=None): this is done by some other operation). """ if isinstance(obj, Series) and (col is None or obj.name == col): - return obj._values + arr = obj._values + if isinstance(arr, BaseMaskedArray): + return arr._data + return arr assert col is not None icol = obj.columns.get_loc(col) assert isinstance(icol, int)
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51336
2023-02-11T22:06:11Z
2023-02-15T21:27:15Z
2023-02-15T21:27:15Z
2023-02-15T21:27:53Z
BUG: DataFrame reductions dtypes on object input
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 78422ec686da8..2362293b4a2ae 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -814,7 +814,7 @@ Other API changes - The levels of the index of the :class:`Series` returned from ``Series.sparse.from_coo`` now always have dtype ``int32``. Previously they had dtype ``int64`` (:issue:`50926`) - :func:`to_datetime` with ``unit`` of either "Y" or "M" will now raise if a sequence contains a non-round ``float`` value, matching the ``Timestamp`` behavior (:issue:`50301`) - The methods :meth:`Series.round`, :meth:`DataFrame.__invert__`, :meth:`Series.__invert__`, :meth:`DataFrame.swapaxes`, :meth:`DataFrame.first`, :meth:`DataFrame.last`, :meth:`Series.first`, :meth:`Series.last` and :meth:`DataFrame.align` will now always return new objects (:issue:`51032`) -- :class:`DataFrameGroupBy` aggregations (e.g. "sum") with object-dtype columns no longer infer non-object dtypes for their results, explicitly call ``result.infer_objects(copy=False)`` on the result to obtain the old behavior (:issue:`51205`) +- :class:`DataFrame` and :class:`DataFrameGroupBy` aggregations (e.g. "sum") with object-dtype columns no longer infer non-object dtypes for their results, explicitly call ``result.infer_objects(copy=False)`` on the result to obtain the old behavior (:issue:`51205`, :issue:`49603`) - Added :func:`pandas.api.types.is_any_real_numeric_dtype` to check for real numeric dtypes (:issue:`51152`) - @@ -1226,10 +1226,10 @@ Numeric ^^^^^^^ - Bug in :meth:`DataFrame.add` cannot apply ufunc when inputs contain mixed DataFrame type and Series type (:issue:`39853`) - Bug in arithmetic operations on :class:`Series` not propagating mask when combining masked dtypes and numpy dtypes (:issue:`45810`, :issue:`42630`) -- Bug in DataFrame reduction methods (e.g. :meth:`DataFrame.sum`) with object dtype, ``axis=1`` and ``numeric_only=False`` would not be coerced to float (:issue:`49551`) - Bug in :meth:`DataFrame.sem` and :meth:`Series.sem` where an erroneous ``TypeError`` would always raise when using data backed by an :class:`ArrowDtype` (:issue:`49759`) - Bug in :meth:`Series.__add__` casting to object for list and masked :class:`Series` (:issue:`22962`) - Bug in :meth:`DataFrame.query` with ``engine="numexpr"`` and column names are ``min`` or ``max`` would raise a ``TypeError`` (:issue:`50937`) +- Bug in :meth:`DataFrame.min` and :meth:`DataFrame.max` with tz-aware data containing ``pd.NaT`` and ``axis=1`` would return incorrect results (:issue:`51242`) Conversion ^^^^^^^^^^ diff --git a/pandas/conftest.py b/pandas/conftest.py index 50951532364d1..773da503ddb2b 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -293,6 +293,14 @@ def ordered(request): return request.param +@pytest.fixture(params=[True, False]) +def skipna(request): + """ + Boolean 'skipna' parameter. + """ + return request.param + + @pytest.fixture(params=["first", "last", False]) def keep(request): """ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c7d9c798aa7e6..a7c504366f118 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -141,7 +141,6 @@ is_integer_dtype, is_iterator, is_list_like, - is_object_dtype, is_scalar, is_sequence, needs_i8_conversion, @@ -10459,54 +10458,44 @@ def _get_data() -> DataFrame: data = self._get_bool_data() return data - if numeric_only or axis == 0: - # For numeric_only non-None and axis non-None, we know - # which blocks to use and no try/except is needed. - # For numeric_only=None only the case with axis==0 and no object - # dtypes are unambiguous can be handled with BlockManager.reduce - # Case with EAs see GH#35881 - df = self - if numeric_only: - df = _get_data() - if axis == 1: - df = df.T - axis = 0 - - # After possibly _get_data and transposing, we are now in the - # simple case where we can use BlockManager.reduce - res = df._mgr.reduce(blk_func) - out = df._constructor(res).iloc[0] - if out_dtype is not None: - out = out.astype(out_dtype) - if axis == 0 and len(self) == 0 and name in ["sum", "prod"]: - # Even if we are object dtype, follow numpy and return - # float64, see test_apply_funcs_over_empty - out = out.astype(np.float64) - - return out - - assert not numeric_only and axis in (1, None) - - data = self - values = data.values - result = func(values) - - if hasattr(result, "dtype"): - if filter_type == "bool" and notna(result).all(): - result = result.astype(np.bool_) - elif filter_type is None and is_object_dtype(result.dtype): - try: - result = result.astype(np.float64) - except (ValueError, TypeError): - # try to coerce to the original dtypes item by item if we can - pass - + # Case with EAs see GH#35881 + df = self + if numeric_only: + df = _get_data() if axis is None: - return result + return func(df.values) + elif axis == 1: + if len(df.index) == 0: + # Taking a transpose would result in no columns, losing the dtype. + # In the empty case, reducing along axis 0 or 1 gives the same + # result dtype, so reduce with axis=0 and ignore values + result = df._reduce( + op, + name, + axis=0, + skipna=skipna, + numeric_only=False, + filter_type=filter_type, + **kwds, + ).iloc[:0] + result.index = df.index + return result + df = df.T + + # After possibly _get_data and transposing, we are now in the + # simple case where we can use BlockManager.reduce + res = df._mgr.reduce(blk_func) + out = df._constructor(res).iloc[0] + if out_dtype is not None: + out = out.astype(out_dtype) + elif (df._mgr.get_dtypes() == object).any(): + out = out.astype(object) + elif len(self) == 0 and name in ("sum", "prod"): + # Even if we are object dtype, follow numpy and return + # float64, see test_apply_funcs_over_empty + out = out.astype(np.float64) - labels = self._get_agg_axis(axis) - result = self._constructor_sliced(result, index=labels) - return result + return out def _reduce_axis1(self, name: str, func, skipna: bool) -> Series: """ diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 3c3ff2f313186..1e3d88d42ef9b 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -984,14 +984,10 @@ def reduce(self: T, func: Callable) -> T: # TODO NaT doesn't preserve dtype, so we need to ensure to create # a timedelta result array if original was timedelta # what if datetime results in timedelta? (eg std) - if res is NaT and is_timedelta64_ns_dtype(arr.dtype): - result_arrays.append(np.array(["NaT"], dtype="timedelta64[ns]")) - else: - # error: Argument 1 to "append" of "list" has incompatible type - # "ExtensionArray"; expected "ndarray" - result_arrays.append( - sanitize_array([res], None) # type: ignore[arg-type] - ) + dtype = arr.dtype if res is NaT else None + result_arrays.append( + sanitize_array([res], None, dtype=dtype) # type: ignore[arg-type] + ) index = Index._simple_new(np.array([None], dtype=object)) # placeholder columns = self.items diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 41ed9485643e7..60c0d04ef28b0 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -1535,7 +1535,12 @@ def _maybe_null_out( result[null_mask] = None elif result is not NaT: if check_below_min_count(shape, mask, min_count): - result = np.nan + result_dtype = getattr(result, "dtype", None) + if is_float_dtype(result_dtype): + # error: Item "None" of "Optional[Any]" has no attribute "type" + result = result_dtype.type("nan") # type: ignore[union-attr] + else: + result = np.nan return result diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index e0be8f3e7ce04..6ed3f6140d361 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -135,6 +135,8 @@ def test_apply_funcs_over_empty(func): result = df.apply(getattr(np, func)) expected = getattr(df, func)() + if func in ("sum", "prod"): + expected = expected.astype(float) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index eaa789a5d3e67..28809e2ecb788 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -317,11 +317,11 @@ def wrapper(x): DataFrame({0: [np.nan, 2], 1: [np.nan, 3], 2: [np.nan, 4]}, dtype=object), ], ) - def test_stat_operators_attempt_obj_array(self, method, df): + def test_stat_operators_attempt_obj_array(self, method, df, axis): # GH#676 assert df.values.dtype == np.object_ - result = getattr(df, method)(1) - expected = getattr(df.astype("f8"), method)(1) + result = getattr(df, method)(axis=axis) + expected = getattr(df.astype("f8"), method)(axis=axis).astype(object) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("op", ["mean", "std", "var", "skew", "kurt", "sem"]) @@ -424,7 +424,7 @@ def test_mean_mixed_string_decimal(self): with pytest.raises(TypeError, match="unsupported operand type"): df.mean() result = df[["A", "C"]].mean() - expected = Series([2.7, 681.6], index=["A", "C"]) + expected = Series([2.7, 681.6], index=["A", "C"], dtype=object) tm.assert_series_equal(result, expected) def test_var_std(self, datetime_frame): @@ -687,6 +687,29 @@ def test_std_timedelta64_skipna_false(self): expected = Series([pd.Timedelta(0)] * 8 + [pd.NaT, pd.Timedelta(0)]) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( + "values", [["2022-01-01", "2022-01-02", pd.NaT, "2022-01-03"], 4 * [pd.NaT]] + ) + def test_std_datetime64_with_nat( + self, values, skipna, using_array_manager, request + ): + # GH#51335 + if using_array_manager and ( + not skipna or all(value is pd.NaT for value in values) + ): + mark = pytest.mark.xfail( + reason="GH#51446: Incorrect type inference on NaT in reduction result" + ) + request.node.add_marker(mark) + df = DataFrame({"a": to_datetime(values)}) + result = df.std(skipna=skipna) + if not skipna or all(value is pd.NaT for value in values): + expected = Series({"a": pd.NaT}, dtype="timedelta64[ns]") + else: + # 86400000000000ns == 1 day + expected = Series({"a": 86400000000000}, dtype="timedelta64[ns]") + tm.assert_series_equal(result, expected) + def test_sum_corner(self): empty_frame = DataFrame() @@ -697,6 +720,29 @@ def test_sum_corner(self): assert len(axis0) == 0 assert len(axis1) == 0 + @pytest.mark.parametrize( + "index", + [ + tm.makeRangeIndex(0), + tm.makeDateIndex(0), + tm.makeNumericIndex(0, dtype=int), + tm.makeNumericIndex(0, dtype=float), + tm.makeDateIndex(0, freq="M"), + tm.makePeriodIndex(0), + ], + ) + def test_axis_1_empty(self, all_reductions, index, using_array_manager): + df = DataFrame(columns=["a"], index=index) + result = getattr(df, all_reductions)(axis=1) + if all_reductions in ("any", "all"): + expected_dtype = "bool" + elif all_reductions == "count": + expected_dtype = "int64" + else: + expected_dtype = "object" + expected = Series([], index=index, dtype=expected_dtype) + tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("method, unit", [("sum", 0), ("prod", 1)]) @pytest.mark.parametrize("numeric_only", [None, True, False]) def test_sum_prod_nanops(self, method, unit, numeric_only): @@ -1418,6 +1464,21 @@ def test_preserve_timezone(self, initial: str, method): result = getattr(df, method)(axis=1) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("method", ["min", "max"]) + def test_minmax_tzaware_skipna_axis_1(self, method, skipna): + # GH#51242 + val = to_datetime("1900-01-01", utc=True) + df = DataFrame( + {"a": Series([pd.NaT, pd.NaT, val]), "b": Series([pd.NaT, val, val])} + ) + op = getattr(df, method) + result = op(axis=1, skipna=skipna) + if skipna: + expected = Series([pd.NaT, val, val]) + else: + expected = Series([pd.NaT, pd.NaT, val]) + tm.assert_series_equal(result, expected) + def test_frame_any_with_timedelta(self): # GH#17667 df = DataFrame( @@ -1609,12 +1670,13 @@ def test_prod_sum_min_count_mixed_object(): @pytest.mark.parametrize("method", ["min", "max", "mean", "median", "skew", "kurt"]) -def test_reduction_axis_none_returns_scalar(method): +@pytest.mark.parametrize("numeric_only", [True, False]) +def test_reduction_axis_none_returns_scalar(method, numeric_only): # GH#21597 As of 2.0, axis=None reduces over all axes. df = DataFrame(np.random.randn(4, 4)) - result = getattr(df, method)(axis=None) + result = getattr(df, method)(axis=None, numeric_only=numeric_only) np_arr = df.to_numpy() if method in {"skew", "kurt"}: comp_mod = pytest.importorskip("scipy.stats") diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index 909ae22410d73..ba21ea4e7db95 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -21,14 +21,6 @@ use_bn = nanops._USE_BOTTLENECK -@pytest.fixture(params=[True, False]) -def skipna(request): - """ - Fixture to pass skipna to nanops functions. - """ - return request.param - - @pytest.fixture def disable_bottleneck(monkeypatch): with monkeypatch.context() as m:
- [x] closes #49603 (Replace xxxx with the GitHub issue number) - [x] closes #51242 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51335
2023-02-11T21:27:39Z
2023-02-18T01:14:54Z
2023-02-18T01:14:54Z
2023-03-13T04:28:29Z
BUG: DatetimeArray+DateOffset result unit
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 31aff5d4ebb41..ab9e12dc5de81 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -774,7 +774,7 @@ def _add_offset(self, offset) -> DatetimeArray: stacklevel=find_stack_level(), ) result = self.astype("O") + offset - result = type(self)._from_sequence(result) + result = type(self)._from_sequence(result).as_unit(self.unit) if not len(self): # GH#30336 _from_sequence won't be able to infer self.tz return result.tz_localize(self.tz) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 933723edd6e66..57a783d601a50 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -12,7 +12,6 @@ List, Tuple, ) -import warnings import numpy as np import pytest @@ -566,6 +565,9 @@ def test_offsets_hashable(self, offset_types): off = _create_offset(offset_types) assert hash(off) is not None + @pytest.mark.filterwarnings( + "ignore:Non-vectorized DateOffset being applied to Series or DatetimeIndex" + ) @pytest.mark.parametrize("unit", ["s", "ms", "us"]) def test_add_dt64_ndarray_non_nano(self, offset_types, unit, request): # check that the result with non-nano matches nano @@ -576,9 +578,8 @@ def test_add_dt64_ndarray_non_nano(self, offset_types, unit, request): arr = dti._data._ndarray.astype(f"M8[{unit}]") dta = type(dti._data)._simple_new(arr, dtype=arr.dtype) - with warnings.catch_warnings(record=True) as w: - expected = dti._data + off - result = dta + off + expected = dti._data + off + result = dta + off exp_unit = unit if isinstance(off, Tick) and off._creso > dta._creso: @@ -586,16 +587,6 @@ def test_add_dt64_ndarray_non_nano(self, offset_types, unit, request): exp_unit = Timedelta(off).unit expected = expected.as_unit(exp_unit) - if len(w): - # PerformanceWarning was issued bc _apply_array raised, so we - # fell back to object dtype, for which the code path does - # not yet cast back to the original resolution - mark = pytest.mark.xfail( - reason="Goes through object dtype in DatetimeArray._add_offset, " - "doesn't restore reso in result" - ) - request.node.add_marker(mark) - tm.assert_numpy_array_equal(result._ndarray, expected._ndarray)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51334
2023-02-11T21:09:01Z
2023-02-13T18:20:54Z
2023-02-13T18:20:54Z
2023-02-13T18:45:15Z
ENH: support td64/dt64 in GroupBy.std
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 778169b0dbeb4..aeb9d476a0a87 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -284,6 +284,7 @@ Other enhancements - Added support for ``dt`` accessor methods when using :class:`ArrowDtype` with a ``pyarrow.timestamp`` type (:issue:`50954`) - :func:`read_sas` now supports using ``encoding='infer'`` to correctly read and use the encoding specified by the sas file. (:issue:`48048`) - :meth:`.DataFrameGroupBy.quantile`, :meth:`.SeriesGroupBy.quantile` and :meth:`.DataFrameGroupBy.std` now preserve nullable dtypes instead of casting to numpy dtypes (:issue:`37493`) +- :meth:`.DataFrameGroupBy.std`, :meth:`.SeriesGroupBy.std` now support datetime64, timedelta64, and :class:`DatetimeTZDtype` dtypes (:issue:`48481`) - :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support an ``axis`` argument. If ``axis`` is set, the default behaviour of which axis to consider can be overwritten (:issue:`47819`) - :func:`.testing.assert_frame_equal` now shows the first element where the DataFrames differ, analogously to ``pytest``'s output (:issue:`47910`) - Added ``index`` parameter to :meth:`DataFrame.to_dict` (:issue:`46398`) diff --git a/pandas/_libs/groupby.pyi b/pandas/_libs/groupby.pyi index 09f4fbec5176e..e3ca9c44d5664 100644 --- a/pandas/_libs/groupby.pyi +++ b/pandas/_libs/groupby.pyi @@ -85,6 +85,7 @@ def group_var( ddof: int = ..., # int64_t mask: np.ndarray | None = ..., result_mask: np.ndarray | None = ..., + is_datetimelike: bool = ..., ) -> None: ... def group_mean( out: np.ndarray, # floating[:, ::1] diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index dd2bdadce31c5..0c378acbc6dc3 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -818,6 +818,7 @@ def group_var( int64_t ddof=1, const uint8_t[:, ::1] mask=None, uint8_t[:, ::1] result_mask=None, + bint is_datetimelike=False, ) -> None: cdef: Py_ssize_t i, j, N, K, lab, ncounts = len(counts) @@ -852,8 +853,13 @@ def group_var( if uses_mask: isna_entry = mask[i, j] + elif is_datetimelike: + # With group_var, we cannot just use _treat_as_na bc + # datetimelike dtypes get cast to float64 instead of + # to int64. + isna_entry = val == NPY_NAT else: - isna_entry = _treat_as_na(val, False) + isna_entry = _treat_as_na(val, is_datetimelike) if not isna_entry: nobs[lab, j] += 1 diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index e42566bfa11a0..810bf27ebf788 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -30,6 +30,7 @@ class providing the base-class of operations. cast, final, ) +import warnings import numpy as np @@ -97,8 +98,10 @@ class providing the base-class of operations. BaseMaskedArray, BooleanArray, Categorical, + DatetimeArray, ExtensionArray, FloatingArray, + TimedeltaArray, ) from pandas.core.base import ( PandasObject, @@ -3724,7 +3727,10 @@ def blk_func(values: ArrayLike) -> ArrayLike: counts = np.zeros(ngroups, dtype=np.int64) func = partial(func, counts=counts) + is_datetimelike = values.dtype.kind in ["m", "M"] vals = values + if is_datetimelike and how == "std": + vals = vals.view("i8") if pre_processing: vals, inferences = pre_processing(vals) @@ -3747,7 +3753,11 @@ def blk_func(values: ArrayLike) -> ArrayLike: result_mask = np.zeros(result.shape, dtype=np.bool_) func = partial(func, result_mask=result_mask) - func(**kwargs) # Call func to modify result in place + # Call func to modify result in place + if how == "std": + func(**kwargs, is_datetimelike=is_datetimelike) + else: + func(**kwargs) if values.ndim == 1: assert result.shape[1] == 1, result.shape @@ -3761,6 +3771,15 @@ def blk_func(values: ArrayLike) -> ArrayLike: result = post_processing(result, inferences, **pp_kwargs) + if how == "std" and is_datetimelike: + values = cast("DatetimeArray | TimedeltaArray", values) + unit = values.unit + with warnings.catch_warnings(): + # suppress "RuntimeWarning: invalid value encountered in cast" + warnings.filterwarnings("ignore") + result = result.astype(np.int64, copy=False) + result = result.view(f"m8[{unit}]") + return result.T # Operate block-wise instead of column-by-column diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index e175f6dda980f..a0b129b65d293 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -37,6 +37,33 @@ def test_repr(): assert result == expected +def test_groupby_std_datetimelike(): + # GH#48481 + tdi = pd.timedelta_range("1 Day", periods=10000) + ser = Series(tdi) + ser[::5] *= 2 # get different std for different groups + + df = ser.to_frame("A") + + df["B"] = ser + Timestamp(0) + df["C"] = ser + Timestamp(0, tz="UTC") + df.iloc[-1] = pd.NaT # last group includes NaTs + + gb = df.groupby(list(range(5)) * 2000) + + result = gb.std() + + # Note: this does not _exactly_ match what we would get if we did + # [gb.get_group(i).std() for i in gb.groups] + # but it _does_ match the floating point error we get doing the + # same operation on int64 data xref GH#51332 + td1 = Timedelta("2887 days 11:21:02.326710176") + td4 = Timedelta("2886 days 00:42:34.664668096") + exp_ser = Series([td1 * 2, td1, td1, td1, td4], index=np.arange(5)) + expected = DataFrame({"A": exp_ser, "B": exp_ser, "C": exp_ser}) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("dtype", ["int64", "int32", "float64", "float32"]) def test_basic(dtype): diff --git a/pandas/tests/groupby/test_raises.py b/pandas/tests/groupby/test_raises.py index 6ceb23a3c44b6..76ba4c974b3fd 100644 --- a/pandas/tests/groupby/test_raises.py +++ b/pandas/tests/groupby/test_raises.py @@ -224,11 +224,11 @@ def test_groupby_raises_datetime(how, by, groupby_series, groupby_func): "prod": (TypeError, "datetime64 type does not support prod"), "quantile": (None, ""), "rank": (None, ""), - "sem": (TypeError, "Cannot cast DatetimeArray to dtype float64"), + "sem": (None, ""), "shift": (None, ""), "size": (None, ""), "skew": (TypeError, r"dtype datetime64\[ns\] does not support reduction"), - "std": (TypeError, "Cannot cast DatetimeArray to dtype float64"), + "std": (None, ""), "sum": (TypeError, "datetime64 type does not support sum operations"), "var": (None, ""), }[groupby_func] diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 0b8dc8f3e8ac4..1e54a4c03f4fc 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -405,12 +405,16 @@ def test_agg(): expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]]) for t in cases: - # In case 2, "date" is an index and a column, so agg still tries to agg + # In case 2, "date" is an index and a column, so get included in the agg if t == cases[2]: - # .var on dt64 column raises - msg = "Cannot cast DatetimeArray to dtype float64" - with pytest.raises(TypeError, match=msg): - t.aggregate([np.mean, np.std]) + date_mean = t["date"].mean() + date_std = t["date"].std() + exp = pd.concat([date_mean, date_std, expected], axis=1) + exp.columns = pd.MultiIndex.from_product( + [["date", "A", "B"], ["mean", "std"]] + ) + result = t.aggregate([np.mean, np.std]) + tm.assert_frame_equal(result, exp) else: result = t.aggregate([np.mean, np.std]) tm.assert_frame_equal(result, expected)
- [x] closes #48481 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51333
2023-02-11T21:08:16Z
2023-02-13T18:37:19Z
2023-02-13T18:37:19Z
2023-02-13T18:43:40Z
BUG : Add Deprecation FutureWarning for parse function call
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 29f360e050548..39c3916a6c63b 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1304,6 +1304,7 @@ I/O - Bug in :meth:`DataFrame.to_dict` not converting ``NA`` to ``None`` (:issue:`50795`) - Bug in :meth:`DataFrame.to_json` where it would segfault when failing to encode a string (:issue:`50307`) - Bug in :func:`read_xml` where file-like objects failed when iterparse is used (:issue:`50641`) +- Bug in :func:`read_excel` where passing invalid argument name ``headers`` to :meth:`parse` doesn't raise error (:issue:`50953`) Period ^^^^^^ diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 79d174db5c0a7..6e9723a4823dc 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -21,6 +21,7 @@ cast, overload, ) +import warnings import zipfile from pandas._config import ( @@ -47,6 +48,7 @@ Appender, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_bool, @@ -1553,11 +1555,49 @@ def parse( Equivalent to read_excel(ExcelFile, ...) See the read_excel docstring for more info on accepted parameters. + .. deprecated:: 2.0.0 + Arguments other than sheet_name by position may not work. + Returns ------- DataFrame or dict of DataFrames DataFrame from the passed in Excel file. """ + arguments = list(kwds.keys()) + allowed_kwargs = [ + "sheet_name", + "header", + "names", + "index_col", + "usecols", + "squeeze", + "dtype", + "engine", + "converters", + "true_values", + "false_values", + "skiprows", + "nrows", + "na_values", + "keep_default_na", + "na_filter", + "verbose", + "parse_dates", + "date_parser", + "thousands", + "decimal", + "comment", + "skipfooter", + "convert_float", + ] + # Check for any invalid kwargs + if [argument for argument in arguments if argument not in allowed_kwargs]: + warnings.warn( + f"{type(self).__name__}.parse is deprecated. " + "Arguments other than sheet_name by position may not work.", + FutureWarning, + stacklevel=find_stack_level(), + ) return self._reader.parse( sheet_name=sheet_name, header=header, diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 3f2fecbfb48a6..df5d59e0c70f8 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1684,3 +1684,11 @@ def test_corrupt_files_closed(self, engine, read_ext): pd.ExcelFile(file, engine=engine) except errors: pass + + def test_read_excel_parse_warning(self, read_ext): + # GH50953 + msg = "Arguments other than sheet_name by position may not work." + with tm.assert_produces_warning(FutureWarning, match=msg): + with pd.ExcelFile("test1" + read_ext) as excel: + excel.parse("Sheet1", headers=[0, 1, 2]) + # invalid argument 'headers' should give warning for deprecation
- [ ] closes #50953 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51331
2023-02-11T19:57:02Z
2023-02-14T03:30:07Z
null
2023-02-14T22:53:26Z
DOC: fix EX02 errors in docstrings
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 2fa023500731e..975f95d4a25dc 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -591,9 +591,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.api.types.is_datetime64_ns_dtype \ pandas.api.types.is_datetime64tz_dtype \ pandas.api.types.is_integer_dtype \ - pandas.api.types.is_interval_dtype \ - pandas.api.types.is_period_dtype \ - pandas.api.types.is_signed_integer_dtype \ pandas.api.types.is_sparse \ pandas.api.types.is_string_dtype \ pandas.api.types.is_timedelta64_dtype \ diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 3444ad77c2981..4512bf0cedfbc 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -397,6 +397,7 @@ def is_period_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_period_dtype >>> is_period_dtype(object) False >>> is_period_dtype(PeriodDtype(freq="D")) @@ -433,6 +434,7 @@ def is_interval_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_interval_dtype >>> is_interval_dtype(object) False >>> is_interval_dtype(IntervalDtype()) @@ -727,6 +729,7 @@ def is_signed_integer_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_signed_integer_dtype >>> is_signed_integer_dtype(str) False >>> is_signed_integer_dtype(int)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Towards #51236. Fixed EX02 for: pandas.api.types.is_interval_dtype pandas.api.types.is_period_dtype pandas.api.types.is_signed_integer_dtype
https://api.github.com/repos/pandas-dev/pandas/pulls/51330
2023-02-11T19:14:45Z
2023-02-21T19:40:03Z
null
2023-02-21T19:40:03Z
DOC remove outdated instructions to delete branch
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index d0bda0ba42bd7..c0e8aa6ba903e 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -331,29 +331,6 @@ To automatically fix formatting errors on each commit you make, you can set up pre-commit yourself. First, create a Python :ref:`environment <contributing_environment>` and then set up :ref:`pre-commit <contributing.pre-commit>`. -Delete your merged branch (optional) ------------------------------------- - -Once your feature branch is accepted into upstream, you'll probably want to get rid of -the branch. First, merge upstream main into your branch so git knows it is safe to -delete your branch:: - - git fetch upstream - git checkout main - git merge upstream/main - -Then you can do:: - - git branch -d shiny-new-feature - -Make sure you use a lower-case ``-d``, or else git won't warn you if your feature -branch has not actually been merged. - -The branch will still exist on GitHub, so to delete it there do:: - - git push origin --delete shiny-new-feature - - Tips for a successful pull request ==================================
since we squash and merge, the recommended workflow here doesn't actually work I don't think it adds any value to contributors, I'd suggest removing it
https://api.github.com/repos/pandas-dev/pandas/pulls/51329
2023-02-11T19:06:10Z
2023-02-14T11:25:39Z
2023-02-14T11:25:39Z
2023-02-14T11:25:47Z
DOC: clarify "inplace"-ness of DataFrame.setitem
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 33d503f3dd4cb..59ebf9f55e558 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3869,23 +3869,27 @@ def _get_value(self, index, col, takeable: bool = False) -> Scalar: def isetitem(self, loc, value) -> None: """ - Set the given value in the column with position 'loc'. + Set the given value in the column with position `loc`. - This is a positional analogue to __setitem__. + This is a positional analogue to ``__setitem__``. Parameters ---------- loc : int or sequence of ints + Index position for the column. value : scalar or arraylike + Value(s) for the column. Notes ----- - Unlike `frame.iloc[:, i] = value`, `frame.isetitem(loc, value)` will - _never_ try to set the values in place, but will always insert a new - array. - - In cases where `frame.columns` is unique, this is equivalent to - `frame[frame.columns[i]] = value`. + ``frame.isetitem(loc, value)`` is an in-place method as it will + modify the DataFrame in place (not returning a new object). In contrast to + ``frame.iloc[:, i] = value`` which will try to update the existing values in + place, ``frame.isetitem(loc, value)`` will not update the values of the column + itself in place, it will instead insert a new array. + + In cases where ``frame.columns`` is unique, this is equivalent to + ``frame[frame.columns[i]] = value``. """ if isinstance(value, DataFrame): if is_scalar(loc):
- [x] closes #51300 - [NA] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [X] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [NA] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [NA] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51328
2023-02-11T17:51:46Z
2023-02-20T21:37:10Z
2023-02-20T21:37:10Z
2023-02-20T21:37:19Z
ENH: Avoid copy when possible in merge
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2650090a3f61a..b55867b432a78 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9809,7 +9809,7 @@ def merge( right_index: bool = False, sort: bool = False, suffixes: Suffixes = ("_x", "_y"), - copy: bool = True, + copy: bool | None = None, indicator: str | bool = False, validate: str | None = None, ) -> DataFrame: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 37013a5d1fb8f..0413fc865f641 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -25,6 +25,7 @@ join as libjoin, lib, ) +from pandas._libs.lib import is_range_indexer from pandas._typing import ( AnyArrayLike, ArrayLike, @@ -757,7 +758,7 @@ def _reindex_and_concat( self.left._info_axis, self.right._info_axis, self.suffixes ) - if left_indexer is not None: + if left_indexer is not None and not is_range_indexer(left_indexer, len(left)): # Pinning the index here (and in the right code just below) is not # necessary, but makes the `.take` more performant if we have e.g. # a MultiIndex for left.index. @@ -773,7 +774,9 @@ def _reindex_and_concat( left = left._constructor(lmgr) left.index = join_index - if right_indexer is not None: + if right_indexer is not None and not is_range_indexer( + right_indexer, len(right) + ): rmgr = right._mgr.reindex_indexer( join_index, right_indexer, diff --git a/pandas/tests/copy_view/test_functions.py b/pandas/tests/copy_view/test_functions.py index ffc80d2d11798..b6f2f0543cb2b 100644 --- a/pandas/tests/copy_view/test_functions.py +++ b/pandas/tests/copy_view/test_functions.py @@ -1,6 +1,5 @@ import numpy as np - -import pandas.util._test_decorators as td +import pytest from pandas import ( DataFrame, @@ -182,19 +181,25 @@ def test_concat_mixed_series_frame(using_copy_on_write): tm.assert_frame_equal(result, expected) -@td.skip_copy_on_write_not_yet_implemented # TODO(CoW) -def test_merge_on_key(using_copy_on_write): +@pytest.mark.parametrize( + "func", + [ + lambda df1, df2, **kwargs: df1.merge(df2, **kwargs), + lambda df1, df2, **kwargs: merge(df1, df2, **kwargs), + ], +) +def test_merge_on_key(using_copy_on_write, func): df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]}) df2 = DataFrame({"key": ["a", "b", "c"], "b": [4, 5, 6]}) df1_orig = df1.copy() df2_orig = df2.copy() - result = merge(df1, df2, on="key") + result = func(df1, df2, on="key") if using_copy_on_write: assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) - assert not np.shares_memory(get_array(result, "key"), get_array(df1, "key")) + assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) else: assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) @@ -239,4 +244,39 @@ def test_merge_on_index(using_copy_on_write): tm.assert_frame_equal(df2, df2_orig) -# TODO(CoW) add merge tests where one of left/right isn't copied +@pytest.mark.parametrize( + "func, how", + [ + (lambda df1, df2, **kwargs: merge(df2, df1, on="key", **kwargs), "right"), + (lambda df1, df2, **kwargs: merge(df1, df2, on="key", **kwargs), "left"), + ], +) +def test_merge_on_key_enlarging_one(using_copy_on_write, func, how): + df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]}) + df2 = DataFrame({"key": ["a", "b"], "b": [4, 5]}) + df1_orig = df1.copy() + df2_orig = df2.copy() + + result = func(df1, df2, how=how) + + if using_copy_on_write: + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert df2._mgr._has_no_reference(1) + assert df2._mgr._has_no_reference(0) + assert np.shares_memory(get_array(result, "key"), get_array(df1, "key")) is ( + how == "left" + ) + assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) + else: + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + + if how == "left": + result.iloc[0, 1] = 0 + else: + result.iloc[0, 2] = 0 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + tm.assert_frame_equal(df1, df1_orig) + tm.assert_frame_equal(df2, df2_orig)
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Technically this would change the behavior for the non CoW case with copy=False as well
https://api.github.com/repos/pandas-dev/pandas/pulls/51327
2023-02-11T17:11:56Z
2023-02-14T20:41:57Z
2023-02-14T20:41:56Z
2023-02-14T20:53:34Z
BLD: Fix regex in arm64 wheel builders
diff --git a/.circleci/config.yml b/.circleci/config.yml index 772a1c8821dcf..5f25c891acf8a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -39,7 +39,8 @@ jobs: elif [[ $TRIGGER_SOURCE == "scheduled_pipeline" ]]; then export IS_SCHEDULE_DISPATCH="true" # Look for the build label/[wheel build] in commit - elif (git log --format=oneline -n 1 $CIRCLE_SHA1) | grep -q '[wheel build]'; then + # grep takes a regex, so need to escape brackets + elif (git log --format=oneline -n 1 $CIRCLE_SHA1) | grep -q '\[wheel build\]'; then : # Do nothing elif ! (curl https://api.github.com/repos/pandas-dev/pandas/issues/$CIRCLE_PR_NUMBER | jq '.labels' | grep -q 'Build'); then circleci-agent step halt
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51326
2023-02-11T12:56:39Z
2023-02-11T20:48:49Z
2023-02-11T20:48:49Z
2023-02-11T21:12:15Z
TYP: Fix missed copy annotations in concat
diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 0de995d2f773f..a36352e83ff3e 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -73,7 +73,7 @@ def concat( names=..., verify_integrity: bool = ..., sort: bool = ..., - copy: bool = ..., + copy: bool | None = ..., ) -> DataFrame: ... @@ -90,7 +90,7 @@ def concat( names=..., verify_integrity: bool = ..., sort: bool = ..., - copy: bool = ..., + copy: bool | None = ..., ) -> Series: ... @@ -107,7 +107,7 @@ def concat( names=..., verify_integrity: bool = ..., sort: bool = ..., - copy: bool = ..., + copy: bool | None = ..., ) -> DataFrame | Series: ... @@ -124,7 +124,7 @@ def concat( names=..., verify_integrity: bool = ..., sort: bool = ..., - copy: bool = ..., + copy: bool | None = ..., ) -> DataFrame: ... @@ -141,7 +141,7 @@ def concat( names=..., verify_integrity: bool = ..., sort: bool = ..., - copy: bool = ..., + copy: bool | None = ..., ) -> DataFrame | Series: ...
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51325
2023-02-11T11:43:27Z
2023-02-11T13:30:26Z
2023-02-11T13:30:26Z
2023-02-11T13:30:45Z
TST: Add test for set_index not mutating index when parent is mutated
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index d822cc03c499d..37ca3733d7908 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -648,6 +648,15 @@ def test_set_index(using_copy_on_write): tm.assert_frame_equal(df, df_orig) +def test_set_index_mutating_parent_does_not_mutate_index(): + df = DataFrame({"a": [1, 2, 3], "b": 1}) + result = df.set_index("a") + expected = result.copy() + + df.iloc[0, 0] = 100 + tm.assert_frame_equal(result, expected) + + def test_add_prefix(using_copy_on_write): # GH 49473 df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]})
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51324
2023-02-11T11:32:47Z
2023-02-14T20:36:29Z
2023-02-14T20:36:29Z
2023-02-14T20:53:06Z
DOC: fix EX02 errors in docstrings II
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 3ad8a685c8ed3..82802d717b45e 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -589,15 +589,12 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.Timestamp.fromtimestamp \ pandas.api.types.infer_dtype \ pandas.api.types.is_datetime64_any_dtype \ - pandas.api.types.is_datetime64_dtype \ pandas.api.types.is_datetime64_ns_dtype \ pandas.api.types.is_datetime64tz_dtype \ pandas.api.types.is_float_dtype \ pandas.api.types.is_int64_dtype \ pandas.api.types.is_integer_dtype \ pandas.api.types.is_interval_dtype \ - pandas.api.types.is_numeric_dtype \ - pandas.api.types.is_object_dtype \ pandas.api.types.is_period_dtype \ pandas.api.types.is_signed_integer_dtype \ pandas.api.types.is_sparse \ diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index ce6ed6ca60238..d258b8f5a3c7f 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -170,6 +170,7 @@ def is_object_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_object_dtype >>> is_object_dtype(object) True >>> is_object_dtype(int) @@ -286,6 +287,7 @@ def is_datetime64_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_datetime64_dtype >>> is_datetime64_dtype(object) False >>> is_datetime64_dtype(np.datetime64) @@ -1135,6 +1137,7 @@ def is_numeric_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_numeric_dtype >>> is_numeric_dtype(str) False >>> is_numeric_dtype(int)
Related to issue #51236 This PR enables functions: `pandas.api.types.is_object_dtype` `pandas.api.types.is_numeric_dtype` `pandas.api.types.is_datetime64_dtype`
https://api.github.com/repos/pandas-dev/pandas/pulls/51323
2023-02-11T10:33:47Z
2023-02-11T16:00:24Z
2023-02-11T16:00:24Z
2023-02-11T16:00:24Z
BUG: non-64-bit numeric dtypes should raise in IntervalDtype constructor
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 29f360e050548..6361d22f0ba73 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1238,6 +1238,8 @@ Interval - Bug in :meth:`IntervalIndex.is_overlapping` incorrect output if interval has duplicate left boundaries (:issue:`49581`) - Bug in :meth:`Series.infer_objects` failing to infer :class:`IntervalDtype` for an object series of :class:`Interval` objects (:issue:`50090`) - Bug in :meth:`Series.shift` with :class:`IntervalDtype` and invalid null ``fill_value`` failing to raise ``TypeError`` (:issue:`51258`) +- Bug in :class:`IntervalDtype` where it accepted non-64-bit numeric subtypes, even though :class:`arrays.InterArray` only can hold numeric data if it is 64-bit. + Supplying non-64-bit numeric subtypes to :class:`IntervalDtype` now raises a ``TypeError`` (:issue:`45412`) - Indexing diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 3444ad77c2981..57a43dfbf9698 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -863,6 +863,58 @@ def is_int64_dtype(arr_or_dtype) -> bool: return _is_dtype_type(arr_or_dtype, classes(np.int64)) +def is_64bit_real_numeric_dtype(arr_or_dtype) -> bool: + """ + Check whether the provided array or dtype is of 64-bit dtype. + + Parameters + ---------- + arr_or_dtype : array-like or dtype + The array or dtype to check. + + Returns + ------- + boolean + Whether or not the array or dtype is of 64-bit dtype. + + Examples + -------- + >>> is_64bit_real_numeric_dtype(str) + False + >>> is_64bit_real_numeric_dtype(np.int32) + False + >>> is_64bit_real_numeric_dtype(np.int64) + True + >>> is_64bit_real_numeric_dtype(pd.Int64Dtype()) + True + >>> is_64bit_real_numeric_dtype("Int64") + True + >>> is_64bit_real_numeric_dtype('int8') + False + >>> is_64bit_real_numeric_dtype('Int8') + False + >>> is_64bit_real_numeric_dtype(float) + True + >>> is_64bit_real_numeric_dtype(np.uint64) + True + >>> is_64bit_real_numeric_dtype(np.array(['a', 'b'])) + False + >>> is_64bit_real_numeric_dtype(np.array([1, 2], dtype=np.int64)) + True + >>> is_64bit_real_numeric_dtype(pd.Index([1, 2.])) # float + True + >>> is_64bit_real_numeric_dtype(np.array([1, 2], dtype=np.uint32)) + False + """ + return _is_dtype_type( + arr_or_dtype, classes(np.int64, np.uint64, np.float64) + ) or _is_dtype( + arr_or_dtype, + lambda typ: isinstance(typ, ExtensionDtype) + and typ.type in (np.int64, np.uint64, np.float64), + ) + + def is_datetime64_any_dtype(arr_or_dtype) -> bool: """ Check whether the provided array or dtype is of the datetime64 dtype. diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 33ff6d1eee686..2d67af4a8b5d2 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -1082,6 +1082,8 @@ class IntervalDtype(PandasExtensionDtype): def __new__(cls, subtype=None, closed: str_type | None = None): from pandas.core.dtypes.common import ( + is_64bit_real_numeric_dtype, + is_any_real_numeric_dtype, is_string_dtype, pandas_dtype, ) @@ -1132,6 +1134,12 @@ def __new__(cls, subtype=None, closed: str_type | None = None): "for IntervalDtype" ) raise TypeError(msg) + elif is_any_real_numeric_dtype(subtype) and not is_64bit_real_numeric_dtype( + subtype + ): + raise TypeError( + f"numeric subtype must be 64-bit numeric dtype, was {subtype}" + ) key = f"{subtype}{closed}" try: diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index d054fb59d8561..aae22e86ca88e 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -8,6 +8,7 @@ from pandas.core.dtypes.base import _registry as registry from pandas.core.dtypes.common import ( + is_64bit_real_numeric_dtype, is_bool_dtype, is_categorical_dtype, is_datetime64_any_dtype, @@ -16,6 +17,7 @@ is_datetime64tz_dtype, is_dtype_equal, is_interval_dtype, + is_numeric_dtype, is_period_dtype, is_string_dtype, ) @@ -597,6 +599,7 @@ def test_construction_generic(self, subtype): @pytest.mark.parametrize( "subtype", [ + *[x for x in tm.ALL_REAL_DTYPES if not is_64bit_real_numeric_dtype(x)], CategoricalDtype(list("abc"), False), CategoricalDtype(list("wxyz"), True), object, @@ -607,11 +610,14 @@ def test_construction_generic(self, subtype): ], ) def test_construction_not_supported(self, subtype): - # GH 19016 - msg = ( - "category, object, and string subtypes are not supported " - "for IntervalDtype" - ) + # GH19016, GH45412 + if is_numeric_dtype(subtype): + msg = "numeric subtype must be 64-bit numeric dtype, was" + else: + msg = ( + "category, object, and string subtypes are not supported " + "for IntervalDtype" + ) with pytest.raises(TypeError, match=msg): IntervalDtype(subtype)
- [x] closes #45412 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51322
2023-02-11T09:11:01Z
2023-05-24T16:12:41Z
null
2023-05-24T16:12:41Z
CLN: clean ._hidden_attrs
diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 38f97e6f12501..7469e92436e1a 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -361,7 +361,7 @@ class SparseArray(OpsMixin, PandasObject, ExtensionArray): """ _subtyp = "sparse_array" # register ABCSparseArray - _hidden_attrs = PandasObject._hidden_attrs | frozenset(["get_values"]) + _hidden_attrs = PandasObject._hidden_attrs | frozenset([]) _sparse_index: SparseIndex _sparse_values: np.ndarray _dtype: SparseDtype diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5d2a0fe66cc1d..d76648558bc6e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -250,9 +250,7 @@ class NDFrame(PandasObject, indexing.IndexingMixin): ] _internal_names_set: set[str] = set(_internal_names) _accessors: set[str] = set() - _hidden_attrs: frozenset[str] = frozenset( - ["_AXIS_NAMES", "_AXIS_NUMBERS", "get_values"] - ) + _hidden_attrs: frozenset[str] = frozenset([]) _metadata: list[str] = [] _is_copy: weakref.ReferenceType[NDFrame] | None = None _mgr: Manager diff --git a/pandas/core/series.py b/pandas/core/series.py index 8934b7c65130b..c37215107c2be 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -345,9 +345,7 @@ class Series(base.IndexOpsMixin, NDFrame): # type: ignore[misc] _internal_names_set = {"index"} | NDFrame._internal_names_set _accessors = {"dt", "cat", "str", "sparse"} _hidden_attrs = ( - base.IndexOpsMixin._hidden_attrs - | NDFrame._hidden_attrs - | frozenset(["compress", "ptp"]) + base.IndexOpsMixin._hidden_attrs | NDFrame._hidden_attrs | frozenset([]) ) # Override cache_readonly bc Series is mutable
Clean-up contents of `_hidden_attrs` after deprecations & removals.
https://api.github.com/repos/pandas-dev/pandas/pulls/51321
2023-02-11T07:54:17Z
2023-02-13T18:44:12Z
2023-02-13T18:44:12Z
2023-02-13T23:26:24Z
BUG: to_datetime with both origin and unit
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 43a34c8e18b2d..492b209270be1 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1182,6 +1182,7 @@ Datetimelike - Bug in :func:`to_datetime` was not returning input with ``errors='ignore'`` when input was out-of-bounds (:issue:`50587`) - Bug in :func:`DataFrame.from_records` when given a :class:`DataFrame` input with timezone-aware datetime64 columns incorrectly dropping the timezone-awareness (:issue:`51162`) - Bug in :func:`to_datetime` was raising ``decimal.InvalidOperation`` when parsing date strings with ``errors='coerce'`` (:issue:`51084`) +- Bug in :func:`to_datetime` with both ``unit`` and ``origin`` specified returning incorrect results (:issue:`42624`) - Timedelta diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 76e144c70c7d5..3006bc6290ff7 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -606,7 +606,7 @@ def _adjust_to_origin(arg, origin, unit): # we are going to offset back to unix / epoch time try: - offset = Timestamp(origin) + offset = Timestamp(origin, unit=unit) except OutOfBoundsDatetime as err: raise OutOfBoundsDatetime(f"origin {origin} is Out of Bounds") from err except ValueError as err: diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index ef5ace2d1f1ed..31b9f2f991efd 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -3196,6 +3196,16 @@ def julian_dates(): class TestOrigin: + def test_origin_and_unit(self): + # GH#42624 + ts = to_datetime(1, unit="s", origin=1) + expected = Timestamp("1970-01-01 00:00:02") + assert ts == expected + + ts = to_datetime(1, unit="s", origin=1_000_000_000) + expected = Timestamp("2001-09-09 01:46:41") + assert ts == expected + def test_julian(self, julian_dates): # gh-11276, gh-11745 # for origin as julian
- [x] closes #42624 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51320
2023-02-11T01:26:37Z
2023-02-13T18:59:48Z
2023-02-13T18:59:48Z
2023-02-13T19:01:07Z
ENH: EA._hash_pandas_object
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 865f6d46cfee0..d3e7cba4ed712 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -512,6 +512,7 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.api.extensions.ExtensionArray._from_factorized \ pandas.api.extensions.ExtensionArray._from_sequence \ pandas.api.extensions.ExtensionArray._from_sequence_of_strings \ + pandas.api.extensions.ExtensionArray._hash_pandas_object \ pandas.api.extensions.ExtensionArray._reduce \ pandas.api.extensions.ExtensionArray._values_for_argsort \ pandas.api.extensions.ExtensionArray._values_for_factorize \ diff --git a/doc/source/reference/extensions.rst b/doc/source/reference/extensions.rst index 595b415ff7342..b33efd388bd60 100644 --- a/doc/source/reference/extensions.rst +++ b/doc/source/reference/extensions.rst @@ -38,6 +38,7 @@ objects. api.extensions.ExtensionArray._from_factorized api.extensions.ExtensionArray._from_sequence api.extensions.ExtensionArray._from_sequence_of_strings + api.extensions.ExtensionArray._hash_pandas_object api.extensions.ExtensionArray._reduce api.extensions.ExtensionArray._values_for_argsort api.extensions.ExtensionArray._values_for_factorize diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 5d1bb04cfacbd..3bcc3159ddf58 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -192,6 +192,16 @@ def _values_for_argsort(self) -> np.ndarray: def _values_for_factorize(self): return self._ndarray, self._internal_fill_value + def _hash_pandas_object( + self, *, encoding: str, hash_key: str, categorize: bool + ) -> npt.NDArray[np.uint64]: + from pandas.core.util.hashing import hash_array + + values = self._ndarray + return hash_array( + values, encoding=encoding, hash_key=hash_key, categorize=categorize + ) + # Signature of "argmin" incompatible with supertype "ExtensionArray" def argmin(self, axis: AxisInt = 0, skipna: bool = True): # type: ignore[override] # override base class by adding axis keyword diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index db8c87f0654cd..1a082a7579dc3 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -140,6 +140,7 @@ class ExtensionArray: _from_factorized _from_sequence _from_sequence_of_strings + _hash_pandas_object _reduce _values_for_argsort _values_for_factorize @@ -1002,11 +1003,6 @@ def _values_for_factorize(self) -> tuple[np.ndarray, Any]: as NA in the factorization routines, so it will be coded as `-1` and not included in `uniques`. By default, ``np.nan`` is used. - - Notes - ----- - The values returned by this method are also used in - :func:`pandas.util.hash_pandas_object`. """ return self.astype(object), np.nan @@ -1452,6 +1448,31 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs): # Non-Optimized Default Methods; in the case of the private methods here, # these are not guaranteed to be stable across pandas versions. + def _hash_pandas_object( + self, *, encoding: str, hash_key: str, categorize: bool + ) -> npt.NDArray[np.uint64]: + """ + Hook for hash_pandas_object. + + Default is likely non-performant. + + Parameters + ---------- + encoding : str + hash_key : str + categorize : bool + + Returns + ------- + np.ndarray[uint64] + """ + from pandas.core.util.hashing import hash_array + + values = self.to_numpy(copy=False) + return hash_array( + values, encoding=encoding, hash_key=hash_key, categorize=categorize + ) + def tolist(self) -> list: """ Return a list of the values. diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 02ee2eb4a80ce..dd48da9ab6c16 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1762,6 +1762,49 @@ def _values_for_rank(self): ) return values + def _hash_pandas_object( + self, *, encoding: str, hash_key: str, categorize: bool + ) -> npt.NDArray[np.uint64]: + """ + Hash a Categorical by hashing its categories, and then mapping the codes + to the hashes. + + Parameters + ---------- + encoding : str + hash_key : str + categorize : bool + Ignored for Categorical. + + Returns + ------- + np.ndarray[uint64] + """ + # Note we ignore categorize, as we are already Categorical. + from pandas.core.util.hashing import hash_array + + # Convert ExtensionArrays to ndarrays + values = np.asarray(self.categories._values) + hashed = hash_array(values, encoding, hash_key, categorize=False) + + # we have uint64, as we don't directly support missing values + # we don't want to use take_nd which will coerce to float + # instead, directly construct the result with a + # max(np.uint64) as the missing value indicator + # + # TODO: GH#15362 + + mask = self.isna() + if len(hashed): + result = hashed.take(self._codes) + else: + result = np.zeros(len(mask), dtype="uint64") + + if mask.any(): + result[mask] = lib.u8max + + return result + # ------------------------------------------------------------------ # NDArrayBackedExtensionArray compat diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index 350914cc50556..280e9068b9f44 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -9,22 +9,17 @@ Hashable, Iterable, Iterator, - cast, ) import numpy as np -from pandas._libs import lib from pandas._libs.hashing import hash_object_array from pandas._typing import ( ArrayLike, npt, ) -from pandas.core.dtypes.common import ( - is_categorical_dtype, - is_list_like, -) +from pandas.core.dtypes.common import is_list_like from pandas.core.dtypes.generic import ( ABCDataFrame, ABCExtensionArray, @@ -35,7 +30,6 @@ if TYPE_CHECKING: from pandas import ( - Categorical, DataFrame, Index, MultiIndex, @@ -214,53 +208,14 @@ def hash_tuples( # hash the list-of-ndarrays hashes = ( - _hash_categorical(cat, encoding=encoding, hash_key=hash_key) for cat in cat_vals + cat._hash_pandas_object(encoding=encoding, hash_key=hash_key, categorize=False) + for cat in cat_vals ) h = combine_hash_arrays(hashes, len(cat_vals)) return h -def _hash_categorical( - cat: Categorical, encoding: str, hash_key: str -) -> npt.NDArray[np.uint64]: - """ - Hash a Categorical by hashing its categories, and then mapping the codes - to the hashes - - Parameters - ---------- - cat : Categorical - encoding : str - hash_key : str - - Returns - ------- - ndarray[np.uint64] of hashed values, same size as len(c) - """ - # Convert ExtensionArrays to ndarrays - 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 - # we don't want to use take_nd which will coerce to float - # instead, directly construct the result with a - # max(np.uint64) as the missing value indicator - # - # TODO: GH 15362 - - mask = cat.isna() - if len(hashed): - result = hashed.take(cat.codes) - else: - result = np.zeros(len(mask), dtype="uint64") - - if mask.any(): - result[mask] = lib.u8max - - return result - - def hash_array( vals: ArrayLike, encoding: str = "utf8", @@ -288,17 +243,11 @@ def hash_array( """ if not hasattr(vals, "dtype"): raise TypeError("must pass a ndarray-like") - dtype = vals.dtype - - # For categoricals, we hash the categories, then remap the codes to the - # 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 isinstance(vals, ABCExtensionArray): - vals, _ = vals._values_for_factorize() + if isinstance(vals, ABCExtensionArray): + return vals._hash_pandas_object( + encoding=encoding, hash_key=hash_key, categorize=categorize + ) elif not isinstance(vals, np.ndarray): # GH#42003 @@ -347,7 +296,9 @@ def _hash_ndarray( codes, categories = factorize(vals, sort=False) cat = Categorical(codes, Index(categories), ordered=False, fastpath=True) - return _hash_categorical(cat, encoding, hash_key) + return cat._hash_pandas_object( + encoding=encoding, hash_key=hash_key, categorize=False + ) try: vals = hash_object_array(vals, hash_key, encoding) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index ca867ffb77296..173edfbdcd7a7 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -18,6 +18,17 @@ class BaseMethodsTests(BaseExtensionTests): """Various Series and DataFrame methods.""" + def test_hash_pandas_object(self, data): + # _hash_pandas_object should return a uint64 ndarray of the same length + # as the data + res = data._hash_pandas_object( + encoding="utf-8", + hash_key=pd.core.util.hashing._default_hash_key, + categorize=False, + ) + assert res.dtype == np.uint64 + assert res.shape == data.shape + def test_value_counts_default_dropna(self, data): # make sure we have consistent default dropna kwarg if not hasattr(data, "value_counts"): diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 37a7d78d3aa3d..7fda870e6f721 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -240,6 +240,10 @@ class TestReduce(base.BaseNoReduceTests): class TestMethods(BaseJSON, base.BaseMethodsTests): + @pytest.mark.xfail(reason="ValueError: setting an array element with a sequence") + def test_hash_pandas_object(self, data): + super().test_hash_pandas_object(data) + @unhashable def test_value_counts(self, all_data, dropna): super().test_value_counts(all_data, dropna)
- [x] closes #51108 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51319
2023-02-11T00:10:29Z
2023-03-01T16:25:02Z
2023-03-01T16:25:02Z
2023-06-20T07:23:05Z
CLN: assorted
diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c index 2ed0cef3cdc58..38304cca94a12 100644 --- a/pandas/_libs/src/parser/io.c +++ b/pandas/_libs/src/parser/io.c @@ -67,7 +67,7 @@ void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, func = PyObject_GetAttrString(src->obj, "read"); - /* TODO: does this release the GIL? */ + /* Note: PyObject_CallObject requires the GIL */ result = PyObject_CallObject(func, args); Py_XDECREF(args); Py_XDECREF(func); diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index e48871c537310..445683968c58f 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -651,6 +651,7 @@ cdef datetime dateutil_parse( try: res, _ = DEFAULTPARSER._parse(timestr, dayfirst=dayfirst, yearfirst=yearfirst) except InvalidOperation: + # GH#51157 dateutil can raise decimal.InvalidOperation res = None if res is None: diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index e69b0899facb9..00e949b1dd318 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -14,6 +14,7 @@ ContextManager, Counter, Iterable, + cast, ) import numpy as np @@ -121,6 +122,7 @@ PeriodIndex, TimedeltaIndex, ) + from pandas.core.arrays import ArrowExtensionArray _N = 30 _K = 4 @@ -1019,11 +1021,11 @@ def shares_memory(left, right) -> bool: if isinstance(left, ExtensionArray) and left.dtype == "string[pyarrow]": # https://github.com/pandas-dev/pandas/pull/43930#discussion_r736862669 + left = cast("ArrowExtensionArray", left) if isinstance(right, ExtensionArray) and right.dtype == "string[pyarrow]": - # error: "ExtensionArray" has no attribute "_data" - left_pa_data = left._data # type: ignore[attr-defined] - # error: "ExtensionArray" has no attribute "_data" - right_pa_data = right._data # type: ignore[attr-defined] + right = cast("ArrowExtensionArray", right) + left_pa_data = left._data + right_pa_data = right._data left_buf1 = left_pa_data.chunk(0).buffers()[1] right_buf1 = right_pa_data.chunk(0).buffers()[1] return left_buf1 == right_buf1 diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index f2bfde585fbeb..2c71990d74cb1 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -20,6 +20,7 @@ from typing import ( Any, TypeVar, + cast, overload, ) @@ -159,8 +160,8 @@ def validate_argsort_with_ascending(ascending: bool | int | None, args, kwargs) ascending = True validate_argsort_kind(args, kwargs, max_fname_arg_count=3) - # error: Incompatible return value type (got "int", expected "bool") - return ascending # type: ignore[return-value] + ascending = cast(bool, ascending) + return ascending CLIP_DEFAULTS: dict[str, Any] = {"out": None} diff --git a/pandas/core/apply.py b/pandas/core/apply.py index c28da1bc758cd..c69f36ff6db0c 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -588,13 +588,11 @@ class NDFrameApply(Apply): not GroupByApply or ResamplerWindowApply """ + obj: DataFrame | Series + @property def index(self) -> Index: - # error: Argument 1 to "__get__" of "AxisProperty" has incompatible type - # "Union[Series, DataFrame, GroupBy[Any], SeriesGroupBy, - # DataFrameGroupBy, BaseWindow, Resampler]"; expected "Union[DataFrame, - # Series]" - return self.obj.index # type:ignore[arg-type] + return self.obj.index @property def agg_axis(self) -> Index: diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index fb953e601735e..e2fe70c963b11 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -88,7 +88,6 @@ from pandas.core.algorithms import ( factorize, take_nd, - unique1d, ) from pandas.core.arrays._mixins import ( NDArrayBackedExtensionArray, @@ -2096,8 +2095,8 @@ def unique(self): ['b', 'a'] Categories (3, object): ['a' < 'b' < 'c'] """ - unique_codes = unique1d(self.codes) - return self._from_backing_data(unique_codes) + # pylint: disable=useless-parent-delegation + return super().unique() def _cast_quantile_result(self, res_values: np.ndarray) -> np.ndarray: # make sure we have correct itemsize for resulting codes diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2650090a3f61a..33d503f3dd4cb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3811,6 +3811,8 @@ def _getitem_multilevel(self, key): # string in the key. If the result is a Series, exclude the # implied empty string from its name. if len(result.columns) == 1: + # e.g. test_frame_getitem_multicolumn_empty_level, + # test_frame_mixed_depth_get, test_loc_setitem_single_column_slice top = result.columns[0] if isinstance(top, tuple): top = top[0] @@ -7822,13 +7824,13 @@ def combine( result = {} for col in new_columns: series = this[col] - otherSeries = other[col] + other_series = other[col] this_dtype = series.dtype - other_dtype = otherSeries.dtype + other_dtype = other_series.dtype this_mask = isna(series) - other_mask = isna(otherSeries) + other_mask = isna(other_series) # don't overwrite columns unnecessarily # DO propagate if this column is not in the intersection @@ -7838,9 +7840,9 @@ def combine( if do_fill: series = series.copy() - otherSeries = otherSeries.copy() + other_series = other_series.copy() series[this_mask] = fill_value - otherSeries[other_mask] = fill_value + other_series[other_mask] = fill_value if col not in self.columns: # If self DataFrame does not have col in other DataFrame, @@ -7855,9 +7857,9 @@ def combine( # if we have different dtypes, possibly promote new_dtype = find_common_type([this_dtype, other_dtype]) series = series.astype(new_dtype, copy=False) - otherSeries = otherSeries.astype(new_dtype, copy=False) + other_series = other_series.astype(new_dtype, copy=False) - arr = func(series, otherSeries) + arr = func(series, other_series) if isinstance(new_dtype, np.dtype): # if new_dtype is an EA Dtype, then `func` is expected to return # the correct dtype without any additional casting @@ -9919,7 +9921,7 @@ def _dict_round(df: DataFrame, decimals): except KeyError: yield vals - def _series_round(ser: Series, decimals: int): + def _series_round(ser: Series, decimals: int) -> Series: if is_integer_dtype(ser.dtype) or is_float_dtype(ser.dtype): return ser.round(decimals) return ser diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index a3402e53904a4..58076992f3a83 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1265,9 +1265,10 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) result = op.agg() if not is_dict_like(func) and result is not None: return result - elif relabeling and result is not None: + elif relabeling: # this should be the only (non-raising) case with relabeling # used reordered index of columns + result = cast(DataFrame, result) result = result.iloc[:, order] result = cast(DataFrame, result) # error: Incompatible types in assignment (expression has type @@ -1336,6 +1337,9 @@ def _iterate_slices(self) -> Iterable[Series]: else: for label, values in obj.items(): if label in self.exclusions: + # Note: if we tried to just iterate over _obj_with_exclusions, + # we would break test_wrap_agg_out by yielding a column + # that is skipped here but not dropped from obj_with_exclusions continue yield values @@ -1379,6 +1383,7 @@ def _wrap_applied_output( return result # GH12824 + # using values[0] here breaks test_groupby_apply_none_first first_not_none = next(com.not_none(*values), None) if first_not_none is None: @@ -1817,7 +1822,7 @@ def _indexed_output_to_ndframe( def _wrap_agged_manager(self, mgr: Manager2D) -> DataFrame: return self.obj._constructor(mgr) - def _iterate_column_groupbys(self, obj: DataFrame | Series): + def _iterate_column_groupbys(self, obj: DataFrame): for i, colname in enumerate(obj.columns): yield colname, SeriesGroupBy( obj.iloc[:, i], diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index e42566bfa11a0..0454f21e79ab5 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -89,7 +89,6 @@ class providing the base-class of operations. from pandas.core import ( algorithms, - nanops, sample, ) from pandas.core._numba import executor @@ -1342,10 +1341,6 @@ def f(g): with np.errstate(all="ignore"): return func(g, *args, **kwargs) - elif hasattr(nanops, f"nan{func}"): - # TODO: should we wrap this in to e.g. _is_builtin_func? - f = getattr(nanops, f"nan{func}") - else: raise ValueError( "func must be a callable if args or kwargs are supplied" @@ -1417,6 +1412,8 @@ def _python_apply_general( is_transform, ) + # TODO: I (jbrockmendel) think this should be equivalent to doing grouped_reduce + # on _agg_py_fallback, but trying that here fails a bunch of tests 2023-02-07. @final def _python_agg_general(self, func, *args, **kwargs): func = com.is_builtin_func(func) @@ -2902,10 +2899,7 @@ def blk_func(values: ArrayLike) -> ArrayLike: out[i, :] = algorithms.take_nd(value_element, indexer) return out - obj = self._obj_with_exclusions - if self.axis == 1: - obj = obj.T - mgr = obj._mgr + mgr = self._get_data_to_aggregate() res_mgr = mgr.apply(blk_func) new_obj = self._wrap_agged_manager(res_mgr) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index c2e3eb49723ec..20c3733b50bc5 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -207,6 +207,7 @@ def _get_cython_vals(self, values: np.ndarray) -> np.ndarray: if how in ["var", "mean"] or ( self.kind == "transform" and self.has_dropped_na ): + # has_dropped_na check need for test_null_group_str_transformer # result may still include NaN, so we have to cast values = ensure_float64(values) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 60d022a0c7964..6d20935d5f244 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -630,7 +630,6 @@ def _replace_regex( to_replace, value, inplace: bool = False, - convert: bool = True, mask=None, ) -> list[Block]: """ @@ -644,8 +643,6 @@ def _replace_regex( Replacement object. inplace : bool, default False Perform inplace modification. - convert : bool, default True - If true, try to coerce any object types to better types. mask : array-like of bool, optional True indicate corresponding element is ignored. @@ -788,7 +785,6 @@ def _replace_coerce( to_replace, value, inplace=inplace, - convert=False, mask=mask, ) else: diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 0af851669820e..1ffcf93278e50 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -1512,6 +1512,10 @@ def _maybe_null_out( Dtype The product of all elements on a given axis. ( NaNs are treated as 1) """ + if mask is None and min_count == 0: + # nothing to check; short-circuit + return result + if axis is not None and isinstance(result, np.ndarray): if mask is not None: null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0 diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 34d1f98501b0b..64480a7da3326 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -4045,6 +4045,9 @@ def get_blk_items(mgr): blocks = list(mgr.blocks) blk_items = get_blk_items(mgr) for c in data_columns: + # This reindex would raise ValueError if we had a duplicate + # index, so we can infer that (as long as axis==1) we + # get a single column back, so a single block. mgr = frame.reindex([c], axis=axis)._mgr mgr = cast(BlockManager, mgr) blocks.extend(mgr.blocks) diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 7fdb7423d9a1d..75f27d38c8fd8 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -1574,7 +1574,7 @@ def test_pi_sub_period(self): assert result.freq == exp.freq def test_pi_sub_pdnat(self): - # GH#13071 + # GH#13071, GH#19389 idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" ) diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index 695ba359f60d1..8ae0f60bfc88e 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -496,7 +496,6 @@ def test_is_datetime_or_timedelta_dtype(): assert not com.is_datetime_or_timedelta_dtype(pd.Series([1, 2])) assert not com.is_datetime_or_timedelta_dtype(np.array(["a", "b"])) - # TODO(jreback), this is slightly suspect assert not com.is_datetime_or_timedelta_dtype(DatetimeTZDtype("ns", "US/Eastern")) assert com.is_datetime_or_timedelta_dtype(np.datetime64) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 55dca3a3bc619..1d3514e39cf00 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -568,6 +568,7 @@ def test_array_equivalent_nested(strict_nan): assert not array_equivalent(left, right, strict_nan=strict_nan) +@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning") @pytest.mark.parametrize( "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False] ) @@ -610,6 +611,7 @@ def test_array_equivalent_nested_list(strict_nan): assert not array_equivalent(left, right, strict_nan=strict_nan) +@pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning") @pytest.mark.xfail(reason="failing") @pytest.mark.parametrize("strict_nan", [True, False]) def test_array_equivalent_nested_mixed_list(strict_nan): diff --git a/pandas/tests/groupby/test_allowlist.py b/pandas/tests/groupby/test_allowlist.py index 1d18e7dc6c2cf..c7657d3e8eea5 100644 --- a/pandas/tests/groupby/test_allowlist.py +++ b/pandas/tests/groupby/test_allowlist.py @@ -314,8 +314,6 @@ def test_all_methods_categorized(mframe): # removed a public method? all_categorized = reduction_kernels | transformation_kernels | groupby_other_methods - print(names) - print(all_categorized) if names != all_categorized: msg = f""" Some methods which are supposed to be on the Grouper class diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index 8c30836f2cf91..49b2e621b7adc 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -63,7 +63,3 @@ def test_generate_bins(binner, closed, expected): values = np.array([1, 2, 3, 4, 5, 6], dtype=np.int64) result = lib.generate_bins_dt64(values, binner, closed=closed) tm.assert_numpy_array_equal(result, expected) - - -class TestMoments: - pass diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py index bc9795ca21e58..f534a0c65fdbc 100644 --- a/pandas/tests/groupby/test_filters.py +++ b/pandas/tests/groupby/test_filters.py @@ -369,8 +369,7 @@ def test_filter_and_transform_with_non_unique_int_index(): tm.assert_series_equal(actual, expected) actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) - NA = np.nan - expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid") + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") # ^ made manually because this can get confusing! tm.assert_series_equal(actual, expected) @@ -412,8 +411,7 @@ def test_filter_and_transform_with_multiple_non_unique_int_index(): tm.assert_series_equal(actual, expected) actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) - NA = np.nan - expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid") + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") # ^ made manually because this can get confusing! tm.assert_series_equal(actual, expected) @@ -455,8 +453,7 @@ def test_filter_and_transform_with_non_unique_float_index(): tm.assert_series_equal(actual, expected) actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) - NA = np.nan - expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid") + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") # ^ made manually because this can get confusing! tm.assert_series_equal(actual, expected) @@ -501,8 +498,7 @@ def test_filter_and_transform_with_non_unique_timestamp_index(): tm.assert_series_equal(actual, expected) actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) - NA = np.nan - expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid") + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") # ^ made manually because this can get confusing! tm.assert_series_equal(actual, expected) @@ -544,8 +540,7 @@ def test_filter_and_transform_with_non_unique_string_index(): tm.assert_series_equal(actual, expected) actual = grouped_ser.filter(lambda x: len(x) > 1, dropna=False) - NA = np.nan - expected = Series([NA, 1, 1, NA, 2, NA, NA, 3], index, name="pid") + expected = Series([np.nan, 1, 1, np.nan, 2, np.nan, np.nan, 3], index, name="pid") # ^ made manually because this can get confusing! tm.assert_series_equal(actual, expected) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index eeea9eef1ab45..b1ab1135f6e35 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1470,9 +1470,7 @@ def test_numeric_only(kernel, has_arg, numeric_only, keys): @pytest.mark.parametrize("dtype", [bool, int, float, object]) def test_deprecate_numeric_only_series(dtype, groupby_func, request): # GH#46560 - if groupby_func in ("backfill", "pad"): - pytest.skip("method is deprecated") - elif groupby_func == "corrwith": + if groupby_func == "corrwith": msg = "corrwith is not implemented on SeriesGroupBy" request.node.add_marker(pytest.mark.xfail(reason=msg)) diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py index 854ae8b62db30..da1d692f9eb2d 100644 --- a/pandas/tests/indexes/categorical/test_astype.py +++ b/pandas/tests/indexes/categorical/test_astype.py @@ -73,12 +73,15 @@ def test_astype_category(self, name, dtype_ordered, index_ordered): expected = index tm.assert_index_equal(result, expected) - def test_categorical_date_roundtrip(self): + @pytest.mark.parametrize("box", [True, False]) + def test_categorical_date_roundtrip(self, box): # astype to categorical and back should preserve date objects v = date.today() obj = Index([v, v]) assert obj.dtype == object + if box: + obj = obj.array cat = obj.astype("category") diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 175f435fe9696..46bd9ea8af055 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -15,7 +15,6 @@ OutOfBoundsDatetime, astype_overflowsafe, ) -from pandas.compat import PY39 import pandas as pd from pandas import ( @@ -32,9 +31,6 @@ period_array, ) -if PY39: - import zoneinfo - class TestDatetimeIndex: def test_from_dt64_unsupported_unit(self): @@ -1102,104 +1098,3 @@ def test_date_range_tuple_freq_raises(self): edate = datetime(2000, 1, 1) with pytest.raises(TypeError, match="pass as a string instead"): date_range(end=edate, freq=("D", 5), periods=20) - - -def test_timestamp_constructor_invalid_fold_raise(): - # Test for #25057 - # Valid fold values are only [None, 0, 1] - msg = "Valid values for the fold argument are None, 0, or 1." - with pytest.raises(ValueError, match=msg): - Timestamp(123, fold=2) - - -def test_timestamp_constructor_pytz_fold_raise(): - # Test for #25057 - # pytz doesn't support fold. Check that we raise - # if fold is passed with pytz - msg = "pytz timezones do not support fold. Please use dateutil timezones." - tz = pytz.timezone("Europe/London") - with pytest.raises(ValueError, match=msg): - Timestamp(datetime(2019, 10, 27, 0, 30, 0, 0), tz=tz, fold=0) - - -@pytest.mark.parametrize("fold", [0, 1]) -@pytest.mark.parametrize( - "ts_input", - [ - 1572136200000000000, - 1572136200000000000.0, - np.datetime64(1572136200000000000, "ns"), - "2019-10-27 01:30:00+01:00", - datetime(2019, 10, 27, 0, 30, 0, 0, tzinfo=timezone.utc), - ], -) -def test_timestamp_constructor_fold_conflict(ts_input, fold): - # Test for #25057 - # Check that we raise on fold conflict - msg = ( - "Cannot pass fold with possibly unambiguous input: int, float, " - "numpy.datetime64, str, or timezone-aware datetime-like. " - "Pass naive datetime-like or build Timestamp from components." - ) - with pytest.raises(ValueError, match=msg): - Timestamp(ts_input=ts_input, fold=fold) - - -@pytest.mark.parametrize("tz", ["dateutil/Europe/London", None]) -@pytest.mark.parametrize("fold", [0, 1]) -def test_timestamp_constructor_retain_fold(tz, fold): - # Test for #25057 - # Check that we retain fold - ts = Timestamp(year=2019, month=10, day=27, hour=1, minute=30, tz=tz, fold=fold) - result = ts.fold - expected = fold - assert result == expected - - -_tzs = ["dateutil/Europe/London"] -if PY39: - try: - _tzs = ["dateutil/Europe/London", zoneinfo.ZoneInfo("Europe/London")] - except zoneinfo.ZoneInfoNotFoundError: - pass - - -@pytest.mark.parametrize("tz", _tzs) -@pytest.mark.parametrize( - "ts_input,fold_out", - [ - (1572136200000000000, 0), - (1572139800000000000, 1), - ("2019-10-27 01:30:00+01:00", 0), - ("2019-10-27 01:30:00+00:00", 1), - (datetime(2019, 10, 27, 1, 30, 0, 0, fold=0), 0), - (datetime(2019, 10, 27, 1, 30, 0, 0, fold=1), 1), - ], -) -def test_timestamp_constructor_infer_fold_from_value(tz, ts_input, fold_out): - # Test for #25057 - # Check that we infer fold correctly based on timestamps since utc - # or strings - ts = Timestamp(ts_input, tz=tz) - result = ts.fold - expected = fold_out - assert result == expected - # TODO: belongs in Timestamp tests? - - -@pytest.mark.parametrize("tz", ["dateutil/Europe/London"]) -@pytest.mark.parametrize( - "ts_input,fold,value_out", - [ - (datetime(2019, 10, 27, 1, 30, 0, 0), 0, 1572136200000000), - (datetime(2019, 10, 27, 1, 30, 0, 0), 1, 1572139800000000), - ], -) -def test_timestamp_constructor_adjust_value_for_fold(tz, ts_input, fold, value_out): - # Test for #25057 - # Check that we adjust value for fold correctly - # based on timestamps since utc - ts = Timestamp(ts_input, tz=tz, fold=fold) - result = ts._value - expected = value_out - assert result == expected diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index 7f615a18167ae..ca0796e55f28d 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -13,7 +13,10 @@ import pytz from pandas._libs.tslibs.dtypes import NpyDatetimeUnit -from pandas.compat import PY310 +from pandas.compat import ( + PY39, + PY310, +) from pandas.errors import OutOfBoundsDatetime from pandas import ( @@ -22,6 +25,9 @@ Timestamp, ) +if PY39: + import zoneinfo + class TestTimestampConstructors: def test_construct_from_string_invalid_raises(self): @@ -787,3 +793,103 @@ def test_non_nano_value(): # check that the suggested workaround actually works result = ts.asm8.view("i8") assert result == -52700112000 + + +def test_timestamp_constructor_invalid_fold_raise(): + # Test forGH #25057 + # Valid fold values are only [None, 0, 1] + msg = "Valid values for the fold argument are None, 0, or 1." + with pytest.raises(ValueError, match=msg): + Timestamp(123, fold=2) + + +def test_timestamp_constructor_pytz_fold_raise(): + # Test for GH#25057 + # pytz doesn't support fold. Check that we raise + # if fold is passed with pytz + msg = "pytz timezones do not support fold. Please use dateutil timezones." + tz = pytz.timezone("Europe/London") + with pytest.raises(ValueError, match=msg): + Timestamp(datetime(2019, 10, 27, 0, 30, 0, 0), tz=tz, fold=0) + + +@pytest.mark.parametrize("fold", [0, 1]) +@pytest.mark.parametrize( + "ts_input", + [ + 1572136200000000000, + 1572136200000000000.0, + np.datetime64(1572136200000000000, "ns"), + "2019-10-27 01:30:00+01:00", + datetime(2019, 10, 27, 0, 30, 0, 0, tzinfo=timezone.utc), + ], +) +def test_timestamp_constructor_fold_conflict(ts_input, fold): + # Test for GH#25057 + # Check that we raise on fold conflict + msg = ( + "Cannot pass fold with possibly unambiguous input: int, float, " + "numpy.datetime64, str, or timezone-aware datetime-like. " + "Pass naive datetime-like or build Timestamp from components." + ) + with pytest.raises(ValueError, match=msg): + Timestamp(ts_input=ts_input, fold=fold) + + +@pytest.mark.parametrize("tz", ["dateutil/Europe/London", None]) +@pytest.mark.parametrize("fold", [0, 1]) +def test_timestamp_constructor_retain_fold(tz, fold): + # Test for GH#25057 + # Check that we retain fold + ts = Timestamp(year=2019, month=10, day=27, hour=1, minute=30, tz=tz, fold=fold) + result = ts.fold + expected = fold + assert result == expected + + +_tzs = ["dateutil/Europe/London"] +if PY39: + try: + _tzs = ["dateutil/Europe/London", zoneinfo.ZoneInfo("Europe/London")] + except zoneinfo.ZoneInfoNotFoundError: + pass + + +@pytest.mark.parametrize("tz", _tzs) +@pytest.mark.parametrize( + "ts_input,fold_out", + [ + (1572136200000000000, 0), + (1572139800000000000, 1), + ("2019-10-27 01:30:00+01:00", 0), + ("2019-10-27 01:30:00+00:00", 1), + (datetime(2019, 10, 27, 1, 30, 0, 0, fold=0), 0), + (datetime(2019, 10, 27, 1, 30, 0, 0, fold=1), 1), + ], +) +def test_timestamp_constructor_infer_fold_from_value(tz, ts_input, fold_out): + # Test for GH#25057 + # Check that we infer fold correctly based on timestamps since utc + # or strings + ts = Timestamp(ts_input, tz=tz) + result = ts.fold + expected = fold_out + assert result == expected + + +@pytest.mark.parametrize("tz", ["dateutil/Europe/London"]) +@pytest.mark.parametrize( + "ts_input,fold,value_out", + [ + (datetime(2019, 10, 27, 1, 30, 0, 0), 0, 1572136200000000), + (datetime(2019, 10, 27, 1, 30, 0, 0), 1, 1572139800000000), + ], +) +def test_timestamp_constructor_adjust_value_for_fold(tz, ts_input, fold, value_out): + # Test for GH#25057 + # Check that we adjust value for fold correctly + # based on timestamps since utc + ts = Timestamp(ts_input, tz=tz, fold=fold) + result = ts._value + expected = value_out + assert result == expected diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index ef5ace2d1f1ed..b8be54c282dfd 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -547,7 +547,7 @@ class TestToDatetime: @pytest.mark.filterwarnings("ignore:Could not infer format") def test_to_datetime_overflow(self): # we should get an OutOfBoundsDatetime, NOT OverflowError - # TODO: Timestamp raises VaueError("could not convert string to Timestamp") + # TODO: Timestamp raises ValueError("could not convert string to Timestamp") # can we make these more consistent? arg = "08335394550" msg = 'Parsing "08335394550" to datetime overflows, at position 0' diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index ff966496fdda8..34e0c111360fd 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -410,12 +410,6 @@ def _is_business_daily(self) -> bool: ) def _get_wom_rule(self) -> str | None: - # FIXME: dont leave commented-out - # wdiffs = unique(np.diff(self.index.week)) - # We also need -47, -49, -48 to catch index spanning year boundary - # if not lib.ismember(wdiffs, set([4, 5, -47, -49, -48])).all(): - # return None - weekdays = unique(self.index.weekday) if len(weekdays) > 1: return None
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51318
2023-02-10T23:34:11Z
2023-02-13T18:48:11Z
2023-02-13T18:48:11Z
2023-02-13T19:01:48Z
allow type to be specified in argument of tolist()
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index d1bc322a6ec7a..5ee57538f0a3e 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -307,7 +307,7 @@ Other enhancements - Added new argument ``dtype`` to :func:`read_sql` to be consistent with :func:`read_sql_query` (:issue:`50797`) - Added new argument ``engine`` to :func:`read_json` to support parsing JSON with pyarrow by specifying ``engine="pyarrow"`` (:issue:`48893`) - Added support for SQLAlchemy 2.0 (:issue:`40686`) -- +- Added new argument ``scalar_type`` to :meth:`Index.tolist` to allow a specification for typing purposes of the elements of the returned list. .. --------------------------------------------------------------------------- .. _whatsnew_200.notable_bug_fixes: diff --git a/pandas/core/base.py b/pandas/core/base.py index b708ff44b39d0..ac5a630d002f5 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -28,6 +28,7 @@ IndexLabel, NDFrameT, Shape, + T as Ttolist, npt, ) from pandas.compat import PYPY @@ -735,13 +736,34 @@ def argmin( delegate, skipna=skipna ) - def tolist(self): + # The overloads are done this way due to a mypy issue. See + # https://github.com/python/mypy/issues/3737#issuecomment-465355737 + @overload + def tolist(self) -> list[Any]: + ... + + @overload + def tolist(self, scalar_type: type[Ttolist]) -> list[Ttolist]: + ... + + def tolist(self, scalar_type=Any) -> list[Any]: """ Return a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) + or a tuple (for MultiIndex) + + For type checking purposes, the type of the returned elements of the + list may be specified. For example ``index.tolist(str)`` will appear + to a type checker as ``list[str]``. However, the returned type of + each element will be the actual type of the elements in the values. + + Parameters + ---------- + scalar_type : type, default Any + Returned type of elements in the list. Returns ------- @@ -763,6 +785,7 @@ def __iter__(self) -> Iterator: These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) + or a tuple (for MultiIndex) Returns ------- diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index ff24f97106c51..bdde5f0408cb0 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -3,6 +3,7 @@ from typing import ( Any, Hashable, + overload, ) import numpy as np @@ -11,6 +12,7 @@ from pandas._typing import ( Dtype, DtypeObj, + T as Ttolist, npt, ) from pandas.util._decorators import ( @@ -52,7 +54,6 @@ @inherit_names( [ "argsort", - "tolist", "codes", "categories", "ordered", @@ -328,6 +329,19 @@ def _format_with_header(self, header: list[str], na_rep: str) -> list[str]: # -------------------------------------------------------------------- + # The overloads are done this way due to a mypy issue. See + # https://github.com/python/mypy/issues/3737#issuecomment-465355737 + @overload + def tolist(self) -> list[Any]: + ... + + @overload + def tolist(self, scalar_type: type[Ttolist]) -> list[Ttolist]: + ... + + def tolist(self, scalar_type=Any) -> list[Any]: + return self._data.tolist() + @property def inferred_type(self) -> str: return "categorical" diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index ca34fcfc7a625..6d1d0dab5a80d 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -385,8 +385,9 @@ def _should_fallback_to_positional(self) -> bool: return False # -------------------------------------------------------------------- - - def tolist(self) -> list[int]: + # error: Signature of "tolist" incompatible with supertype + # "IndexOpsMixin" [override] + def tolist(self, scalar_type: type = int) -> list[int]: # type: ignore[override] return list(self._range) @doc(Index.__iter__) diff --git a/pandas/tests/indexes/test_any_index.py b/pandas/tests/indexes/test_any_index.py index 3b3d6dbaf697f..0ceed0a3dda03 100644 --- a/pandas/tests/indexes/test_any_index.py +++ b/pandas/tests/indexes/test_any_index.py @@ -95,6 +95,8 @@ def test_to_series_with_arguments(self, index): def test_tolist_matches_list(self, index): assert index.tolist() == list(index) + if len(index) > 0: + assert index.tolist(type(index[0])) == list(index) class TestRoundTrips:
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - no corresponding issue - [x] [Tests added and passed] - modified `tests/indexes/test_any_index.py:TestConversion.test_tolist_matches_list()` - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/v2.0.0.rst` file if fixing a bug or adding a new feature. I'm not sure how people will feel about this idea. The idea here is that if you do something like `y = [x for x in df.index if x.startswith("a")]`, right now, the type of `x` cannot be inferred. That means that the expression `x.startswith("a")` isn't type checked. But, with this PR, if you do `y = [x for x in df.index.tolist(str) if x.startswith("a")]` then the expression `x.startswith("a")` will be type checked. Not only that, the type checker can infer that `y` will be `list[str]` in this example. Furthermore, if you wrote `y = [x for x in df.index.tolist(int) if x.startswith("a")]`, then the type checker would catch that you can't call `startswith()` on an `int`. Note that the new argument to `tolist()` is optional. The argument is ignored in the `tolist()` method. It is only used to change the type of the result. It does not convert the type of the values in the list. This is only there for convenience with typing. If this PR is accepted for 2.0, then a corresponding change will also be made to `pandas-stubs` once 2.0 is released.
https://api.github.com/repos/pandas-dev/pandas/pulls/51317
2023-02-10T23:28:37Z
2023-02-13T19:56:00Z
null
2023-02-13T20:48:14Z
ENH: Use MaskedEngine for numeric pyarrow dtypes
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index adfa382b66514..e6068fc4e94b1 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1117,7 +1117,7 @@ Performance improvements - Performance improvement in :meth:`DataFrame.loc` and :meth:`Series.loc` for tuple-based indexing of a :class:`MultiIndex` (:issue:`48384`) - Performance improvement for :meth:`Series.replace` with categorical dtype (:issue:`49404`) - Performance improvement for :meth:`MultiIndex.unique` (:issue:`48335`) -- Performance improvement for indexing operations with nullable dtypes (:issue:`49420`) +- Performance improvement for indexing operations with nullable and arrow dtypes (:issue:`49420`, :issue:`51316`) - Performance improvement for :func:`concat` with extension array backed indexes (:issue:`49128`, :issue:`49178`) - Performance improvement for :func:`api.types.infer_dtype` (:issue:`51054`) - Reduce memory usage of :meth:`DataFrame.to_pickle`/:meth:`Series.to_pickle` when using BZ2 or LZMA (:issue:`49068`) diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 2a6c26d595548..1b42ad1c0fda7 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -1141,12 +1141,26 @@ cdef class ExtensionEngine(SharedEngine): cdef class MaskedIndexEngine(IndexEngine): def __init__(self, object values): - super().__init__(values._data) - self.mask = values._mask + super().__init__(self._get_data(values)) + self.mask = self._get_mask(values) + + def _get_data(self, object values) -> np.ndarray: + if hasattr(values, "_mask"): + return values._data + # We are an ArrowExtensionArray + # Set 1 as na_value to avoid ending up with NA and an object array + # TODO: Remove when arrow engine is implemented + return values.to_numpy(na_value=1, dtype=values.dtype.numpy_dtype) + + def _get_mask(self, object values) -> np.ndarray: + if hasattr(values, "_mask"): + return values._mask + # We are an ArrowExtensionArray + return values.isna() def get_indexer(self, object values) -> np.ndarray: self._ensure_mapping_populated() - return self.mapping.lookup(values._data, values._mask) + return self.mapping.lookup(self._get_data(values), self._get_mask(values)) def get_indexer_non_unique(self, object targets): """ @@ -1171,8 +1185,8 @@ cdef class MaskedIndexEngine(IndexEngine): Py_ssize_t count = 0, count_missing = 0 Py_ssize_t i, j, n, n_t, n_alloc, start, end, na_idx - target_vals = targets._data - target_mask = targets._mask + target_vals = self._get_data(targets) + target_mask = self._get_mask(targets) values = self.values assert not values.dtype == object # go through object path instead diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 5e67a2c92cccb..894dc75e351a4 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -11,6 +11,7 @@ TypeVar, cast, ) +import warnings import numpy as np @@ -890,7 +891,10 @@ def to_numpy( mask = ~self.isna() result[mask] = np.asarray(self[mask]._data) else: - result = np.asarray(self._data, dtype=dtype) + with warnings.catch_warnings(): + # int dtype with NA raises Warning + warnings.filterwarnings("ignore", category=RuntimeWarning) + result = np.asarray(self._data, dtype=dtype) if copy or self._hasna: result = result.copy() if self._hasna: diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 424cbf12c99cc..bd631c0c0d948 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -221,6 +221,19 @@ "Int16": libindex.MaskedInt16Engine, "Int8": libindex.MaskedInt8Engine, "boolean": libindex.MaskedBoolEngine, + "double[pyarrow]": libindex.MaskedFloat64Engine, + "float64[pyarrow]": libindex.MaskedFloat64Engine, + "float32[pyarrow]": libindex.MaskedFloat32Engine, + "float[pyarrow]": libindex.MaskedFloat32Engine, + "uint64[pyarrow]": libindex.MaskedUInt64Engine, + "uint32[pyarrow]": libindex.MaskedUInt32Engine, + "uint16[pyarrow]": libindex.MaskedUInt16Engine, + "uint8[pyarrow]": libindex.MaskedUInt8Engine, + "int64[pyarrow]": libindex.MaskedInt64Engine, + "int32[pyarrow]": libindex.MaskedInt32Engine, + "int16[pyarrow]": libindex.MaskedInt16Engine, + "int8[pyarrow]": libindex.MaskedInt8Engine, + "bool[pyarrow]": libindex.MaskedBoolEngine, } @@ -796,7 +809,7 @@ def _engine( # For base class (object dtype) we get ObjectEngine target_values = self._get_engine_target() if isinstance(target_values, ExtensionArray): - if isinstance(target_values, BaseMaskedArray): + if isinstance(target_values, (BaseMaskedArray, ArrowExtensionArray)): return _masked_engines[target_values.dtype.name](target_values) elif self._engine_type is libindex.ObjectEngine: return libindex.ExtensionEngine(target_values) @@ -4932,6 +4945,10 @@ def _get_engine_target(self) -> ArrayLike: type(self) is Index and isinstance(self._values, ExtensionArray) and not isinstance(self._values, BaseMaskedArray) + and not ( + isinstance(self._values, ArrowExtensionArray) + and is_numeric_dtype(self.dtype) + ) ): # TODO(ExtensionIndex): remove special-case, just use self._values return self._values.astype(object) diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py index eec1df8b44f33..c99e912ce4c0f 100644 --- a/pandas/tests/indexes/numeric/test_indexing.py +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -317,26 +317,26 @@ def test_get_indexer_uint64(self, index_large): tm.assert_numpy_array_equal(indexer, expected) @pytest.mark.parametrize("val, val2", [(4, 5), (4, 4), (4, NA), (NA, NA)]) - def test_get_loc_masked(self, val, val2, any_numeric_ea_dtype): + def test_get_loc_masked(self, val, val2, any_numeric_ea_and_arrow_dtype): # GH#39133 - idx = Index([1, 2, 3, val, val2], dtype=any_numeric_ea_dtype) + idx = Index([1, 2, 3, val, val2], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_loc(2) assert result == 1 with pytest.raises(KeyError, match="9"): idx.get_loc(9) - def test_get_loc_masked_na(self, any_numeric_ea_dtype): + def test_get_loc_masked_na(self, any_numeric_ea_and_arrow_dtype): # GH#39133 - idx = Index([1, 2, NA], dtype=any_numeric_ea_dtype) + idx = Index([1, 2, NA], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_loc(NA) assert result == 2 - idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_dtype) + idx = Index([1, 2, NA, NA], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_loc(NA) tm.assert_numpy_array_equal(result, np.array([False, False, True, True])) - idx = Index([1, 2, 3], dtype=any_numeric_ea_dtype) + idx = Index([1, 2, 3], dtype=any_numeric_ea_and_arrow_dtype) with pytest.raises(KeyError, match="NA"): idx.get_loc(NA) @@ -371,16 +371,19 @@ def test_get_loc_masked_na_and_nan(self): idx.get_loc(NA) @pytest.mark.parametrize("val", [4, 2]) - def test_get_indexer_masked_na(self, any_numeric_ea_dtype, val): + def test_get_indexer_masked_na(self, any_numeric_ea_and_arrow_dtype, val): # GH#39133 - idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_dtype) + idx = Index([1, 2, NA, 3, val], dtype=any_numeric_ea_and_arrow_dtype) result = idx.get_indexer_for([1, NA, 5]) expected = np.array([0, 2, -1]) tm.assert_numpy_array_equal(result, expected, check_dtype=False) - def test_get_indexer_masked_na_boolean(self): + @pytest.mark.parametrize("dtype", ["boolean", "bool[pyarrow]"]) + def test_get_indexer_masked_na_boolean(self, dtype): # GH#39133 - idx = Index([True, False, NA], dtype="boolean") + if dtype == "bool[pyarrow]": + pytest.importorskip("pyarrow") + idx = Index([True, False, NA], dtype=dtype) result = idx.get_loc(False) assert result == 1 result = idx.get_loc(NA)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. ``` idx = pd.Index(list(range(1_000_000)), dtype="int64[pyarrow]") idxer = list(range(1, 500_000, 10)) pr %timeit idx.get_indexer(idxer) 4.85 ms ± 24.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) main %timeit idx.get_indexer(idxer) 16.9 ms ± 116 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ``` cc @mroeschke Is this roughly what you had in mind?
https://api.github.com/repos/pandas-dev/pandas/pulls/51316
2023-02-10T23:23:46Z
2023-02-16T23:59:09Z
2023-02-16T23:59:09Z
2023-02-16T23:59:13Z
CLN: Move DeepChainMap to only location used
diff --git a/pandas/compat/chainmap.py b/pandas/compat/chainmap.py deleted file mode 100644 index 5bec8e5fa1913..0000000000000 --- a/pandas/compat/chainmap.py +++ /dev/null @@ -1,37 +0,0 @@ -from __future__ import annotations - -from typing import ( - ChainMap, - TypeVar, -) - -_KT = TypeVar("_KT") -_VT = TypeVar("_VT") - - -class DeepChainMap(ChainMap[_KT, _VT]): - """ - Variant of ChainMap that allows direct updates to inner scopes. - - Only works when all passed mapping are mutable. - """ - - def __setitem__(self, key: _KT, value: _VT) -> None: - for mapping in self.maps: - if key in mapping: - mapping[key] = value - return - self.maps[0][key] = value - - def __delitem__(self, key: _KT) -> None: - """ - Raises - ------ - KeyError - If `key` doesn't exist. - """ - for mapping in self.maps: - if key in mapping: - del mapping[key] - return - raise KeyError(key) diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index f7d1314b12da2..ba3ff2e137857 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -3,10 +3,7 @@ import ast from functools import partial -from typing import ( - TYPE_CHECKING, - Any, -) +from typing import Any import numpy as np @@ -36,9 +33,6 @@ pprint_thing_encoded, ) -if TYPE_CHECKING: - from pandas.compat.chainmap import DeepChainMap - class PyTablesScope(_scope.Scope): __slots__ = ("queryables",) @@ -567,7 +561,7 @@ def __init__( self._visitor = None # capture the environment if needed - local_dict: DeepChainMap[Any, Any] | None = None + local_dict: _scope.DeepChainMap[Any, Any] | None = None if isinstance(where, PyTablesExpr): local_dict = where.env.scope diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 6d070540de26a..0b9ba84cae511 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -10,16 +10,51 @@ import pprint import struct import sys +from typing import ( + ChainMap, + TypeVar, +) import numpy as np from pandas._libs.tslibs import Timestamp -from pandas.compat.chainmap import DeepChainMap from pandas.errors import UndefinedVariableError +_KT = TypeVar("_KT") +_VT = TypeVar("_VT") + + +# https://docs.python.org/3/library/collections.html#chainmap-examples-and-recipes +class DeepChainMap(ChainMap[_KT, _VT]): + """ + Variant of ChainMap that allows direct updates to inner scopes. + + Only works when all passed mapping are mutable. + """ + + def __setitem__(self, key: _KT, value: _VT) -> None: + for mapping in self.maps: + if key in mapping: + mapping[key] = value + return + self.maps[0][key] = value + + def __delitem__(self, key: _KT) -> None: + """ + Raises + ------ + KeyError + If `key` doesn't exist. + """ + for mapping in self.maps: + if key in mapping: + del mapping[key] + return + raise KeyError(key) + def ensure_scope( - level: int, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs + level: int, global_dict=None, local_dict=None, resolvers=(), target=None ) -> Scope: """Ensure that we are grabbing the correct scope.""" return Scope(
null
https://api.github.com/repos/pandas-dev/pandas/pulls/51314
2023-02-10T22:17:04Z
2023-02-11T04:50:59Z
2023-02-11T04:50:59Z
2023-02-11T04:51:03Z
CI/TST: Enable -W error:::pandas in pyproject.toml
diff --git a/.github/workflows/macos-windows.yml b/.github/workflows/macos-windows.yml index 7446ec00a87c9..bc6ecd7c5e5d0 100644 --- a/.github/workflows/macos-windows.yml +++ b/.github/workflows/macos-windows.yml @@ -18,8 +18,6 @@ env: PANDAS_CI: 1 PYTEST_TARGET: pandas PATTERN: "not slow and not db and not network and not single_cpu" - ERROR_ON_WARNINGS: "1" - permissions: contents: read diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index efcf270d77760..7b31c5392849b 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -40,7 +40,6 @@ jobs: - name: "Minimum Versions" env_file: actions-38-minimum_versions.yaml pattern: "not slow and not network and not single_cpu" - error_on_warnings: "0" - name: "Locale: it_IT" env_file: actions-38.yaml pattern: "not slow and not network and not single_cpu" @@ -65,12 +64,10 @@ jobs: env_file: actions-310.yaml pattern: "not slow and not network and not single_cpu" pandas_copy_on_write: "1" - error_on_warnings: "0" - name: "Data Manager" env_file: actions-38.yaml pattern: "not slow and not network and not single_cpu" pandas_data_manager: "array" - error_on_warnings: "0" - name: "Pypy" env_file: actions-pypy-38.yaml pattern: "not slow and not network and not single_cpu" @@ -79,7 +76,6 @@ jobs: env_file: actions-310-numpydev.yaml pattern: "not slow and not network and not single_cpu" test_args: "-W error::DeprecationWarning -W error::FutureWarning" - error_on_warnings: "0" exclude: - env_file: actions-38.yaml pyarrow_version: "8" @@ -99,7 +95,6 @@ jobs: ENV_FILE: ci/deps/${{ matrix.env_file }} PATTERN: ${{ matrix.pattern }} EXTRA_APT: ${{ matrix.extra_apt || '' }} - ERROR_ON_WARNINGS: ${{ matrix.error_on_warnings || '1' }} LANG: ${{ matrix.lang || '' }} LC_ALL: ${{ matrix.lc_all || '' }} PANDAS_DATA_MANAGER: ${{ matrix.pandas_data_manager || 'block' }} diff --git a/ci/run_tests.sh b/ci/run_tests.sh index a48d6c1ad6580..e6de5caf955fc 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -30,13 +30,6 @@ if [[ "$PATTERN" ]]; then PYTEST_CMD="$PYTEST_CMD -m \"$PATTERN\"" fi -if [[ "$ERROR_ON_WARNINGS" == "1" ]]; then - for pth in $(find pandas -name '*.py' -not -path "pandas/tests/*" | sed -e 's/\.py//g' -e 's/\/__init__//g' -e 's/\//./g'); - do - PYTEST_CMD="$PYTEST_CMD -W error:::$pth" - done -fi - echo $PYTEST_CMD sh -c "$PYTEST_CMD" diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py index 0d1076f235b1d..201aa81183301 100644 --- a/pandas/_testing/_warnings.py +++ b/pandas/_testing/_warnings.py @@ -5,6 +5,7 @@ nullcontext, ) import re +import sys from typing import ( Generator, Literal, @@ -163,6 +164,17 @@ def _assert_caught_no_extra_warnings( for actual_warning in caught_warnings: if _is_unexpected_warning(actual_warning, expected_warning): + # GH#38630 pytest.filterwarnings does not suppress these. + if actual_warning.category == ResourceWarning: + # GH 44732: Don't make the CI flaky by filtering SSL-related + # ResourceWarning from dependencies + if "unclosed <ssl.SSLSocket" in str(actual_warning.message): + continue + # GH 44844: Matplotlib leaves font files open during the entire process + # upon import. Don't make CI flaky if ResourceWarning raised + # due to these open files. + if any("matplotlib" in mod for mod in sys.modules): + continue extra_warnings.append( ( actual_warning.category.__name__, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0e050cdbdeea0..ec1509d67596e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4015,10 +4015,10 @@ class animal locomotion Get values at several indexes - >>> df.xs(('mammal', 'dog')) - num_legs num_wings - locomotion - walks 4 0 + >>> df.xs(('mammal', 'dog', 'walks')) + num_legs 4 + num_wings 0 + Name: (mammal, dog, walks), dtype: int64 Get values at specified index and level diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 4e86166ef512d..7dedd705f8c70 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -632,36 +632,9 @@ def read_sql( >>> pd.read_sql('test_data', 'postgres:///db_name') # doctest:+SKIP Apply date parsing to columns through the ``parse_dates`` argument - - >>> pd.read_sql('SELECT int_column, date_column FROM test_data', - ... conn, - ... parse_dates=["date_column"]) - int_column date_column - 0 0 2012-10-11 - 1 1 2010-12-11 - The ``parse_dates`` argument calls ``pd.to_datetime`` on the provided columns. Custom argument values for applying ``pd.to_datetime`` on a column are specified via a dictionary format: - 1. Ignore errors while parsing the values of "date_column" - - >>> pd.read_sql('SELECT int_column, date_column FROM test_data', - ... conn, - ... parse_dates={"date_column": {"errors": "ignore"}}) - int_column date_column - 0 0 2012-10-11 - 1 1 2010-12-11 - - 2. Apply a dayfirst date parsing order on the values of "date_column" - - >>> pd.read_sql('SELECT int_column, date_column FROM test_data', - ... conn, - ... parse_dates={"date_column": {"dayfirst": True}}) - int_column date_column - 0 0 2012-11-10 - 1 1 2010-11-12 - - 3. Apply custom formatting when date parsing the values of "date_column" >>> pd.read_sql('SELECT int_column, date_column FROM test_data', ... conn, diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 7abc8e5eb92cc..fc0c81339de08 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -1332,7 +1332,9 @@ def test_query_ea_dtypes(self, dtype): # GH#50261 df = DataFrame({"a": Series([1, 2], dtype=dtype)}) ref = {2} # noqa:F841 - result = df.query("a in @ref") + warning = RuntimeWarning if dtype == "Int64" and NUMEXPR_INSTALLED else None + with tm.assert_produces_warning(warning): + result = df.query("a in @ref") expected = DataFrame({"a": Series([2], dtype=dtype, index=[1])}) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index d969ce4a2bb71..42ecdb611576b 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2774,6 +2774,9 @@ def test_sum_of_booleans(n): tm.assert_frame_equal(result, expected) +@pytest.mark.filterwarnings( + "ignore:invalid value encountered in remainder:RuntimeWarning" +) @pytest.mark.parametrize("method", ["head", "tail", "nth", "first", "last"]) def test_groupby_method_drop_na(method): # GH 21755 diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index cf1537b42bc9f..874b37120cc23 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -789,6 +789,9 @@ def test_nth_slices_with_column_axis( tm.assert_frame_equal(result, expected) +@pytest.mark.filterwarnings( + "ignore:invalid value encountered in remainder:RuntimeWarning" +) def test_head_tail_dropna_true(): # GH#45089 df = DataFrame( diff --git a/pandas/tests/io/pytables/test_retain_attributes.py b/pandas/tests/io/pytables/test_retain_attributes.py index 67e864591626c..8ca8e624a6de2 100644 --- a/pandas/tests/io/pytables/test_retain_attributes.py +++ b/pandas/tests/io/pytables/test_retain_attributes.py @@ -1,5 +1,3 @@ -from warnings import catch_warnings - import pytest from pandas._libs.tslibs import Timestamp @@ -9,6 +7,7 @@ Series, _testing as tm, date_range, + errors, read_hdf, ) from pandas.tests.io.pytables.common import ( @@ -39,7 +38,7 @@ def test_retain_index_attributes(setup_path): ) # try to append a table with a different frequency - with catch_warnings(record=True): + with tm.assert_produces_warning(errors.AttributeConflictWarning): df2 = DataFrame( { "A": Series( @@ -75,7 +74,7 @@ def test_retain_index_attributes(setup_path): def test_retain_index_attributes2(tmp_path, setup_path): path = tmp_path / setup_path - with catch_warnings(record=True): + with tm.assert_produces_warning(errors.AttributeConflictWarning): df = DataFrame( {"A": Series(range(3), index=date_range("2000-1-1", periods=3, freq="H"))} ) @@ -93,7 +92,7 @@ def test_retain_index_attributes2(tmp_path, setup_path): assert read_hdf(path, "data").index.name == "foo" - with catch_warnings(record=True): + with tm.assert_produces_warning(errors.AttributeConflictWarning): idx2 = date_range("2001-1-1", periods=3, freq="H") idx2.name = "bar" df2 = DataFrame({"A": Series(range(3), index=idx2)}) diff --git a/pandas/tests/io/sas/test_byteswap.py b/pandas/tests/io/sas/test_byteswap.py index 2c88907df3b1d..0ef4eeb54beb3 100644 --- a/pandas/tests/io/sas/test_byteswap.py +++ b/pandas/tests/io/sas/test_byteswap.py @@ -29,6 +29,7 @@ def test_int_byteswap(read_offset, number, int_type, should_byteswap): _test(number, int_type, read_offset, should_byteswap) +@pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning") @given(read_offset=st.integers(0, 11), number=st.floats()) @pytest.mark.parametrize("float_type", [np.float32, np.float64]) @pytest.mark.parametrize("should_byteswap", [True, False]) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index e4044feab1cbd..fa72bf4368b69 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -32,6 +32,7 @@ ops, ) from pandas.core.computation import expressions as expr +from pandas.core.computation.check import NUMEXPR_INSTALLED @pytest.fixture(autouse=True, params=[0, 1000000], ids=["numexpr", "python"]) @@ -349,14 +350,21 @@ def test_add_list_to_masked_array(self, val, dtype): result = [1, None, val] + ser tm.assert_series_equal(result, expected) - def test_add_list_to_masked_array_boolean(self): + def test_add_list_to_masked_array_boolean(self, request): # GH#22962 + warning = ( + UserWarning + if request.node.callspec.id == "numexpr" and NUMEXPR_INSTALLED + else None + ) ser = Series([True, None, False], dtype="boolean") - result = ser + [True, None, True] + with tm.assert_produces_warning(warning): + result = ser + [True, None, True] expected = Series([True, None, True], dtype="boolean") tm.assert_series_equal(result, expected) - result = [True, None, True] + ser + with tm.assert_produces_warning(warning): + result = [True, None, True] + ser tm.assert_series_equal(result, expected) diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index c241603fd7ff9..ec4f8893885f3 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -199,6 +199,9 @@ def test_invalid(self): result = expr._can_use_numexpr(operator.add, "+", array, array2, "evaluate") assert result + @pytest.mark.filterwarnings( + "ignore:invalid value encountered in true_divide:RuntimeWarning" + ) @pytest.mark.parametrize( "opname,op_str", [("add", "+"), ("sub", "-"), ("mul", "*"), ("truediv", "/"), ("pow", "**")], diff --git a/pyproject.toml b/pyproject.toml index 0de87ce9c0385..8c3d27b6bb5d3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -397,11 +397,14 @@ doctest_optionflags = [ "ELLIPSIS", ] filterwarnings = [ + "error:::pandas", "error::ResourceWarning", "error::pytest.PytestUnraisableExceptionWarning", "ignore:.*ssl.SSLSocket:pytest.PytestUnraisableExceptionWarning", - "ignore:unclosed <ssl.SSLSocket:ResourceWarning", + "ignore:.*ssl.SSLSocket:ResourceWarning", "ignore::ResourceWarning:asyncio", + # From plotting doctests + "ignore:More than 20 figures have been opened:RuntimeWarning", # Will be fixed in numba 0.56: https://github.com/numba/numba/issues/7758 "ignore:`np.MachAr` is deprecated:DeprecationWarning:numba", "ignore:.*urllib3:DeprecationWarning:botocore",
- [ ] closes #48553 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51312
2023-02-10T19:32:56Z
2023-02-22T23:30:53Z
2023-02-22T23:30:53Z
2023-02-22T23:53:02Z
REF: avoid try/except in _gotitem
diff --git a/pandas/core/resample.py b/pandas/core/resample.py index cb129ec272ff3..9053bbdecf237 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -394,15 +394,18 @@ def _gotitem(self, key, ndim: int, subset=None): grouper = self.grouper if subset is None: subset = self.obj + if key is not None: + subset = subset[key] + else: + # reached via Apply.agg_dict_like with selection=None and ndim=1 + assert subset.ndim == 1 + if ndim == 1: + assert subset.ndim == 1 + grouped = get_groupby( subset, by=None, grouper=grouper, axis=self.axis, group_keys=self.group_keys ) - - # try the key selection - try: - return grouped[key] - except KeyError: - return grouped + return grouped def _groupby_and_aggregate(self, how, *args, **kwargs): """ @@ -1214,6 +1217,11 @@ def _gotitem(self, key, ndim, subset=None): # create a new object to prevent aliasing if subset is None: subset = self.obj + if key is not None: + subset = subset[key] + else: + # reached via Apply.agg_dict_like with selection=None, ndim=1 + assert subset.ndim == 1 # Try to select from a DataFrame, falling back to a Series try: @@ -1228,6 +1236,8 @@ def _gotitem(self, key, ndim, subset=None): (lib.is_scalar(key) and key in subset) or lib.is_list_like(key) ): selection = key + elif subset.ndim == 1 and lib.is_scalar(key) and key == subset.name: + selection = key new_rs = type(self)( groupby=groupby, diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index ef0524e48f9e2..57ed10e798928 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -303,6 +303,8 @@ def _gotitem(self, key, ndim, subset=None): (is_scalar(key) and key in subset) or is_list_like(key) ): selection = key + elif subset.ndim == 1 and is_scalar(key) and key == subset.name: + selection = key new_win = type(self)(subset, selection=selection, **kwargs) return new_win
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51311
2023-02-10T18:52:20Z
2023-02-13T19:04:55Z
2023-02-13T19:04:55Z
2023-02-13T19:07:15Z
DOC: fix Series.name docstring, closes #42550
diff --git a/pandas/core/series.py b/pandas/core/series.py index a88dd224068ac..8aeda5c71966c 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -268,7 +268,7 @@ class Series(base.IndexOpsMixin, NDFrame): # type: ignore[misc] Data type for the output Series. If not specified, this will be inferred from `data`. See the :ref:`user guide <basics.dtypes>` for more usages. - name : str, optional + name : Hashable, default None The name to give to the Series. copy : bool, default False Copy input data. Only affects Series or 1d ndarray input. See examples.
- [x] closes #42550 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51310
2023-02-10T18:45:23Z
2023-02-11T04:53:46Z
2023-02-11T04:53:46Z
2023-02-11T16:20:19Z
TYP: try out TypeGuard
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index fbc577712d294..31d4274bb5f8d 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -1,6 +1,6 @@ # TODO(npdtypes): Many types specified here can be made more specific/accurate; # the more specific versions are specified in comments - +from decimal import Decimal from typing import ( Any, Callable, @@ -13,9 +13,12 @@ from typing import ( import numpy as np +from pandas._libs.interval import Interval +from pandas._libs.tslibs import Period from pandas._typing import ( ArrayLike, DtypeObj, + TypeGuard, npt, ) @@ -38,13 +41,13 @@ def infer_dtype(value: object, skipna: bool = ...) -> str: ... def is_iterator(obj: object) -> bool: ... def is_scalar(val: object) -> bool: ... def is_list_like(obj: object, allow_sets: bool = ...) -> 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_period(val: object) -> TypeGuard[Period]: ... +def is_interval(val: object) -> TypeGuard[Interval]: ... +def is_decimal(val: object) -> TypeGuard[Decimal]: ... +def is_complex(val: object) -> TypeGuard[complex]: ... +def is_bool(val: object) -> TypeGuard[bool | np.bool_]: ... +def is_integer(val: object) -> TypeGuard[int | np.integer]: ... +def is_float(val: object) -> TypeGuard[float]: ... def is_interval_array(values: np.ndarray) -> bool: ... def is_datetime64_array(values: np.ndarray) -> bool: ... def is_timedelta_or_timedelta64_array(values: np.ndarray) -> bool: ... diff --git a/pandas/_typing.py b/pandas/_typing.py index 9d64842373573..e299d5309a6b9 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -84,6 +84,11 @@ # Name "npt._ArrayLikeInt_co" is not defined [name-defined] NumpySorter = Optional[npt._ArrayLikeInt_co] # type: ignore[name-defined] + if sys.version_info >= (3, 10): + from typing import TypeGuard + else: + from typing_extensions import TypeGuard # pyright: reportUnusedImport = false + if sys.version_info >= (3, 11): from typing import Self else: @@ -91,6 +96,7 @@ else: npt: Any = None Self: Any = None + TypeGuard: Any = None HashableT = TypeVar("HashableT", bound=Hashable) diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index bdd26b315ed83..8b2916bf1ded9 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -25,6 +25,7 @@ overload, ) +import numpy as np from numpy import ndarray from pandas._libs.lib import ( @@ -215,7 +216,7 @@ def validate_clip_with_axis( ) -def validate_cum_func_with_skipna(skipna, args, kwargs, name) -> bool: +def validate_cum_func_with_skipna(skipna: bool, args, kwargs, name) -> bool: """ If this function is called via the 'numpy' library, the third parameter in its signature is 'dtype', which takes either a 'numpy' dtype or 'None', so @@ -224,6 +225,8 @@ def validate_cum_func_with_skipna(skipna, args, kwargs, name) -> bool: if not is_bool(skipna): args = (skipna,) + args skipna = True + elif isinstance(skipna, np.bool_): + skipna = bool(skipna) validate_cum_func(args, kwargs, fname=name) return skipna diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 8c537a5082585..bd3d4b57c6d63 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -2182,7 +2182,6 @@ def validate_periods(periods: int | float | None) -> int | None: periods = int(periods) elif not lib.is_integer(periods): raise TypeError(f"periods must be a number, got {periods}") - periods = cast(int, periods) return periods diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e9da7598d1ebc..aa43c53d3c56c 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -194,15 +194,9 @@ def maybe_box_native(value: Scalar | None | NAType) -> Scalar | None | NAType: scalar or Series """ if is_float(value): - # error: Argument 1 to "float" has incompatible type - # "Union[Union[str, int, float, bool], Union[Any, Timestamp, Timedelta, Any]]"; - # expected "Union[SupportsFloat, _SupportsIndex, str]" - value = float(value) # type: ignore[arg-type] + value = float(value) elif is_integer(value): - # error: Argument 1 to "int" has incompatible type - # "Union[Union[str, int, float, bool], Union[Any, Timestamp, Timedelta, Any]]"; - # expected "Union[str, SupportsInt, _SupportsIndex, _SupportsTrunc]" - value = int(value) # type: ignore[arg-type] + value = int(value) elif is_bool(value): value = bool(value) elif isinstance(value, (np.datetime64, np.timedelta64)): diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index 28e034de869f4..af4f0a1c0aa05 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -5,12 +5,19 @@ from collections import abc from numbers import Number import re -from typing import Pattern +from typing import ( + TYPE_CHECKING, + Hashable, + Pattern, +) import numpy as np from pandas._libs import lib +if TYPE_CHECKING: + from pandas._typing import TypeGuard + is_bool = lib.is_bool is_integer = lib.is_integer @@ -30,7 +37,7 @@ is_iterator = lib.is_iterator -def is_number(obj) -> bool: +def is_number(obj) -> TypeGuard[Number | np.number]: """ Check if the object is a number. @@ -132,7 +139,7 @@ def is_file_like(obj) -> bool: return bool(hasattr(obj, "__iter__")) -def is_re(obj) -> bool: +def is_re(obj) -> TypeGuard[Pattern]: """ Check if the object is a regex pattern instance. @@ -325,7 +332,7 @@ def is_named_tuple(obj) -> bool: return isinstance(obj, abc.Sequence) and hasattr(obj, "_fields") -def is_hashable(obj) -> bool: +def is_hashable(obj) -> TypeGuard[Hashable]: """ Return True if hash(obj) will succeed, False otherwise. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ce4c3d81c4f90..93edb93781ba3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9501,11 +9501,7 @@ def melt( ) def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: if not lib.is_integer(periods): - if not ( - is_float(periods) - # error: "int" has no attribute "is_integer" - and periods.is_integer() # type: ignore[attr-defined] - ): + if not (is_float(periods) and periods.is_integer()): raise ValueError("periods must be an integer") periods = int(periods) @@ -10397,8 +10393,13 @@ def _series_round(ser: Series, decimals: int) -> Series: new_cols = list(_dict_round(self, decimals)) elif is_integer(decimals): # Dispatch to Block.round + # Argument "decimals" to "round" of "BaseBlockManager" has incompatible + # type "Union[int, integer[Any]]"; expected "int" return self._constructor( - self._mgr.round(decimals=decimals, using_cow=using_copy_on_write()), + self._mgr.round( + decimals=decimals, # type: ignore[arg-type] + using_cow=using_copy_on_write(), + ), ).__finalize__(self, method="round") else: raise TypeError("decimals must be an integer, a dict-like or a Series") diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 17e4a4c142f66..fa19aae674621 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4089,7 +4089,8 @@ class animal locomotion loc, new_index = index._get_loc_level(key, level=0) if not drop_level: if lib.is_integer(loc): - new_index = index[loc : loc + 1] + # Slice index must be an integer or None + new_index = index[loc : loc + 1] # type: ignore[misc] else: new_index = index[loc] else: diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index f880e1f10106d..4070b25767912 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -70,7 +70,11 @@ def get_objs_combined_axis( - objs, intersect: bool = False, axis: Axis = 0, sort: bool = True, copy: bool = False + objs, + intersect: bool = False, + axis: Axis = 0, + sort: bool = True, + copy: bool = False, ) -> Index: """ Extract combined index: return intersection or union (depending on the diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 37df3a7024626..c2dcd7389db5c 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2699,6 +2699,7 @@ def _partial_tup_index(self, tup: tuple, side: Literal["left", "right"] = "left" for k, (lab, lev, level_codes) in enumerate(zipped): section = level_codes[start:end] + loc: npt.NDArray[np.intp] | np.intp | int if lab not in lev and not isna(lab): # short circuit try: @@ -2930,7 +2931,8 @@ def get_loc_level(self, key, level: IndexLabel = 0, drop_level: bool = True): loc, mi = self._get_loc_level(key, level=level) if not drop_level: if lib.is_integer(loc): - mi = self[loc : loc + 1] + # Slice index must be an integer or None + mi = self[loc : loc + 1] # type: ignore[misc] else: mi = self[loc] return loc, mi diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index faa1e9658fa80..d92a3fe13e42f 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -298,9 +298,7 @@ def _maybe_convert_timedelta(self, other) -> int | npt.NDArray[np.int64]: raise raise_on_incompatible(self, other) elif is_integer(other): - # integer is passed to .shift via - # _add_datetimelike_methods basically - # but ufunc may pass integer to _add_delta + assert isinstance(other, int) return other # raise when input doesn't have freq diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 8db08fc15c0f4..1dac439ad9aea 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1562,7 +1562,7 @@ def _is_scalar_access(self, key: tuple) -> bool: return all(is_integer(k) for k in key) - def _validate_integer(self, key: int, axis: AxisInt) -> None: + def _validate_integer(self, key: int | np.integer, axis: AxisInt) -> None: """ Check that 'key' is a valid position in the desired axis. @@ -2171,7 +2171,7 @@ def _ensure_iterable_column_indexer(self, column_indexer): """ Ensure that our column indexer is something that can be iterated over. """ - ilocs: Sequence[int] | np.ndarray + ilocs: Sequence[int | np.integer] | np.ndarray if is_integer(column_indexer): ilocs = [column_indexer] elif isinstance(column_indexer, slice): diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index 650d51b896dc5..395db8060ce0e 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -391,6 +391,8 @@ class _Concatenator: Orchestrates a concatenation operation for BlockManagers """ + sort: bool + def __init__( self, objs: Iterable[NDFrame] | Mapping[HashableT, NDFrame], @@ -555,7 +557,9 @@ def __init__( raise ValueError( f"The 'sort' keyword only accepts boolean values; {sort} was passed." ) - self.sort = sort + # Incompatible types in assignment (expression has type "Union[bool, bool_]", + # variable has type "bool") + self.sort = sort # type: ignore[assignment] self.ignore_index = ignore_index self.verify_integrity = verify_integrity diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 21ce1d3c96379..d2b022214167f 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -2026,7 +2026,8 @@ def _get_merge_keys( elif is_float_dtype(lt): if not is_number(self.tolerance): raise MergeError(msg) - if self.tolerance < 0: + # error: Unsupported operand types for > ("int" and "Number") + if self.tolerance < 0: # type: ignore[operator] raise MergeError("tolerance must be positive") else: diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b11ff11421ed4..ed0de80e381c3 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1402,7 +1402,7 @@ def _generate_cython_apply_func( self, args: tuple[Any, ...], kwargs: dict[str, Any], - raw: bool, + raw: bool | np.bool_, function: Callable[..., Any], ) -> Callable[[np.ndarray, np.ndarray, np.ndarray, int], np.ndarray]: from pandas import Series diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 315d18d052d9f..d8c9ece3b2cce 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -1348,4 +1348,5 @@ def _validate_skipfooter_arg(skipfooter: int) -> int: if skipfooter < 0: raise ValueError("skipfooter cannot be negative") - return skipfooter + # Incompatible return value type (got "Union[int, integer[Any]]", expected "int") + return skipfooter # type: ignore[return-value] diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 8d48d04c738e8..ec04a9ce81d92 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -44,7 +44,6 @@ from pandas.core.dtypes.common import ( is_datetime64tz_dtype, is_dict_like, - is_integer, is_list_like, ) from pandas.core.dtypes.dtypes import DatetimeTZDtype @@ -1022,7 +1021,7 @@ def insert( chunk_iter = zip(*(arr[start_i:end_i] for arr in data_list)) num_inserted = exec_insert(conn, keys, chunk_iter) # GH 46891 - if is_integer(num_inserted): + if num_inserted is not None: if total_inserted is None: total_inserted = num_inserted else: diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index dc51a5b0a77fb..3d79d483038ee 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -775,7 +775,7 @@ def psql_insert_copy(table, conn, keys, data_iter): "test_frame", conn, index=False, method=psql_insert_copy ) # GH 46891 - if not isinstance(expected_count, int): + if expected_count is None: assert result_count is None else: assert result_count == expected_count diff --git a/pandas/util/_validators.py b/pandas/util/_validators.py index 17ef583febc24..f03d1ceb507fd 100644 --- a/pandas/util/_validators.py +++ b/pandas/util/_validators.py @@ -250,7 +250,7 @@ def validate_bool_kwarg( """ good_value = is_bool(value) if none_allowed: - good_value = good_value or value is None + good_value = good_value or (value is None) if int_allowed: good_value = good_value or isinstance(value, int) @@ -260,7 +260,7 @@ def validate_bool_kwarg( f'For argument "{arg_name}" expected type bool, received ' f"type {type(value).__name__}." ) - return value + return value # pyright: ignore[reportGeneralTypeIssues] def validate_fillna_kwargs(value, method, validate_scalar_dict_value: bool = True): @@ -438,7 +438,7 @@ def validate_insert_loc(loc: int, length: int) -> int: loc += length if not 0 <= loc <= length: raise IndexError(f"loc must be an integer between -{length} and {length}") - return loc + return loc # pyright: ignore[reportGeneralTypeIssues] def check_dtype_backend(dtype_backend) -> None:
This effectively makes mypy understand that `is_integer(obj)` is equivalent to `isinstance(obj, (int, np.integer))`. This is a mixed bag. It allows for getting rid of some redundant casts/ignores, but makes some new ones necessary. I'd be fine either way on this.
https://api.github.com/repos/pandas-dev/pandas/pulls/51309
2023-02-10T18:36:27Z
2023-03-16T20:14:30Z
2023-03-16T20:14:30Z
2023-03-16T20:32:47Z
CI: Add pyarrow 11 to ci
diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index cb07c67dda2df..fc7c3cd5f4b32 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -29,7 +29,7 @@ jobs: matrix: env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml, actions-311.yaml] pattern: ["not single_cpu", "single_cpu"] - pyarrow_version: ["8", "9", "10"] + pyarrow_version: ["8", "9", "10", "11"] include: - name: "Downstream Compat" env_file: actions-38-downstream_compat.yaml @@ -83,14 +83,20 @@ jobs: pyarrow_version: "8" - env_file: actions-38.yaml pyarrow_version: "9" + - env_file: actions-38.yaml + pyarrow_version: "10" - env_file: actions-39.yaml pyarrow_version: "8" - env_file: actions-39.yaml pyarrow_version: "9" + - env_file: actions-39.yaml + pyarrow_version: "10" - env_file: actions-310.yaml pyarrow_version: "8" - env_file: actions-310.yaml pyarrow_version: "9" + - env_file: actions-310.yaml + pyarrow_version: "10" fail-fast: false name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }} env:
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51308
2023-02-10T18:33:41Z
2023-03-31T17:45:36Z
null
2023-04-27T19:53:41Z
API: ArrowDtype.type
diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 3a3f0b8ce61be..18caee3249d32 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -506,6 +506,18 @@ def __len__(self) -> int: """ return len(self._data) + def __contains__(self, key) -> bool: + # https://github.com/pandas-dev/pandas/pull/51307#issuecomment-1426372604 + if isna(key) and key is not self.dtype.na_value: + if self.dtype.kind == "f" and lib.is_float(key) and isna(key): + return pc.any(pc.is_nan(self._data)).as_py() + + # e.g. date or timestamp types we do not allow None here to match pd.NA + return False + # TODO: maybe complex? object? + + return bool(super().__contains__(key)) + @property def _hasna(self) -> bool: return self._data.null_count > 0 diff --git a/pandas/core/arrays/arrow/dtype.py b/pandas/core/arrays/arrow/dtype.py index 90c86cd6d55ef..331e66698cc35 100644 --- a/pandas/core/arrays/arrow/dtype.py +++ b/pandas/core/arrays/arrow/dtype.py @@ -1,9 +1,20 @@ from __future__ import annotations +from datetime import ( + date, + datetime, + time, + timedelta, +) +from decimal import Decimal import re import numpy as np +from pandas._libs.tslibs import ( + Timedelta, + Timestamp, +) from pandas._typing import ( TYPE_CHECKING, DtypeObj, @@ -88,9 +99,40 @@ def __repr__(self) -> str: @property def type(self): """ - Returns pyarrow.DataType. + Returns associated scalar type. """ - return type(self.pyarrow_dtype) + pa_type = self.pyarrow_dtype + if pa.types.is_integer(pa_type): + return int + elif pa.types.is_floating(pa_type): + return float + elif pa.types.is_string(pa_type): + return str + elif pa.types.is_binary(pa_type): + return bytes + elif pa.types.is_boolean(pa_type): + return bool + elif pa.types.is_duration(pa_type): + if pa_type.unit == "ns": + return Timedelta + else: + return timedelta + elif pa.types.is_timestamp(pa_type): + if pa_type.unit == "ns": + return Timestamp + else: + return datetime + elif pa.types.is_date(pa_type): + return date + elif pa.types.is_time(pa_type): + return time + elif pa.types.is_decimal(pa_type): + return Decimal + elif pa.types.is_null(pa_type): + # TODO: None? pd.NA? pa.null? + return type(pa_type) + else: + raise NotImplementedError(pa_type) @property def name(self) -> str: # type: ignore[override] diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 60d022a0c7964..55afa95129e83 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -15,7 +15,6 @@ import numpy as np from pandas._libs import ( - Timestamp, internals as libinternals, lib, writers, @@ -63,6 +62,7 @@ is_string_dtype, ) from pandas.core.dtypes.dtypes import ( + DatetimeTZDtype, ExtensionDtype, PandasDtype, PeriodDtype, @@ -2232,9 +2232,8 @@ def get_block_type(dtype: DtypeObj): ------- cls : class, subclass of Block """ - # We use vtype and kind checks because they are much more performant + # We use kind checks because it is much more performant # than is_foo_dtype - vtype = dtype.type kind = dtype.kind cls: type[Block] @@ -2242,7 +2241,7 @@ def get_block_type(dtype: DtypeObj): if isinstance(dtype, SparseDtype): # Need this first(ish) so that Sparse[datetime] is sparse cls = ExtensionBlock - elif vtype is Timestamp: + elif isinstance(dtype, DatetimeTZDtype): cls = DatetimeTZBlock elif isinstance(dtype, PeriodDtype): cls = NDArrayBackedExtensionBlock diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 681d048f38485..27b30fd6aab6f 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -323,39 +323,7 @@ def test_from_sequence_of_strings_pa_array(self, data, request): class TestGetitemTests(base.BaseGetitemTests): - def test_getitem_scalar(self, data): - # In the base class we expect data.dtype.type; but this (intentionally) - # returns Python scalars or pd.NA - pa_type = data._data.type - if pa.types.is_integer(pa_type): - exp_type = int - elif pa.types.is_floating(pa_type): - exp_type = float - elif pa.types.is_string(pa_type): - exp_type = str - elif pa.types.is_binary(pa_type): - exp_type = bytes - elif pa.types.is_boolean(pa_type): - exp_type = bool - elif pa.types.is_duration(pa_type): - exp_type = timedelta - elif pa.types.is_timestamp(pa_type): - if pa_type.unit == "ns": - exp_type = pd.Timestamp - else: - exp_type = datetime - elif pa.types.is_date(pa_type): - exp_type = date - elif pa.types.is_time(pa_type): - exp_type = time - else: - raise NotImplementedError(data.dtype) - - result = data[0] - assert isinstance(result, exp_type), type(result) - - result = pd.Series(data)[0] - assert isinstance(result, exp_type), type(result) + pass class TestBaseAccumulateTests(base.BaseAccumulateTests):
cc @mroeschke we discussed this one of the pyarrow testing PRs. Still has some failing `pandas/tests/extension/test_arrow.py::TestBaseInterface::test_contains` tests where eyeballs would be welcome. ATM this returns Timestamp/Timedelta when the pyarrow unit is "ns" and pydatetime/pydatetime otherwise. We could reasonably update that to be always-Timestamp/Timedelta.
https://api.github.com/repos/pandas-dev/pandas/pulls/51307
2023-02-10T18:28:59Z
2023-02-16T16:38:33Z
2023-02-16T16:38:33Z
2023-02-16T16:46:43Z
DOC: fix EX02 errors in docstrings
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 17ad347d58fdf..9830e5d92f8d4 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -593,8 +593,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.api.types.is_datetime64_dtype \ pandas.api.types.is_datetime64_ns_dtype \ pandas.api.types.is_datetime64tz_dtype \ - pandas.api.types.is_float_dtype \ - pandas.api.types.is_int64_dtype \ pandas.api.types.is_integer_dtype \ pandas.api.types.is_interval_dtype \ pandas.api.types.is_numeric_dtype \ diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index ce6ed6ca60238..8ff9040d8e224 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -832,6 +832,7 @@ def is_int64_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_int64_dtype >>> is_int64_dtype(str) False >>> is_int64_dtype(np.int32) @@ -1216,6 +1217,7 @@ def is_float_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_float_dtype >>> is_float_dtype(str) False >>> is_float_dtype(int)
- Related to issue #51236 This PR enables functions: `pandas.api.types.is_float_dtype` `pandas.api.types.is_int64_dtype`
https://api.github.com/repos/pandas-dev/pandas/pulls/51306
2023-02-10T18:23:18Z
2023-02-11T04:52:22Z
2023-02-11T04:52:22Z
2023-02-11T04:52:29Z
BUG: idxmax and idxmin raising for all na ea series
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index d1bc322a6ec7a..eb72bee265c1b 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1256,6 +1256,7 @@ Missing - Bug in :meth:`DataFrame.update` with ``overwrite=False`` raising ``TypeError`` when ``self`` has column with ``NaT`` values and column not present in ``other`` (:issue:`16713`) - Bug in :meth:`Series.replace` raising ``RecursionError`` when replacing value in object-dtype :class:`Series` containing ``NA`` (:issue:`47480`) - Bug in :meth:`Series.replace` raising ``RecursionError`` when replacing value in numeric :class:`Series` with ``NA`` (:issue:`50758`) +- Bug in :meth:`Series.idxmin` and :meth:`Series.idxmax` raising ``ValueError`` for all ``NA`` with extension array dtype (:issue:`51276`) MultiIndex ^^^^^^^^^^ diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index b28a9def8a7ea..807afb1ff9d61 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -461,6 +461,8 @@ def nargminmax(values: ExtensionArray, method: str, axis: AxisInt = 0): func = np.argmax if method == "argmax" else np.argmin mask = np.asarray(isna(values)) + if mask.all(): + return -1 arr_values = values._values_for_argsort() if arr_values.ndim > 1: diff --git a/pandas/tests/series/methods/test_argsort.py b/pandas/tests/series/methods/test_argsort.py index 1fbc9ed787e11..ba5800c5dd315 100644 --- a/pandas/tests/series/methods/test_argsort.py +++ b/pandas/tests/series/methods/test_argsort.py @@ -65,3 +65,10 @@ def test_argsort_stable(self): def test_argsort_preserve_name(self, datetime_series): result = datetime_series.argsort() assert result.name == datetime_series.name + + @pytest.mark.parametrize("func", ["idxmin", "idxmax"]) + def test_idxmin_idxmax_all_na(self, any_numeric_ea_and_arrow_dtype, func): + # GH#51276 + ser = Series([None, None], dtype=any_numeric_ea_and_arrow_dtype) + result = getattr(ser, func)() + assert result is np.nan
- [x] closes #51276 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Not sure if NA or NaN makes more sense. I think we have a couple of ops where we return nan even for ea dtypes when the result is a scalar
https://api.github.com/repos/pandas-dev/pandas/pulls/51305
2023-02-10T17:42:57Z
2023-02-23T14:31:20Z
null
2023-08-28T21:09:51Z
ENH: Do unique check before computing indexer in reindex
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 363bfe76d40fb..4e7b64efe7819 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4217,17 +4217,11 @@ def reindex( ) elif self._is_multi: raise ValueError("cannot handle a non-unique multi-index!") - else: - if method is not None or limit is not None: - raise ValueError( - "cannot reindex a non-unique index " - "with a method or limit" - ) - indexer, _ = self.get_indexer_non_unique(target) - - if not self.is_unique: + elif not self.is_unique: # GH#42568 raise ValueError("cannot reindex on an axis with duplicate labels") + else: + indexer, _ = self.get_indexer_non_unique(target) target = self._wrap_reindex_result(target, indexer, preserve_names) return target, indexer
- [x] closes #51287 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51304
2023-02-10T17:25:20Z
2023-02-14T20:58:08Z
2023-02-14T20:58:08Z
2024-02-26T03:50:56Z
TST: Test mask/where inplace don't modify views with CoW
diff --git a/pandas/tests/copy_view/test_replace.py b/pandas/tests/copy_view/test_replace.py index a1347d8e12950..de7278dca06ff 100644 --- a/pandas/tests/copy_view/test_replace.py +++ b/pandas/tests/copy_view/test_replace.py @@ -1,4 +1,5 @@ import numpy as np +import pytest from pandas import ( Categorical, @@ -12,7 +13,7 @@ def test_replace_categorical_inplace_reference(using_copy_on_write): df = DataFrame({"a": Categorical([1, 2, 3])}) df_orig = df.copy() arr_a = get_array(df, "a") - view = df[:] # noqa + view = df[:] df.replace(to_replace=[1], value=2, inplace=True) if using_copy_on_write: @@ -27,7 +28,7 @@ def test_replace_categorical_inplace_reference(using_copy_on_write): def test_replace_inplace_reference(using_copy_on_write): df = DataFrame({"a": [1.5, 2, 3]}) arr_a = get_array(df, "a") - view = df[:] # noqa + view = df[:] df.replace(to_replace=[1.5], value=15.5, inplace=True) if using_copy_on_write: @@ -36,3 +37,22 @@ def test_replace_inplace_reference(using_copy_on_write): assert view._mgr._has_no_reference(0) else: assert np.shares_memory(get_array(df, "a"), arr_a) + + +@pytest.mark.parametrize("method", ["where", "mask"]) +def test_masking_inplace(using_copy_on_write, method): + df = DataFrame({"a": [1.5, 2, 3]}) + df_orig = df.copy() + arr_a = get_array(df, "a") + view = df[:] + + method = getattr(df, method) + method(df["a"] > 1.6, -1, inplace=True) + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), arr_a) + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(get_array(df, "a"), arr_a)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51303
2023-02-10T16:55:55Z
2023-02-10T21:19:11Z
2023-02-10T21:19:11Z
2023-02-10T22:27:04Z
ENH: Enable more Arrow CSV tests/features
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index c927dc2ac4a96..200ba9af508b6 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -270,6 +270,7 @@ Other enhancements - :func:`to_datetime` now accepts ``"mixed"`` as an argument to ``format``, which will infer the format for each element individually (:issue:`50972`) - Added new argument ``engine`` to :func:`read_json` to support parsing JSON with pyarrow by specifying ``engine="pyarrow"`` (:issue:`48893`) - Added support for SQLAlchemy 2.0 (:issue:`40686`) +- Added support for ``decimal`` parameter when ``engine="pyarrow"`` in :func:`read_csv` (:issue:`51302`) - :class:`Index` set operations :meth:`Index.union`, :meth:`Index.intersection`, :meth:`Index.difference`, and :meth:`Index.symmetric_difference` now support ``sort=True``, which will always return a sorted result, unlike the default ``sort=None`` which does not sort in some cases (:issue:`25151`) - Added new escape mode "latex-math" to avoid escaping "$" in formatter (:issue:`50040`) @@ -1287,6 +1288,7 @@ I/O - Bug in :meth:`DataFrame.to_json` where it would segfault when failing to encode a string (:issue:`50307`) - Bug in :meth:`DataFrame.to_html` with ``na_rep`` set when the :class:`DataFrame` contains non-scalar data (:issue:`47103`) - Bug in :func:`read_xml` where file-like objects failed when iterparse is used (:issue:`50641`) +- Bug in :func:`read_csv` when ``engine="pyarrow"`` where ``encoding`` parameter was not handled correctly (:issue:`51302`) - Bug in :func:`read_xml` ignored repeated elements when iterparse is used (:issue:`51183`) - Bug in :class:`ExcelWriter` leaving file handles open if an exception occurred during instantiation (:issue:`51443`) diff --git a/pandas/io/parsers/arrow_parser_wrapper.py b/pandas/io/parsers/arrow_parser_wrapper.py index 30fc65dca7ca1..a741a11332e99 100644 --- a/pandas/io/parsers/arrow_parser_wrapper.py +++ b/pandas/io/parsers/arrow_parser_wrapper.py @@ -54,6 +54,7 @@ def _get_pyarrow_options(self) -> None: "na_values": "null_values", "escapechar": "escape_char", "skip_blank_lines": "ignore_empty_lines", + "decimal": "decimal_point", } for pandas_name, pyarrow_name in mapping.items(): if pandas_name in self.kwds and self.kwds.get(pandas_name) is not None: @@ -71,13 +72,20 @@ def _get_pyarrow_options(self) -> None: for option_name, option_value in self.kwds.items() if option_value is not None and option_name - in ("include_columns", "null_values", "true_values", "false_values") + in ( + "include_columns", + "null_values", + "true_values", + "false_values", + "decimal_point", + ) } self.read_options = { "autogenerate_column_names": self.header is None, "skip_rows": self.header if self.header is not None else self.kwds["skiprows"], + "encoding": self.encoding, } def _finalize_pandas_output(self, frame: DataFrame) -> DataFrame: diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index 015f27ed4f2c4..df675a0a3a6cc 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -475,7 +475,6 @@ class _Fwf_Defaults(TypedDict): "quoting", "lineterminator", "converters", - "decimal", "iterator", "dayfirst", "verbose", diff --git a/pandas/tests/io/parser/common/test_decimal.py b/pandas/tests/io/parser/common/test_decimal.py index ab58ddff9c06e..72d4eb2c69845 100644 --- a/pandas/tests/io/parser/common/test_decimal.py +++ b/pandas/tests/io/parser/common/test_decimal.py @@ -9,9 +9,10 @@ from pandas import DataFrame import pandas._testing as tm -pytestmark = pytest.mark.usefixtures("pyarrow_skip") +xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +@xfail_pyarrow @pytest.mark.parametrize( "data,thousands,decimal", [ diff --git a/pandas/tests/io/parser/dtypes/test_categorical.py b/pandas/tests/io/parser/dtypes/test_categorical.py index a0deebecdfff8..33422d41c2f93 100644 --- a/pandas/tests/io/parser/dtypes/test_categorical.py +++ b/pandas/tests/io/parser/dtypes/test_categorical.py @@ -118,7 +118,6 @@ def test_categorical_dtype_high_cardinality_numeric(all_parsers): tm.assert_frame_equal(actual, expected) -@xfail_pyarrow def test_categorical_dtype_utf16(all_parsers, csv_dir_path): # see gh-10153 pth = os.path.join(csv_dir_path, "utf16_ex.txt") diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py index 775d5571c7a3d..f537c2f0681d7 100644 --- a/pandas/tests/io/parser/test_encoding.py +++ b/pandas/tests/io/parser/test_encoding.py @@ -20,9 +20,9 @@ import pandas._testing as tm skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") +xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") -@skip_pyarrow def test_bytes_io_input(all_parsers): encoding = "cp1255" parser = all_parsers @@ -44,7 +44,7 @@ def test_read_csv_unicode(all_parsers): tm.assert_frame_equal(result, expected) -@skip_pyarrow +@xfail_pyarrow @pytest.mark.parametrize("sep", [",", "\t"]) @pytest.mark.parametrize("encoding", ["utf-16", "utf-16le", "utf-16be"]) def test_utf16_bom_skiprows(all_parsers, sep, encoding): @@ -73,7 +73,6 @@ def test_utf16_bom_skiprows(all_parsers, sep, encoding): tm.assert_frame_equal(result, expected) -@skip_pyarrow def test_utf16_example(all_parsers, csv_dir_path): path = os.path.join(csv_dir_path, "utf16_ex.txt") parser = all_parsers @@ -81,7 +80,6 @@ def test_utf16_example(all_parsers, csv_dir_path): assert len(result) == 50 -@skip_pyarrow def test_unicode_encoding(all_parsers, csv_dir_path): path = os.path.join(csv_dir_path, "unicode_series.csv") parser = all_parsers @@ -94,7 +92,6 @@ def test_unicode_encoding(all_parsers, csv_dir_path): assert got == expected -@skip_pyarrow @pytest.mark.parametrize( "data,kwargs,expected", [ @@ -114,7 +111,7 @@ def test_unicode_encoding(all_parsers, csv_dir_path): ), ], ) -def test_utf8_bom(all_parsers, data, kwargs, expected): +def test_utf8_bom(all_parsers, data, kwargs, expected, request): # see gh-4793 parser = all_parsers bom = "\ufeff" @@ -124,11 +121,20 @@ def _encode_data_with_bom(_data): bom_data = (bom + _data).encode(utf8) return BytesIO(bom_data) + if ( + parser.engine == "pyarrow" + and data == "\n1" + and kwargs.get("skip_blank_lines", True) + ): + # Manually xfail, since we don't have mechanism to xfail specific version + request.node.add_marker( + pytest.mark.xfail(reason="Pyarrow can't read blank lines") + ) + result = parser.read_csv(_encode_data_with_bom(data), encoding=utf8, **kwargs) tm.assert_frame_equal(result, expected) -@skip_pyarrow def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): # see gh-13549 expected = DataFrame({"mb_num": [4.8], "multibyte": ["test"]}) @@ -141,7 +147,6 @@ def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): tm.assert_frame_equal(result, expected) -@skip_pyarrow @pytest.mark.parametrize( "file_path,encoding", [ @@ -226,7 +231,7 @@ def test_parse_encoded_special_characters(encoding): tm.assert_frame_equal(result, expected) -@skip_pyarrow +@xfail_pyarrow @pytest.mark.parametrize("encoding", ["utf-8", None, "utf-16", "cp1255", "latin-1"]) def test_encoding_memory_map(all_parsers, encoding): # GH40986 @@ -244,7 +249,7 @@ def test_encoding_memory_map(all_parsers, encoding): tm.assert_frame_equal(df, expected) -@skip_pyarrow +@xfail_pyarrow def test_chunk_splits_multibyte_char(all_parsers): """ Chunk splits a multibyte character with memory_map=True @@ -264,7 +269,7 @@ def test_chunk_splits_multibyte_char(all_parsers): tm.assert_frame_equal(dfr, df) -@skip_pyarrow +@xfail_pyarrow def test_readcsv_memmap_utf8(all_parsers): """ GH 43787
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51302
2023-02-10T16:46:06Z
2023-03-15T20:28:06Z
2023-03-15T20:28:06Z
2023-03-15T20:28:12Z
TST: avoid mutating DataFrame.values in tests (use iloc instead)
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 4742348b209d9..e69b0899facb9 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -796,7 +796,7 @@ def _gen_unique_rand(rng, _extra_size): def makeMissingDataframe(density: float = 0.9, random_state=None) -> DataFrame: df = makeDataFrame() i, j = _create_missing_idx(*df.shape, density=density, random_state=random_state) - df.values[i, j] = np.nan + df.iloc[i, j] = np.nan return df diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 4bb7f62fb13bd..2dfc31ccc1638 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -620,7 +620,7 @@ def test_setitem_fancy_scalar(self, float_frame): for idx in f.index[::5]: i = f.index.get_loc(idx) val = np.random.randn() - expected.values[i, j] = val + expected.iloc[i, j] = val ix[idx, col] = val tm.assert_frame_equal(f, expected) diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 5082aea354d6d..c4f5b60918e84 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -218,9 +218,8 @@ def test_corr_item_cache(self, using_copy_on_write): _ = df.corr(numeric_only=True) if using_copy_on_write: - # TODO(CoW) we should disallow this, so `df` doesn't get updated - ser.values[0] = 99 - assert df.loc[0, "A"] == 99 + ser.iloc[0] = 99 + assert df.loc[0, "A"] == 0 else: # Check that the corr didn't break link between ser and df ser.values[0] = 99 diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index b3f63db05dd28..2b5d675f029d3 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -550,8 +550,9 @@ def test_fillna_dataframe(self): tm.assert_frame_equal(result, expected) def test_fillna_columns(self): - df = DataFrame(np.random.randn(10, 10)) - df.values[:, ::2] = np.nan + arr = np.random.randn(10, 10) + arr[:, ::2] = np.nan + df = DataFrame(arr) result = df.fillna(method="ffill", axis=1) expected = df.T.fillna(method="pad").T diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index c621e9bae78f8..a13252ffdcf79 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2102,13 +2102,14 @@ def test_constructor_frame_copy(self, float_frame): def test_constructor_ndarray_copy(self, float_frame, using_array_manager): if not using_array_manager: - df = DataFrame(float_frame.values) + arr = float_frame.values.copy() + df = DataFrame(arr) - float_frame.values[5] = 5 + arr[5] = 5 assert (df.values[5] == 5).all() - df = DataFrame(float_frame.values, copy=True) - float_frame.values[6] = 6 + df = DataFrame(arr, copy=True) + arr[6] = 6 assert not (df.values[6] == 6).all() else: arr = float_frame.values.copy() diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index e93dd022f46ac..0942e5320de39 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -356,8 +356,9 @@ def test_cython_api2(): def test_cython_median(): - df = DataFrame(np.random.randn(1000)) - df.values[::2] = np.nan + arr = np.random.randn(1000) + arr[::2] = np.nan + df = DataFrame(arr) labels = np.random.randint(0, 50, size=1000).astype(float) labels[::17] = np.nan diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index dd16cca28677c..96d631964ab65 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -750,7 +750,7 @@ def test_int_series_slicing(self, multiindex_year_month_day_dataframe_random_dat exp = ymd["A"].copy() s[5:] = 0 - exp.values[5:] = 0 + exp.iloc[5:] = 0 tm.assert_numpy_array_equal(s.values, exp.values) result = ymd[5:] diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index ab84e0781a8f5..4bb00ad7f4c81 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -372,8 +372,8 @@ def test_frame(compression, setup_path): df = tm.makeDataFrame() # put in some random NAs - df.values[0, 0] = np.nan - df.values[5, 3] = np.nan + df.iloc[0, 0] = np.nan + df.iloc[5, 3] = np.nan _check_roundtrip_table( df, tm.assert_frame_equal, path=setup_path, compression=compression diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 3d09954ed3c0f..c36831ba60b89 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -899,7 +899,7 @@ def expected(self, dtype): arr = np.arange(5).astype(dtype) ser = Series(arr) ser = ser.astype(object) - ser.values[0] = np.timedelta64(4, "ns") + ser.iloc[0] = np.timedelta64(4, "ns") return ser @pytest.fixture diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index f8144a732e3a9..8897a0936b2c7 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -32,7 +32,7 @@ def test_fillna_nat(self): filled2 = series.fillna(value=series.values[2]) expected = series.copy() - expected.values[3] = expected.values[2] + expected.iloc[3] = expected.iloc[2] tm.assert_series_equal(filled, expected) tm.assert_series_equal(filled2, expected)
This is splitting off some "usefully anyway" test changes from https://github.com/pandas-dev/pandas/pull/51082 We have several places internally where we mutate the `df.values[..] = ..` directly, while this is certainly a discouraged pattern (also only work if you have a single block), and often easily avoided by using `df.iloc[..] = ..` or mutating the array before creating the DataFrame, instead.
https://api.github.com/repos/pandas-dev/pandas/pulls/51301
2023-02-10T16:03:32Z
2023-02-11T11:36:21Z
2023-02-11T11:36:21Z
2023-02-14T21:12:32Z
BUG: avoid StringArray.__setitem__ to mutate the value being set as side-effect
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 43a34c8e18b2d..410690de1a1ec 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1229,6 +1229,7 @@ Strings ^^^^^^^ - Bug in :func:`pandas.api.types.is_string_dtype` that would not return ``True`` for :class:`StringDtype` or :class:`ArrowDtype` with ``pyarrow.string()`` (:issue:`15585`) - Bug in converting string dtypes to "datetime64[ns]" or "timedelta64[ns]" incorrectly raising ``TypeError`` (:issue:`36153`) +- Bug in setting values in a string-dtype column with an array, mutating the array as side effect when it contains missing values (:issue:`51299`) - Interval diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 478a91b54fc48..bef1ae0c04c4e 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -423,7 +423,10 @@ def __setitem__(self, key, value): if len(value) and not lib.is_string_array(value, skipna=True): raise TypeError("Must provide strings.") - value[isna(value)] = libmissing.NA + mask = isna(value) + if mask.any(): + value = value.copy() + value[isna(value)] = libmissing.NA super().__setitem__(key, value) diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 20bd37e64a4e1..7e17efe4e7380 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -72,6 +72,19 @@ def test_setitem_with_scalar_string(dtype): tm.assert_extension_array_equal(arr, expected) +def test_setitem_with_array_with_missing(dtype): + # ensure that when setting with an array of values, we don't mutate the + # array `value` in __setitem__(self, key, value) + arr = pd.array(["a", "b", "c"], dtype=dtype) + value = np.array(["A", None]) + value_orig = value.copy() + arr[[0, 1]] = value + + expected = pd.array(["A", pd.NA, "c"], dtype=dtype) + tm.assert_extension_array_equal(arr, expected) + tm.assert_numpy_array_equal(value, value_orig) + + def test_astype_roundtrip(dtype): ser = pd.Series(pd.date_range("2000", periods=12)) ser[0] = None
Encountered this while working on https://github.com/pandas-dev/pandas/pull/51082, and this can be done as independent fix. ``` In [5]: arr = pd.array(["a", "b", "c"], dtype="string") In [6]: value = np.array(["A", None]) In [7]: arr[[0, 1]] = value In [8]: value Out[8]: array(['A', <NA>], dtype=object) # <-- value got mutated !! ``` I think in general the value that is being set should _never_ be mutated during the setitem operation. - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51299
2023-02-10T15:42:07Z
2023-02-11T04:55:44Z
2023-02-11T04:55:44Z
2023-02-11T08:26:17Z
ENH: enable lazy copy in merge() for CoW
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 6c5154b90d614..37013a5d1fb8f 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -134,7 +134,7 @@ def merge( right_index: bool = False, sort: bool = False, suffixes: Suffixes = ("_x", "_y"), - copy: bool = True, + copy: bool | None = None, indicator: str | bool = False, validate: str | None = None, ) -> DataFrame: @@ -744,7 +744,7 @@ def _reindex_and_concat( join_index: Index, left_indexer: npt.NDArray[np.intp] | None, right_indexer: npt.NDArray[np.intp] | None, - copy: bool, + copy: bool | None, ) -> DataFrame: """ reindex along index and concat along columns. @@ -793,7 +793,7 @@ def _reindex_and_concat( result = concat([left, right], axis=1, copy=copy) return result - def get_result(self, copy: bool = True) -> DataFrame: + def get_result(self, copy: bool | None = True) -> DataFrame: if self.indicator: self.left, self.right = self._indicator_pre_merge(self.left, self.right) @@ -1800,7 +1800,7 @@ def __init__( sort=True, # factorize sorts ) - def get_result(self, copy: bool = True) -> DataFrame: + def get_result(self, copy: bool | None = True) -> DataFrame: join_index, left_indexer, right_indexer = self._get_join_info() llabels, rlabels = _items_overlap_with_suffix( diff --git a/pandas/tests/copy_view/test_functions.py b/pandas/tests/copy_view/test_functions.py index 569cbc4ad7583..ffc80d2d11798 100644 --- a/pandas/tests/copy_view/test_functions.py +++ b/pandas/tests/copy_view/test_functions.py @@ -1,9 +1,12 @@ import numpy as np +import pandas.util._test_decorators as td + from pandas import ( DataFrame, Series, concat, + merge, ) import pandas._testing as tm from pandas.tests.copy_view.util import get_array @@ -177,3 +180,63 @@ def test_concat_mixed_series_frame(using_copy_on_write): if using_copy_on_write: assert not np.shares_memory(get_array(result, "a"), get_array(df, "a")) tm.assert_frame_equal(result, expected) + + +@td.skip_copy_on_write_not_yet_implemented # TODO(CoW) +def test_merge_on_key(using_copy_on_write): + df1 = DataFrame({"key": ["a", "b", "c"], "a": [1, 2, 3]}) + df2 = DataFrame({"key": ["a", "b", "c"], "b": [4, 5, 6]}) + df1_orig = df1.copy() + df2_orig = df2.copy() + + result = merge(df1, df2, on="key") + + if using_copy_on_write: + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + assert not np.shares_memory(get_array(result, "key"), get_array(df1, "key")) + assert not np.shares_memory(get_array(result, "key"), get_array(df2, "key")) + else: + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + + result.iloc[0, 1] = 0 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + + result.iloc[0, 2] = 0 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + tm.assert_frame_equal(df1, df1_orig) + tm.assert_frame_equal(df2, df2_orig) + + +def test_merge_on_index(using_copy_on_write): + df1 = DataFrame({"a": [1, 2, 3]}) + df2 = DataFrame({"b": [4, 5, 6]}) + df1_orig = df1.copy() + df2_orig = df2.copy() + + result = merge(df1, df2, left_index=True, right_index=True) + + if using_copy_on_write: + assert np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + else: + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + + result.iloc[0, 0] = 0 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "a"), get_array(df1, "a")) + assert np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + + result.iloc[0, 1] = 0 + if using_copy_on_write: + assert not np.shares_memory(get_array(result, "b"), get_array(df2, "b")) + tm.assert_frame_equal(df1, df1_orig) + tm.assert_frame_equal(df2, df2_orig) + + +# TODO(CoW) add merge tests where one of left/right isn't copied
xref https://github.com/pandas-dev/pandas/issues/49473 The current `copy=False` only works when merging on the index; when merging on keys, we currently get a [0, 1, 2, ..] join index for both left and right, and so that still results in a copy (but that can be avoided using the `is_range_indexer` utility)
https://api.github.com/repos/pandas-dev/pandas/pulls/51297
2023-02-10T14:22:42Z
2023-02-11T16:30:59Z
2023-02-11T16:30:59Z
2023-02-11T16:31:12Z
TST: add CoW test for setitem with Series being set
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index ae5ffb98558d3..d822cc03c499d 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1359,6 +1359,33 @@ def test_isetitem(using_copy_on_write): assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) +@pytest.mark.parametrize( + "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"] +) +def test_isetitem_series(using_copy_on_write, dtype): + df = DataFrame({"a": [1, 2, 3], "b": np.array([4, 5, 6], dtype=dtype)}) + ser = Series([7, 8, 9]) + ser_orig = ser.copy() + df.isetitem(0, ser) + + if using_copy_on_write: + # TODO(CoW) this can share memory + assert not np.shares_memory(get_array(df, "a"), get_array(ser)) + + # mutating dataframe doesn't update series + df.loc[0, "a"] = 0 + tm.assert_series_equal(ser, ser_orig) + + # mutating series doesn't update dataframe + df = DataFrame({"a": [1, 2, 3], "b": np.array([4, 5, 6], dtype=dtype)}) + ser = Series([7, 8, 9]) + df.isetitem(0, ser) + + ser.loc[0] = 0 + expected = DataFrame({"a": [7, 8, 9], "b": np.array([4, 5, 6], dtype=dtype)}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("key", ["a", ["a"]]) def test_get(using_copy_on_write, key): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
xref https://github.com/pandas-dev/pandas/issues/49473 We already have a test for setitem from https://github.com/pandas-dev/pandas/pull/50692/, but that only handled setting an array (actually, does that copy the array?), and not setting with a pandas object for which we could use lazy copy mechanism. This is only adding the test, we seem to actually do an eager copy, so room for optimization.
https://api.github.com/repos/pandas-dev/pandas/pulls/51296
2023-02-10T13:38:26Z
2023-02-11T11:25:27Z
2023-02-11T11:25:27Z
2023-02-11T11:28:29Z
TST: enable CoW copy keyword tests for astype/infer_objects
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 6b54345723118..54335c1131af4 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -66,11 +66,11 @@ def test_copy_shallow(using_copy_on_write): lambda df, copy: df.set_axis(["a", "b", "c"], axis="index", copy=copy), lambda df, copy: df.rename_axis(index="test", copy=copy), lambda df, copy: df.rename_axis(columns="test", copy=copy), - # lambda df, copy: df.astype({'b': 'int64'}, copy=copy), + lambda df, copy: df.astype({"b": "int64"}, copy=copy), # lambda df, copy: df.swaplevel(0, 0, copy=copy), lambda df, copy: df.swapaxes(0, 0, copy=copy), lambda df, copy: df.truncate(0, 5, copy=copy), - # lambda df, copy: df.infer_objects(copy=copy) + lambda df, copy: df.infer_objects(copy=copy), lambda df, copy: df.to_timestamp(copy=copy), lambda df, copy: df.to_period(freq="D", copy=copy), lambda df, copy: df.tz_localize("US/Central", copy=copy), @@ -84,11 +84,11 @@ def test_copy_shallow(using_copy_on_write): "set_axis", "rename_axis0", "rename_axis1", - # "astype", # CoW not yet implemented + "astype", # "swaplevel", # only series "swapaxes", "truncate", - # "infer_objects", # CoW not yet implemented + "infer_objects", "to_timestamp", "to_period", "tz_localize",
Small follow-up on https://github.com/pandas-dev/pandas/pull/50536, now that CoW has been properly added to `astype` and `infer_objects`
https://api.github.com/repos/pandas-dev/pandas/pulls/51293
2023-02-10T11:17:42Z
2023-02-10T15:40:11Z
2023-02-10T15:40:11Z
2023-02-10T15:44:57Z
TST: add CoW tests for xs() and get()
diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 6b54345723118..791a744e5b4e3 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1,6 +1,9 @@ import numpy as np import pytest +from pandas.errors import SettingWithCopyWarning + +import pandas as pd from pandas import ( DataFrame, Index, @@ -1308,3 +1311,90 @@ def test_isetitem(using_copy_on_write): assert np.shares_memory(get_array(df, "c"), get_array(df2, "c")) else: assert not np.shares_memory(get_array(df, "c"), get_array(df2, "c")) + + +@pytest.mark.parametrize("key", ["a", ["a"]]) +def test_get(using_copy_on_write, key): + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + df_orig = df.copy() + + result = df.get(key) + + if using_copy_on_write: + assert np.shares_memory(get_array(result, "a"), get_array(df, "a")) + result.iloc[0] = 0 + assert not np.shares_memory(get_array(result, "a"), get_array(df, "a")) + tm.assert_frame_equal(df, df_orig) + else: + # for non-CoW it depends on whether we got a Series or DataFrame if it + # is a view or copy or triggers a warning or not + warn = SettingWithCopyWarning if isinstance(key, list) else None + with pd.option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(warn): + result.iloc[0] = 0 + + if isinstance(key, list): + tm.assert_frame_equal(df, df_orig) + else: + assert df.iloc[0, 0] == 0 + + +@pytest.mark.parametrize("axis, key", [(0, 0), (1, "a")]) +@pytest.mark.parametrize( + "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"] +) +def test_xs(using_copy_on_write, using_array_manager, axis, key, dtype): + single_block = (dtype == "int64") and not using_array_manager + is_view = single_block or (using_array_manager and axis == 1) + df = DataFrame( + {"a": [1, 2, 3], "b": [4, 5, 6], "c": np.array([7, 8, 9], dtype=dtype)} + ) + df_orig = df.copy() + + result = df.xs(key, axis=axis) + + if axis == 1 or single_block: + assert np.shares_memory(get_array(df, "a"), get_array(result)) + elif using_copy_on_write: + assert result._mgr._has_no_reference(0) + + if using_copy_on_write or is_view: + result.iloc[0] = 0 + else: + with pd.option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(SettingWithCopyWarning): + result.iloc[0] = 0 + + if using_copy_on_write or (not single_block and axis == 0): + tm.assert_frame_equal(df, df_orig) + else: + assert df.iloc[0, 0] == 0 + + +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("key, level", [("l1", 0), (2, 1)]) +def test_xs_multiindex(using_copy_on_write, using_array_manager, key, level, axis): + arr = np.arange(18).reshape(6, 3) + index = MultiIndex.from_product([["l1", "l2"], [1, 2, 3]], names=["lev1", "lev2"]) + df = DataFrame(arr, index=index, columns=list("abc")) + if axis == 1: + df = df.transpose().copy() + df_orig = df.copy() + + result = df.xs(key, level=level, axis=axis) + + if level == 0: + assert np.shares_memory( + get_array(df, df.columns[0]), get_array(result, result.columns[0]) + ) + + warn = ( + SettingWithCopyWarning + if not using_copy_on_write and not using_array_manager + else None + ) + with pd.option_context("chained_assignment", "warn"): + with tm.assert_produces_warning(warn): + result.iloc[0, 0] = 0 + + tm.assert_frame_equal(df, df_orig) diff --git a/pandas/tests/copy_view/util.py b/pandas/tests/copy_view/util.py index 8e53c1644b0a2..ba9b0ecdebb58 100644 --- a/pandas/tests/copy_view/util.py +++ b/pandas/tests/copy_view/util.py @@ -10,7 +10,7 @@ def get_array(obj, col=None): which triggers tracking references / CoW (and we might be testing that this is done by some other operation). """ - if isinstance(obj, Series) and (obj is None or obj.name == col): + if isinstance(obj, Series) and (col is None or obj.name == col): return obj._values assert col is not None icol = obj.columns.get_loc(col)
xref https://github.com/pandas-dev/pandas/issues/49473 Adding basic tests for `xs` and `get`. Those rely on indexing methods under the hood, and thus already work correctly for CoW, but adding some basic tests to have independent coverage.
https://api.github.com/repos/pandas-dev/pandas/pulls/51292
2023-02-10T11:12:59Z
2023-02-10T13:40:59Z
2023-02-10T13:40:59Z
2023-02-10T13:41:02Z
CI pre-commit autoupdate
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 39c1f2b3a6c85..7bd662308afa8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -16,7 +16,7 @@ ci: autofix_prs: false repos: - repo: https://github.com/charliermarsh/ruff-pre-commit - rev: v0.0.215 + rev: v0.0.244 hooks: - id: ruff - repo: https://github.com/MarcoGorelli/absolufy-imports @@ -25,7 +25,7 @@ repos: - id: absolufy-imports files: ^pandas/ - repo: https://github.com/jendrikseipp/vulture - rev: 'v2.6' + rev: 'v2.7' hooks: - id: vulture entry: python scripts/run_vulture.py @@ -38,7 +38,7 @@ repos: types_or: [python, rst, markdown] additional_dependencies: [tomli] - repo: https://github.com/MarcoGorelli/cython-lint - rev: v0.10.1 + rev: v0.12.4 hooks: - id: cython-lint - id: double-quote-cython-strings @@ -71,12 +71,12 @@ repos: '--filter=-readability/casting,-runtime/int,-build/include_subdir,-readability/fn_size' ] - repo: https://github.com/pycqa/pylint - rev: v2.15.9 + rev: v2.16.1 hooks: - id: pylint stages: [manual] - repo: https://github.com/pycqa/pylint - rev: v2.15.9 + rev: v2.16.1 hooks: - id: pylint alias: redefined-outer-name @@ -101,7 +101,7 @@ repos: - id: pyupgrade args: [--py38-plus] - repo: https://github.com/pre-commit/pygrep-hooks - rev: v1.9.0 + rev: v1.10.0 hooks: - id: rst-backticks - id: rst-directive-colons diff --git a/pandas/_libs/index.pyi b/pandas/_libs/index.pyi index 4b4c4d65d1ea4..e08faaaa03139 100644 --- a/pandas/_libs/index.pyi +++ b/pandas/_libs/index.pyi @@ -52,7 +52,6 @@ class DatetimeEngine(Int64Engine): ... class TimedeltaEngine(DatetimeEngine): ... class PeriodEngine(Int64Engine): ... class BoolEngine(UInt8Engine): ... -class MaskedBoolEngine(MaskedUInt8Engine): ... class MaskedFloat64Engine(MaskedIndexEngine): ... class MaskedFloat32Engine(MaskedIndexEngine): ... class MaskedComplex128Engine(MaskedIndexEngine): ... @@ -65,6 +64,7 @@ class MaskedUInt64Engine(MaskedIndexEngine): ... class MaskedUInt32Engine(MaskedIndexEngine): ... class MaskedUInt16Engine(MaskedIndexEngine): ... class MaskedUInt8Engine(MaskedIndexEngine): ... +class MaskedBoolEngine(MaskedUInt8Engine): ... class BaseMultiIndexCodesEngine: levels: list[np.ndarray] diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index fa560cd0853f6..3faef6ed5d46e 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -108,7 +108,10 @@ cpdef cnp.ndarray astype_overflowsafe( bint round_ok=*, bint is_coerce=*, ) -cdef int64_t get_conversion_factor(NPY_DATETIMEUNIT from_unit, NPY_DATETIMEUNIT to_unit) except? -1 +cdef int64_t get_conversion_factor( + NPY_DATETIMEUNIT from_unit, + NPY_DATETIMEUNIT to_unit, +) except? -1 cdef bint cmp_dtstructs(npy_datetimestruct* left, npy_datetimestruct* right, int op) cdef get_implementation_bounds( diff --git a/pyproject.toml b/pyproject.toml index f4998fbe82722..56c16de0b06b4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -246,10 +246,20 @@ ignore = [ "B023", # Functions defined inside a loop must not use variables redefined in the loop # "B301", # not yet implemented + # Too many arguments to function call + "PLR0913", + # Too many returns + "PLR0911", + # Too many branches + "PLR0912", + # Too many statements + "PLR0915", # Additional checks that don't pass yet # Within an except clause, raise exceptions with ... "B904", + # Magic number + "PLR2004", ] exclude = [ @@ -266,6 +276,7 @@ exclude = [ max-line-length = 88 disable = [ # intentionally turned off + "bad-mcs-classmethod-argument", "broad-except", "c-extension-no-member", "comparison-with-itself", @@ -301,6 +312,7 @@ disable = [ "unsupported-assignment-operation", "unsupported-membership-test", "unused-import", + "use-dict-literal", "use-implicit-booleaness-not-comparison", "use-implicit-booleaness-not-len", "wrong-import-order", @@ -311,11 +323,13 @@ disable = [ "no-value-for-parameter", "undefined-variable", "unpacking-non-sequence", + "used-before-assignment", # pylint type "C": convention, for programming standard violation "missing-class-docstring", "missing-function-docstring", "missing-module-docstring", + "superfluous-parens", "too-many-lines", "unidiomatic-typecheck", "unnecessary-dunder-call", @@ -335,6 +349,7 @@ disable = [ "arguments-out-of-order", "arguments-renamed", "attribute-defined-outside-init", + "broad-exception-raised", "comparison-with-callable", "dangerous-default-value", "deprecated-module",
the automated one didn't run, maybe because the diff is too large? this touches a lot of files, but it's mostly just `black` removing newlines
https://api.github.com/repos/pandas-dev/pandas/pulls/51290
2023-02-10T10:50:57Z
2023-02-11T19:15:52Z
2023-02-11T19:15:52Z
2023-02-11T19:15:52Z
CI: Xfail plotting tests
diff --git a/pandas/tests/plotting/frame/test_frame_subplots.py b/pandas/tests/plotting/frame/test_frame_subplots.py index 47d91c7975a28..0f57ade453564 100644 --- a/pandas/tests/plotting/frame/test_frame_subplots.py +++ b/pandas/tests/plotting/frame/test_frame_subplots.py @@ -6,6 +6,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_linux +from pandas.compat.numpy import np_version_gte1p24 import pandas.util._test_decorators as td import pandas as pd @@ -370,6 +372,11 @@ def test_subplots_dup_columns(self): assert len(ax.lines) == 0 assert len(ax.right_ax.lines) == 5 + @pytest.mark.xfail( + np_version_gte1p24 and is_platform_linux(), + reason="Weird rounding problems", + strict=False, + ) def test_bar_log_no_subplots(self): # GH3254, GH3298 matplotlib/matplotlib#1882, #1892 # regressions in 1.2.1 @@ -380,6 +387,11 @@ def test_bar_log_no_subplots(self): ax = df.plot.bar(grid=True, log=True) tm.assert_numpy_array_equal(ax.yaxis.get_ticklocs(), expected) + @pytest.mark.xfail( + np_version_gte1p24 and is_platform_linux(), + reason="Weird rounding problems", + strict=False, + ) def test_bar_log_subplots(self): expected = np.array([0.1, 1.0, 10.0, 100.0, 1000.0, 1e4]) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 3a9aa91002730..3bb411afbaa3a 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas.compat import is_platform_linux +from pandas.compat.numpy import np_version_gte1p24 import pandas.util._test_decorators as td import pandas as pd @@ -238,6 +240,11 @@ def test_line_use_index_false(self): label2 = ax2.get_xlabel() assert label2 == "" + @pytest.mark.xfail( + np_version_gte1p24 and is_platform_linux(), + reason="Weird rounding problems", + strict=False, + ) def test_bar_log(self): expected = np.array([1e-1, 1e0, 1e1, 1e2, 1e3, 1e4])
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51289
2023-02-10T10:38:49Z
2023-02-10T15:53:55Z
2023-02-10T15:53:55Z
2023-02-10T15:56:02Z
DOC Fix EX01 errors - added example
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 7c61157149513..99084f23818c9 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -87,7 +87,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=EX01 --ignore_functions \ pandas.Series.index \ pandas.Series.dtype \ - pandas.Series.shape \ pandas.Series.nbytes \ pandas.Series.ndim \ pandas.Series.size \ diff --git a/pandas/core/base.py b/pandas/core/base.py index b708ff44b39d0..8a1a2b8b99aa5 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -309,6 +309,12 @@ def transpose(self: _T, *args, **kwargs) -> _T: def shape(self) -> Shape: """ Return a tuple of the shape of the underlying data. + + Examples + -------- + >>> s = pd.Series([1, 2, 3]) + >>> s.shape + (3,) """ return self._values.shape
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Towards #37875
https://api.github.com/repos/pandas-dev/pandas/pulls/51288
2023-02-10T10:23:06Z
2023-02-11T17:51:58Z
2023-02-11T17:51:58Z
2023-02-11T18:13:31Z
DOC: fix some issues
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 29f360e050548..dcc9aa9f84545 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -71,7 +71,7 @@ Below is a possibly non-exhaustive list of changes: e.g. ``Index([1, 2, 3])`` will have a ``int64`` dtype, which is the same as previously. 2. The various numeric datetime attributes of :class:`DatetimeIndex` (:attr:`~DatetimeIndex.day`, :attr:`~DatetimeIndex.month`, :attr:`~DatetimeIndex.year` etc.) were previously in of - dtype ``int64``, while they were ``int32`` for :class:`DatetimeArray`. They are now + dtype ``int64``, while they were ``int32`` for :class:`arrays.DatetimeArray`. They are now ``int32`` on ``DatetimeIndex`` also: .. ipython:: python @@ -610,7 +610,7 @@ Empty DataFrames/Series will now default to have a ``RangeIndex`` Before, constructing an empty (where ``data`` is ``None`` or an empty list-like argument) :class:`Series` or :class:`DataFrame` without specifying the axes (``index=None``, ``columns=None``) would return the axes as empty :class:`Index` with object dtype. -Now, the axes return an empty :class:`RangeIndex`. +Now, the axes return an empty :class:`RangeIndex` (:issue:`49572`). *Previous behavior*: diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 3e4d184ecdf47..64dde64371e29 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -132,6 +132,11 @@ class DatetimeIndex(DatetimeTimedeltaMixin): Represented internally as int64, and which can be boxed to Timestamp objects that are subclasses of datetime and carry metadata. + .. versionchanged:: 2.0.0 + The various numeric date/time attributes (:attr:`~DatetimeIndex.day`, + :attr:`~DatetimeIndex.month`, :attr:`~DatetimeIndex.year` etc.) now have dtype + ``int32``. Previously they had dtype ``int64``. + Parameters ---------- data : array-like (1-dimensional)
Some small doc issues.
https://api.github.com/repos/pandas-dev/pandas/pulls/51286
2023-02-10T08:28:54Z
2023-02-13T19:06:13Z
2023-02-13T19:06:12Z
2023-02-13T23:26:46Z
TST: fix pyarrow xfails for date/time dtypes
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index e6516b004a973..8df73398f1e4a 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -338,6 +338,14 @@ def _create_binary_propagating_op(name, is_divmod=False): elif is_cmp and isinstance(other, (date, time, timedelta)): return NA + elif isinstance(other, date): + if name in ["__sub__", "__rsub__"]: + return NA + + elif isinstance(other, timedelta): + if name in ["__sub__", "__rsub__", "__add__", "__radd__"]: + return NA + return NotImplemented method.__name__ = name diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index bdefc65e1f957..705e9d55c06e7 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -384,7 +384,7 @@ def test_accumulate_series(self, data, all_numeric_accumulations, skipna, reques # renders the exception messages even when not showing them pytest.skip(f"{all_numeric_accumulations} not implemented for pyarrow < 9") - elif all_numeric_accumulations == "cumsum" and (pa.types.is_boolean(pa_type)): + elif all_numeric_accumulations == "cumsum" and pa.types.is_boolean(pa_type): request.node.add_marker( pytest.mark.xfail( reason=f"{all_numeric_accumulations} not implemented for {pa_type}", @@ -859,17 +859,7 @@ def test_factorize(self, data_for_grouping, request): def test_combine_add(self, data_repeated, request): pa_dtype = next(data_repeated(1)).dtype.pyarrow_dtype - if pa.types.is_duration(pa_dtype): - # TODO: this fails on the scalar addition constructing 'expected' - # but not in the actual 'combine' call, so may be salvage-able - mark = pytest.mark.xfail( - raises=TypeError, - reason=f"{pa_dtype} cannot be added to {pa_dtype}", - ) - request.node.add_marker(mark) - super().test_combine_add(data_repeated) - - elif pa.types.is_temporal(pa_dtype): + if pa.types.is_temporal(pa_dtype) and not pa.types.is_duration(pa_dtype): # analogous to datetime64, these cannot be added orig_data1, orig_data2 = data_repeated(2) s1 = pd.Series(orig_data1) @@ -915,14 +905,24 @@ def _patch_combine(self, obj, other, op): pa_expected = pa.array(expected_data._values) if pa.types.is_duration(pa_expected.type): - # pyarrow sees sequence of datetime/timedelta objects and defaults - # to "us" but the non-pointwise op retains unit - unit = original_dtype.pyarrow_dtype.unit - if type(other) in [datetime, timedelta] and unit in ["s", "ms"]: - # pydatetime/pytimedelta objects have microsecond reso, so we - # take the higher reso of the original and microsecond. Note - # this matches what we would do with DatetimeArray/TimedeltaArray - unit = "us" + orig_pa_type = original_dtype.pyarrow_dtype + if pa.types.is_date(orig_pa_type): + if pa.types.is_date64(orig_pa_type): + # TODO: why is this different vs date32? + unit = "ms" + else: + unit = "s" + else: + # pyarrow sees sequence of datetime/timedelta objects and defaults + # to "us" but the non-pointwise op retains unit + # timestamp or duration + unit = orig_pa_type.unit + if type(other) in [datetime, timedelta] and unit in ["s", "ms"]: + # pydatetime/pytimedelta objects have microsecond reso, so we + # take the higher reso of the original and microsecond. Note + # this matches what we would do with DatetimeArray/TimedeltaArray + unit = "us" + pa_expected = pa_expected.cast(f"duration[{unit}]") else: pa_expected = pa_expected.cast(original_dtype.pyarrow_dtype) @@ -979,7 +979,7 @@ def _get_arith_xfail_marker(self, opname, pa_dtype): f"for {pa_dtype}" ) ) - elif arrow_temporal_supported: + elif arrow_temporal_supported and pa.types.is_time(pa_dtype): mark = pytest.mark.xfail( raises=TypeError, reason=( @@ -1024,6 +1024,7 @@ def test_arith_series_with_scalar( ) or pa.types.is_duration(pa_dtype) or pa.types.is_timestamp(pa_dtype) + or pa.types.is_date(pa_dtype) ): # BaseOpsUtil._combine always returns int64, while ArrowExtensionArray does # not upcast @@ -1055,6 +1056,7 @@ def test_arith_frame_with_scalar( ) or pa.types.is_duration(pa_dtype) or pa.types.is_timestamp(pa_dtype) + or pa.types.is_date(pa_dtype) ): # BaseOpsUtil._combine always returns int64, while ArrowExtensionArray does # not upcast @@ -1107,6 +1109,7 @@ def test_arith_series_with_array( ) or pa.types.is_duration(pa_dtype) or pa.types.is_timestamp(pa_dtype) + or pa.types.is_date(pa_dtype) ): monkeypatch.setattr(TestBaseArithmeticOps, "_combine", self._patch_combine) self.check_opname(ser, op_name, other, exc=self.series_array_exc)
Sits on top of #50689
https://api.github.com/repos/pandas-dev/pandas/pulls/51281
2023-02-10T01:01:36Z
2023-02-21T09:11:53Z
2023-02-21T09:11:53Z
2023-02-21T15:27:46Z
ENH: Add CoW optimization for fillna
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 53581420f920f..fc083433b9b53 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -223,6 +223,7 @@ Copy-on-Write improvements - :meth:`DataFrame.to_period` / :meth:`Series.to_period` - :meth:`DataFrame.truncate` - :meth:`DataFrame.tz_convert` / :meth:`Series.tz_localize` + - :meth:`DataFrame.fillna` / :meth:`Series.fillna` - :meth:`DataFrame.interpolate` / :meth:`Series.interpolate` - :meth:`DataFrame.ffill` / :meth:`Series.ffill` - :meth:`DataFrame.bfill` / :meth:`Series.bfill` diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 47691a7f964f7..60d022a0c7964 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1014,6 +1014,7 @@ def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: ---------- mask : np.ndarray[bool], SparseArray[bool], or BooleanArray new : a ndarray/object + using_cow: bool, default False Returns ------- @@ -1188,7 +1189,12 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: return [self.make_block(result)] def fillna( - self, value, limit: int | None = None, inplace: bool = False, downcast=None + self, + value, + limit: int | None = None, + inplace: bool = False, + downcast=None, + using_cow: bool = False, ) -> list[Block]: """ fillna on the block with the value. If we fail, then convert to @@ -1207,20 +1213,22 @@ def fillna( if noop: # we can't process the value, but nothing to do if inplace: + if using_cow: + return [self.copy(deep=False)] # Arbitrarily imposing the convention that we ignore downcast # on no-op when inplace=True return [self] else: # GH#45423 consistent downcasting on no-ops. - nb = self.copy() - nbs = nb._maybe_downcast([nb], downcast=downcast) + nb = self.copy(deep=not using_cow) + nbs = nb._maybe_downcast([nb], downcast=downcast, using_cow=using_cow) return nbs if limit is not None: mask[mask.cumsum(self.ndim - 1) > limit] = False if inplace: - nbs = self.putmask(mask.T, value) + nbs = self.putmask(mask.T, value, using_cow=using_cow) else: # without _downcast, we would break # test_fillna_dtype_conversion_equiv_replace @@ -1230,7 +1238,10 @@ def fillna( # makes a difference bc blk may have object dtype, which has # different behavior in _maybe_downcast. return extend_blocks( - [blk._maybe_downcast([blk], downcast=downcast) for blk in nbs] + [ + blk._maybe_downcast([blk], downcast=downcast, using_cow=using_cow) + for blk in nbs + ] ) def interpolate( @@ -1725,12 +1736,21 @@ class ExtensionBlock(libinternals.Block, EABackedBlock): values: ExtensionArray def fillna( - self, value, limit: int | None = None, inplace: bool = False, downcast=None + self, + value, + limit: int | None = None, + inplace: bool = False, + downcast=None, + using_cow: bool = False, ) -> list[Block]: if is_interval_dtype(self.dtype): # Block.fillna handles coercion (test_fillna_interval) return super().fillna( - value=value, limit=limit, inplace=inplace, downcast=downcast + value=value, + limit=limit, + inplace=inplace, + downcast=downcast, + using_cow=using_cow, ) new_values = self.values.fillna(value=value, method=None, limit=limit) nb = self.make_block_same_class(new_values) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 7508b5cd1e8e7..eb4c2d642862b 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -398,15 +398,14 @@ def fillna(self: T, value, limit, inplace: bool, downcast) -> T: if limit is not None: # Do this validation even if we go through one of the no-op paths limit = libalgos.validate_limit(None, limit=limit) - if inplace: - # TODO(CoW) can be optimized to only copy those blocks that have refs - if using_copy_on_write() and any( - not self._has_no_reference_block(i) for i in range(len(self.blocks)) - ): - self = self.copy() return self.apply( - "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast + "fillna", + value=value, + limit=limit, + inplace=inplace, + downcast=downcast, + using_cow=using_copy_on_write(), ) def astype(self: T, dtype, copy: bool | None = False, errors: str = "raise") -> T: diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index 1bfcf7d180e54..32a36b9690465 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -3,9 +3,11 @@ from pandas import ( DataFrame, + Interval, NaT, Series, Timestamp, + interval_range, ) import pandas._testing as tm from pandas.tests.copy_view.util import get_array @@ -162,3 +164,71 @@ def test_interpolate_downcast_reference_triggers_copy(using_copy_on_write): tm.assert_frame_equal(df_orig, view) else: tm.assert_frame_equal(df, view) + + +def test_fillna(using_copy_on_write): + df = DataFrame({"a": [1.5, np.nan], "b": 1}) + df_orig = df.copy() + + df2 = df.fillna(5.5) + if using_copy_on_write: + assert np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + else: + assert not np.shares_memory(get_array(df, "b"), get_array(df2, "b")) + + df2.iloc[0, 1] = 100 + tm.assert_frame_equal(df_orig, df) + + +@pytest.mark.parametrize("downcast", [None, False]) +def test_fillna_inplace(using_copy_on_write, downcast): + df = DataFrame({"a": [1.5, np.nan], "b": 1}) + arr_a = get_array(df, "a") + arr_b = get_array(df, "b") + + df.fillna(5.5, inplace=True, downcast=downcast) + assert np.shares_memory(get_array(df, "a"), arr_a) + assert np.shares_memory(get_array(df, "b"), arr_b) + if using_copy_on_write: + assert df._mgr._has_no_reference(0) + assert df._mgr._has_no_reference(1) + + +def test_fillna_inplace_reference(using_copy_on_write): + df = DataFrame({"a": [1.5, np.nan], "b": 1}) + df_orig = df.copy() + arr_a = get_array(df, "a") + arr_b = get_array(df, "b") + view = df[:] + + df.fillna(5.5, inplace=True) + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), arr_a) + assert np.shares_memory(get_array(df, "b"), arr_b) + assert view._mgr._has_no_reference(0) + assert df._mgr._has_no_reference(0) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(get_array(df, "a"), arr_a) + assert np.shares_memory(get_array(df, "b"), arr_b) + expected = DataFrame({"a": [1.5, 5.5], "b": 1}) + tm.assert_frame_equal(df, expected) + + +def test_fillna_interval_inplace_reference(using_copy_on_write): + ser = Series(interval_range(start=0, end=5), name="a") + ser.iloc[1] = np.nan + + ser_orig = ser.copy() + view = ser[:] + ser.fillna(value=Interval(left=0, right=5), inplace=True) + + if using_copy_on_write: + assert not np.shares_memory( + get_array(ser, "a").left.values, get_array(view, "a").left.values + ) + tm.assert_series_equal(view, ser_orig) + else: + assert np.shares_memory( + get_array(ser, "a").left.values, get_array(view, "a").left.values + ) diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index b74372017f303..85c2febefb6ce 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -249,14 +249,17 @@ def test_fillna_copy_frame(self, data_missing): assert df.A.values is not result.A.values - def test_fillna_copy_series(self, data_missing): + def test_fillna_copy_series(self, data_missing, no_op_with_cow: bool = False): arr = data_missing.take([1, 1]) ser = pd.Series(arr) filled_val = ser[0] result = ser.fillna(filled_val) - assert ser._values is not result._values + if no_op_with_cow: + assert ser._values is result._values + else: + assert ser._values is not result._values assert ser._values is arr def test_fillna_length_mismatch(self, data_missing): diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index 92796c604333d..0ad2de9e834fa 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -116,6 +116,11 @@ def test_combine_add(self, data_repeated): # Timestamp.__add__(Timestamp) not defined pass + def test_fillna_copy_series(self, data_missing, using_copy_on_write): + super().test_fillna_copy_series( + data_missing, no_op_with_cow=using_copy_on_write + ) + class TestInterface(BaseDatetimeTests, base.BaseInterfaceTests): pass diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 0f916cea9d518..3cf24d848e453 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -132,6 +132,11 @@ def test_combine_add(self, data_repeated): def test_fillna_length_mismatch(self, data_missing): super().test_fillna_length_mismatch(data_missing) + def test_fillna_copy_series(self, data_missing, using_copy_on_write): + super().test_fillna_copy_series( + data_missing, no_op_with_cow=using_copy_on_write + ) + class TestMissing(BaseInterval, base.BaseMissingTests): # Index.fillna only accepts scalar `value`, so we have to xfail all diff --git a/pandas/tests/extension/test_period.py b/pandas/tests/extension/test_period.py index 923dc24240f61..fc7ca41399baf 100644 --- a/pandas/tests/extension/test_period.py +++ b/pandas/tests/extension/test_period.py @@ -105,6 +105,11 @@ def test_diff(self, data, periods): else: super().test_diff(data, periods) + def test_fillna_copy_series(self, data_missing, using_copy_on_write): + super().test_fillna_copy_series( + data_missing, no_op_with_cow=using_copy_on_write + ) + class TestInterface(BasePeriodTests, base.BaseInterfaceTests):
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51279
2023-02-09T23:12:52Z
2023-02-11T10:46:32Z
2023-02-11T10:46:32Z
2023-03-01T23:20:36Z
BUG: replace with inplace not respecting cow
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 9fd9faf057a8a..ad4dc9edffefd 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -247,6 +247,9 @@ Copy-on-Write improvements can never update the original Series or DataFrame. Therefore, an informative error is raised to the user instead of silently doing nothing (:issue:`49467`) +- :meth:`DataFrame.replace` will now respect the Copy-on-Write mechanism + when ``inplace=True``. + Copy-on-Write can be enabled through one of .. code-block:: python diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index e66011acb978b..ce48e6b85c430 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -665,6 +665,7 @@ def replace_list( dest_list: Sequence[Any], inplace: bool = False, regex: bool = False, + using_cow: bool = False, ) -> list[Block]: """ See BlockManager.replace_list docstring. @@ -674,7 +675,11 @@ def replace_list( if isinstance(values, Categorical): # TODO: avoid special-casing # GH49404 - blk = self if inplace else self.copy() + if using_cow and inplace: + # TODO(CoW): Optimize + blk = self.copy() + else: + blk = self if inplace else self.copy() values = cast(Categorical, blk.values) values._replace(to_replace=src_list, value=dest_list, inplace=True) return [blk] @@ -703,7 +708,11 @@ def replace_list( masks = [extract_bool_array(x) for x in masks] - rb = [self if inplace else self.copy()] + if using_cow and inplace: + # TODO(CoW): Optimize + rb = [self.copy()] + else: + rb = [self if inplace else self.copy()] for i, (src, dest) in enumerate(pairs): convert = i == src_len # only convert once at the end new_rb: list[Block] = [] diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 517e6d7e48275..4973c0827245f 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -473,6 +473,7 @@ def replace_list( dest_list=dest_list, inplace=inplace, regex=regex, + using_cow=using_copy_on_write(), ) bm._consolidate_inplace() return bm diff --git a/pandas/tests/copy_view/test_replace.py b/pandas/tests/copy_view/test_replace.py new file mode 100644 index 0000000000000..a1347d8e12950 --- /dev/null +++ b/pandas/tests/copy_view/test_replace.py @@ -0,0 +1,38 @@ +import numpy as np + +from pandas import ( + Categorical, + DataFrame, +) +import pandas._testing as tm +from pandas.tests.copy_view.util import get_array + + +def test_replace_categorical_inplace_reference(using_copy_on_write): + df = DataFrame({"a": Categorical([1, 2, 3])}) + df_orig = df.copy() + arr_a = get_array(df, "a") + view = df[:] # noqa + df.replace(to_replace=[1], value=2, inplace=True) + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a").codes, arr_a.codes) + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + tm.assert_frame_equal(view, df_orig) + else: + assert np.shares_memory(get_array(df, "a").codes, arr_a.codes) + + +def test_replace_inplace_reference(using_copy_on_write): + df = DataFrame({"a": [1.5, 2, 3]}) + arr_a = get_array(df, "a") + view = df[:] # noqa + df.replace(to_replace=[1.5], value=15.5, inplace=True) + + if using_copy_on_write: + assert not np.shares_memory(get_array(df, "a"), arr_a) + assert df._mgr._has_no_reference(0) + assert view._mgr._has_no_reference(0) + else: + assert np.shares_memory(get_array(df, "a"), arr_a)
- [x] closes #51277 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This is a short term change that we should get in for the rc to avoid updating multiple object. Will optimise after the other replace pr is merged.
https://api.github.com/repos/pandas-dev/pandas/pulls/51278
2023-02-09T21:18:28Z
2023-02-10T10:47:35Z
2023-02-10T10:47:35Z
2023-02-10T10:47:39Z
DOC: Remove reference to mysql fallback support from user guide.
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 1c3cdd9f4cffd..4e331df9749be 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -5486,11 +5486,8 @@ included in Python's standard library by default. You can find an overview of supported drivers for each SQL dialect in the `SQLAlchemy docs <https://docs.sqlalchemy.org/en/latest/dialects/index.html>`__. -If SQLAlchemy is not installed, a fallback is only provided for sqlite (and -for mysql for backwards compatibility, but this is deprecated and will be -removed in a future version). -This mode requires a Python database adapter which respect the `Python -DB-API <https://www.python.org/dev/peps/pep-0249/>`__. +If SQLAlchemy is not installed, you can use a :class:`sqlite3.Connection` in place of +a SQLAlchemy engine, connection, or URI string. See also some :ref:`cookbook examples <cookbook.sql>` for some advanced strategies.
- [x] closes #51263 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51275
2023-02-09T18:47:24Z
2023-02-10T18:02:36Z
2023-02-10T18:02:36Z
2023-02-10T22:33:08Z
BUG: can't resample with non-nano dateindex, out-of-nanosecond-bounds
diff --git a/pandas/core/resample.py b/pandas/core/resample.py index cb129ec272ff3..96982f8727188 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1731,6 +1731,7 @@ def _get_time_bins(self, ax: DatetimeIndex): ax.min(), ax.max(), self.freq, + unit=ax.unit, closed=self.closed, origin=self.origin, offset=self.offset, @@ -1750,7 +1751,8 @@ def _get_time_bins(self, ax: DatetimeIndex): name=ax.name, ambiguous=True, nonexistent="shift_forward", - ).as_unit(ax.unit) + unit=ax.unit, + ) ax_values = ax.asi8 binner, bin_edges = self._adjust_bin_edges(binner, ax_values) @@ -1960,6 +1962,7 @@ def _get_timestamp_range_edges( first: Timestamp, last: Timestamp, freq: BaseOffset, + unit: str, closed: Literal["right", "left"] = "left", origin: TimeGrouperOrigin = "start_day", offset: Timedelta | None = None, @@ -2015,7 +2018,7 @@ def _get_timestamp_range_edges( origin = origin.tz_localize(None) first, last = _adjust_dates_anchored( - first, last, freq, closed=closed, origin=origin, offset=offset + first, last, freq, closed=closed, origin=origin, offset=offset, unit=unit ) if isinstance(freq, Day): first = first.tz_localize(index_tz) @@ -2082,7 +2085,7 @@ def _get_period_range_edges( adjust_last = freq.is_on_offset(last_ts) first_ts, last_ts = _get_timestamp_range_edges( - first_ts, last_ts, freq, closed=closed, origin=origin, offset=offset + first_ts, last_ts, freq, unit="ns", closed=closed, origin=origin, offset=offset ) first = (first_ts + int(adjust_first) * freq).to_period(freq) @@ -2115,32 +2118,35 @@ def _adjust_dates_anchored( closed: Literal["right", "left"] = "right", origin: TimeGrouperOrigin = "start_day", offset: Timedelta | None = None, + unit: str = "ns", ) -> tuple[Timestamp, Timestamp]: # First and last offsets should be calculated from the start day to fix an # error cause by resampling across multiple days when a one day period is # not a multiple of the frequency. See GH 8683 # To handle frequencies that are not multiple or divisible by a day we let # the possibility to define a fixed origin timestamp. See GH 31809 - first = first.as_unit("ns") - last = last.as_unit("ns") + first = first.as_unit(unit) + last = last.as_unit(unit) if offset is not None: - offset = offset.as_unit("ns") + offset = offset.as_unit(unit) + + freq_value = Timedelta(freq).as_unit(unit)._value - origin_nanos = 0 # origin == "epoch" + origin_timestamp = 0 # origin == "epoch" if origin == "start_day": - origin_nanos = first.normalize()._value + origin_timestamp = first.normalize()._value elif origin == "start": - origin_nanos = first._value + origin_timestamp = first._value elif isinstance(origin, Timestamp): - origin_nanos = origin.as_unit("ns")._value + origin_timestamp = origin.as_unit(unit)._value elif origin in ["end", "end_day"]: origin_last = last if origin == "end" else last.ceil("D") - sub_freq_times = (origin_last._value - first._value) // freq.nanos + sub_freq_times = (origin_last._value - first._value) // freq_value if closed == "left": sub_freq_times += 1 first = origin_last - sub_freq_times * freq - origin_nanos = first._value - origin_nanos += offset._value if offset else 0 + origin_timestamp = first._value + origin_timestamp += offset._value if offset else 0 # GH 10117 & GH 19375. If first and last contain timezone information, # Perform the calculation in UTC in order to avoid localizing on an @@ -2152,19 +2158,19 @@ def _adjust_dates_anchored( if last_tzinfo is not None: last = last.tz_convert("UTC") - foffset = (first._value - origin_nanos) % freq.nanos - loffset = (last._value - origin_nanos) % freq.nanos + foffset = (first._value - origin_timestamp) % freq_value + loffset = (last._value - origin_timestamp) % freq_value if closed == "right": if foffset > 0: # roll back fresult_int = first._value - foffset else: - fresult_int = first._value - freq.nanos + fresult_int = first._value - freq_value if loffset > 0: # roll forward - lresult_int = last._value + (freq.nanos - loffset) + lresult_int = last._value + (freq_value - loffset) else: # already the end of the road lresult_int = last._value @@ -2177,11 +2183,11 @@ def _adjust_dates_anchored( if loffset > 0: # roll forward - lresult_int = last._value + (freq.nanos - loffset) + lresult_int = last._value + (freq_value - loffset) else: - lresult_int = last._value + freq.nanos - fresult = Timestamp(fresult_int) - lresult = Timestamp(lresult_int) + lresult_int = last._value + freq_value + fresult = Timestamp(fresult_int, unit=unit) + lresult = Timestamp(lresult_int, unit=unit) if first_tzinfo is not None: fresult = fresult.tz_localize("UTC").tz_convert(first_tzinfo) if last_tzinfo is not None: diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index d18db6ab5f643..13041a81dadcf 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1838,7 +1838,7 @@ def test_get_timestamp_range_edges(first, last, freq, exp_first, exp_last, unit) exp_last = Timestamp(exp_last) freq = pd.tseries.frequencies.to_offset(freq) - result = _get_timestamp_range_edges(first, last, freq) + result = _get_timestamp_range_edges(first, last, freq, unit="ns") expected = (exp_first, exp_last) assert result == expected @@ -1949,3 +1949,28 @@ def test_resample_unsigned_int(any_unsigned_int_numpy_dtype, unit): ), ) tm.assert_frame_equal(result, expected) + + +def test_long_rule_non_nano(): + # https://github.com/pandas-dev/pandas/issues/51024 + idx = date_range("0300-01-01", "2000-01-01", unit="s", freq="100Y") + ser = Series([1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5, 7, 1, 4, 2, 8, 5], index=idx) + result = ser.resample("200Y").mean() + expected_idx = DatetimeIndex( + np.array( + [ + "0300-12-31", + "0500-12-31", + "0700-12-31", + "0900-12-31", + "1100-12-31", + "1300-12-31", + "1500-12-31", + "1700-12-31", + "1900-12-31", + ] + ).astype("datetime64[s]"), + freq="200A-DEC", + ) + expected = Series([1.0, 3.0, 6.5, 4.0, 3.0, 6.5, 4.0, 3.0, 6.5], index=expected_idx) + tm.assert_series_equal(result, expected)
- [ ] closes #51024 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51274
2023-02-09T18:45:38Z
2023-02-13T21:33:41Z
2023-02-13T21:33:41Z
2023-02-13T21:33:48Z
Revert "PERF: ArrowExtensionArray.to_numpy(dtype=object)"
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 0ea18d69f0dbb..9fd9faf057a8a 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -1078,7 +1078,7 @@ Performance improvements - Performance improvement in :meth:`~arrays.ArrowExtensionArray.factorize` (:issue:`49177`) - Performance improvement in :meth:`~arrays.ArrowExtensionArray.__setitem__` (:issue:`50248`, :issue:`50632`) - Performance improvement in :class:`~arrays.ArrowExtensionArray` comparison methods when array contains NA (:issue:`50524`) -- Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`49973`, :issue:`51227`) +- Performance improvement in :meth:`~arrays.ArrowExtensionArray.to_numpy` (:issue:`49973`) - Performance improvement when parsing strings to :class:`BooleanDtype` (:issue:`50613`) - Performance improvement in :meth:`DataFrame.join` when joining on a subset of a :class:`MultiIndex` (:issue:`48611`) - Performance improvement for :meth:`MultiIndex.intersection` (:issue:`48604`) diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 95a63a1f860ae..075beca106e6a 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -853,12 +853,12 @@ def to_numpy( na_value = self.dtype.na_value pa_type = self._data.type - if pa.types.is_timestamp(pa_type) or pa.types.is_duration(pa_type): + if ( + is_object_dtype(dtype) + or pa.types.is_timestamp(pa_type) + or pa.types.is_duration(pa_type) + ): result = np.array(list(self), dtype=dtype) - elif is_object_dtype(dtype) and self._hasna: - result = np.empty(len(self), dtype=object) - mask = ~self.isna() - result[mask] = np.asarray(self[mask]._data) else: result = np.asarray(self._data, dtype=dtype) if copy or self._hasna: diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 6a0d3c7f6e381..1dac8faa3a9e2 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -1518,16 +1518,6 @@ def test_to_numpy_with_defaults(data): tm.assert_numpy_array_equal(result, expected) -def test_to_numpy_int_with_na(): - # GH51227: ensure to_numpy does not convert int to float - data = [1, None] - arr = pd.array(data, dtype="int64[pyarrow]") - result = arr.to_numpy() - expected = np.array([1, pd.NA], dtype=object) - assert isinstance(result[0], int) - tm.assert_numpy_array_equal(result, expected) - - def test_setitem_null_slice(data): # GH50248 orig = data.copy()
Reverts pandas-dev/pandas#51227
https://api.github.com/repos/pandas-dev/pandas/pulls/51273
2023-02-09T18:33:09Z
2023-02-09T19:09:30Z
2023-02-09T19:09:30Z
2023-02-09T19:10:04Z
CI: Don't test min pyarrow version with multiple python versions
diff --git a/.github/workflows/ubuntu.yml b/.github/workflows/ubuntu.yml index 6726139ed5fa4..cb07c67dda2df 100644 --- a/.github/workflows/ubuntu.yml +++ b/.github/workflows/ubuntu.yml @@ -29,7 +29,7 @@ jobs: matrix: env_file: [actions-38.yaml, actions-39.yaml, actions-310.yaml, actions-311.yaml] pattern: ["not single_cpu", "single_cpu"] - pyarrow_version: ["7", "8", "9", "10"] + pyarrow_version: ["8", "9", "10"] include: - name: "Downstream Compat" env_file: actions-38-downstream_compat.yaml @@ -79,23 +79,17 @@ jobs: test_args: "-W error::DeprecationWarning -W error::FutureWarning" error_on_warnings: "0" exclude: - - env_file: actions-38.yaml - pyarrow_version: "7" - env_file: actions-38.yaml pyarrow_version: "8" - env_file: actions-38.yaml pyarrow_version: "9" - - env_file: actions-39.yaml - pyarrow_version: "7" - env_file: actions-39.yaml pyarrow_version: "8" - env_file: actions-39.yaml pyarrow_version: "9" - - env_file: actions-311.yaml - pyarrow_version: "7" - - env_file: actions-311.yaml + - env_file: actions-310.yaml pyarrow_version: "8" - - env_file: actions-311.yaml + - env_file: actions-310.yaml pyarrow_version: "9" fail-fast: false name: ${{ matrix.name || format('{0} pyarrow={1} {2}', matrix.env_file, matrix.pyarrow_version, matrix.pattern) }}
cc @phofl After the minimum pyarrow version was bumped to 7, we shouldn't need to test this over multiple python versions anymore. Additionally, uses PY3.11 to test multiple pyarrow versions instead of PY3.10
https://api.github.com/repos/pandas-dev/pandas/pulls/51272
2023-02-09T18:26:54Z
2023-02-10T04:42:46Z
2023-02-10T04:42:46Z
2023-02-10T04:42:49Z
CoW: Ensure that iterrows does not allow mutating parent
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index 7fc856be374e9..9ceec88e494a5 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -222,6 +222,7 @@ Copy-on-Write improvements - :meth:`DataFrame.to_timestamp` / :meth:`Series.to_timestamp` - :meth:`DataFrame.to_period` / :meth:`Series.to_period` - :meth:`DataFrame.truncate` + - :meth:`DataFrame.iterrows` - :meth:`DataFrame.tz_convert` / :meth:`Series.tz_localize` - :meth:`DataFrame.fillna` / :meth:`Series.fillna` - :meth:`DataFrame.interpolate` / :meth:`Series.interpolate` diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 71dc3b523fca6..4154def5a7b77 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1392,8 +1392,14 @@ def iterrows(self) -> Iterable[tuple[Hashable, Series]]: """ columns = self.columns klass = self._constructor_sliced + using_cow = using_copy_on_write() for k, v in zip(self.index, self.values): s = klass(v, index=columns, name=k).__finalize__(self) + if using_cow and self._mgr.is_single_block: + s._mgr.blocks[0].refs = self._mgr.blocks[0].refs # type: ignore[union-attr] # noqa + s._mgr.blocks[0].refs.add_reference( # type: ignore[union-attr] + s._mgr.blocks[0] # type: ignore[arg-type, union-attr] + ) yield k, s def itertuples( diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 91419ba415fda..320b840cfa561 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1329,6 +1329,16 @@ def test_asfreq_noop(using_copy_on_write): tm.assert_frame_equal(df, df_orig) +def test_iterrows(using_copy_on_write): + df = DataFrame({"a": 0, "b": 1}, index=[1, 2, 3]) + df_orig = df.copy() + + for _, sub in df.iterrows(): + sub.iloc[0] = 100 + if using_copy_on_write: + tm.assert_frame_equal(df, df_orig) + + def test_interpolate_creates_copy(using_copy_on_write): # GH#51126 df = DataFrame({"a": [1.5, np.nan, 3]})
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. cc @jorisvandenbossche Any idea on how to do this nicer? Do you think we need a way to hand over a ref object when constructing a Series from an array at some point?
https://api.github.com/repos/pandas-dev/pandas/pulls/51271
2023-02-09T18:00:34Z
2023-02-16T08:09:51Z
2023-02-16T08:09:51Z
2023-02-16T10:48:21Z
ENH: Optimize putmask implementation for CoW
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0e6356044c6db..5d2a0fe66cc1d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9612,7 +9612,8 @@ def _where( # align the cond to same shape as myself cond = common.apply_if_callable(cond, self) if isinstance(cond, NDFrame): - cond, _ = cond.align(self, join="right", broadcast_axis=1, copy=False) + # CoW: Make sure reference is not kept alive + cond = cond.align(self, join="right", broadcast_axis=1, copy=False)[0] else: if not hasattr(cond, "shape"): cond = np.asanyarray(cond) @@ -9648,14 +9649,15 @@ def _where( # align with me if other.ndim <= self.ndim: - _, other = self.align( + # CoW: Make sure reference is not kept alive + other = self.align( other, join="left", axis=axis, level=level, fill_value=None, copy=False, - ) + )[1] # if we are NOT aligned, raise as we cannot where index if axis is None and not other._indexed_same(self): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 401b9e60308be..574e633bc4ba3 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -946,7 +946,7 @@ def _unstack( # --------------------------------------------------------------------- - def setitem(self, indexer, value) -> Block: + def setitem(self, indexer, value, using_cow: bool = False) -> Block: """ Attempt self.values[indexer] = value, possibly creating a new array. @@ -956,6 +956,8 @@ def setitem(self, indexer, value) -> Block: The subset of self.values to set value : object The value being set + using_cow: bool, default False + Signaling if CoW is used. Returns ------- @@ -991,10 +993,17 @@ def setitem(self, indexer, value) -> Block: # checking lib.is_scalar here fails on # test_iloc_setitem_custom_object casted = setitem_datetimelike_compat(values, len(vi), casted) + + if using_cow and self.refs.has_reference(): + values = values.copy() + self = self.make_block_same_class( + values.T if values.ndim == 2 else values + ) + values[indexer] = casted return self - def putmask(self, mask, new) -> list[Block]: + def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: """ putmask the data to the block; it is possible that we may create a new dtype of block @@ -1022,11 +1031,21 @@ def putmask(self, mask, new) -> list[Block]: new = extract_array(new, extract_numpy=True) if noop: + if using_cow: + return [self.copy(deep=False)] return [self] try: casted = np_can_hold_element(values.dtype, new) + + if using_cow and self.refs.has_reference(): + # Do this here to avoid copying twice + values = values.copy() + self = self.make_block_same_class(values) + putmask_without_repeat(values.T, mask, casted) + if using_cow: + return [self.copy(deep=False)] return [self] except LossySetitemError: @@ -1038,7 +1057,7 @@ def putmask(self, mask, new) -> list[Block]: return self.coerce_to_target_dtype(new).putmask(mask, new) else: indexer = mask.nonzero()[0] - nb = self.setitem(indexer, new[indexer]) + nb = self.setitem(indexer, new[indexer], using_cow=using_cow) return [nb] else: @@ -1053,7 +1072,7 @@ def putmask(self, mask, new) -> list[Block]: n = new[:, i : i + 1] submask = orig_mask[:, i : i + 1] - rbs = nb.putmask(submask, n) + rbs = nb.putmask(submask, n, using_cow=using_cow) res_blocks.extend(rbs) return res_blocks @@ -1448,7 +1467,7 @@ class EABackedBlock(Block): values: ExtensionArray - def setitem(self, indexer, value): + def setitem(self, indexer, value, using_cow: bool = False): """ Attempt self.values[indexer] = value, possibly creating a new array. @@ -1461,6 +1480,8 @@ def setitem(self, indexer, value): The subset of self.values to set value : object The value being set + using_cow: bool, default False + Signaling if CoW is used. Returns ------- @@ -1567,7 +1588,7 @@ def where(self, other, cond, _downcast: str | bool = "infer") -> list[Block]: nb = self.make_block_same_class(res_values) return [nb] - def putmask(self, mask, new) -> list[Block]: + def putmask(self, mask, new, using_cow: bool = False) -> list[Block]: """ See Block.putmask.__doc__ """ @@ -1585,8 +1606,16 @@ def putmask(self, mask, new) -> list[Block]: mask = self._maybe_squeeze_arg(mask) if not mask.any(): + if using_cow: + return [self.copy(deep=False)] return [self] + if using_cow and self.refs.has_reference(): + values = values.copy() + self = self.make_block_same_class( # type: ignore[assignment] + values.T if values.ndim == 2 else values + ) + try: # Caller is responsible for ensuring matching lengths values._putmask(mask, new) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 1439c174b4f43..791f282517e33 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -362,14 +362,6 @@ def setitem(self: T, indexer, value) -> T: return self.apply("setitem", indexer=indexer, value=value) def putmask(self, mask, new, align: bool = True): - if using_copy_on_write() and any( - not self._has_no_reference_block(i) for i in range(len(self.blocks)) - ): - # some reference -> copy full dataframe - # TODO(CoW) this could be optimized to only copy the blocks that would - # get modified - self = self.copy() - if align: align_keys = ["new", "mask"] else: @@ -381,6 +373,7 @@ def putmask(self, mask, new, align: bool = True): align_keys=align_keys, mask=mask, new=new, + using_cow=using_copy_on_write(), ) def diff(self: T, n: int, axis: AxisInt) -> T: diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 6b54345723118..bd64d52ec157c 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1237,8 +1237,9 @@ def test_replace(using_copy_on_write, replace_kwargs): tm.assert_frame_equal(df, df_orig) -def test_putmask(using_copy_on_write): - df = DataFrame({"a": [1, 2], "b": 1, "c": 2}) +@pytest.mark.parametrize("dtype", ["int64", "Int64"]) +def test_putmask(using_copy_on_write, dtype): + df = DataFrame({"a": [1, 2], "b": 1, "c": 2}, dtype=dtype) view = df[:] df_orig = df.copy() df[df == df] = 5 @@ -1252,6 +1253,51 @@ def test_putmask(using_copy_on_write): assert view.iloc[0, 0] == 5 +@pytest.mark.parametrize("dtype", ["int64", "Int64"]) +def test_putmask_no_reference(using_copy_on_write, dtype): + df = DataFrame({"a": [1, 2], "b": 1, "c": 2}, dtype=dtype) + arr_a = get_array(df, "a") + df[df == df] = 5 + + if using_copy_on_write: + assert np.shares_memory(arr_a, get_array(df, "a")) + + +@pytest.mark.parametrize("dtype", ["float64", "Float64"]) +def test_putmask_aligns_rhs_no_reference(using_copy_on_write, dtype): + df = DataFrame({"a": [1.5, 2], "b": 1.5}, dtype=dtype) + arr_a = get_array(df, "a") + df[df == df] = DataFrame({"a": [5.5, 5]}) + + if using_copy_on_write: + assert np.shares_memory(arr_a, get_array(df, "a")) + + +@pytest.mark.parametrize("val, exp", [(5.5, True), (5, False)]) +def test_putmask_dont_copy_some_blocks(using_copy_on_write, val, exp): + df = DataFrame({"a": [1, 2], "b": 1, "c": 1.5}) + view = df[:] + df_orig = df.copy() + indexer = DataFrame( + [[True, False, False], [True, False, False]], columns=list("abc") + ) + df[indexer] = val + + if using_copy_on_write: + assert not np.shares_memory(get_array(view, "a"), get_array(df, "a")) + # TODO(CoW): Could split blocks to avoid copying the whole block + assert np.shares_memory(get_array(view, "b"), get_array(df, "b")) is exp + assert np.shares_memory(get_array(view, "c"), get_array(df, "c")) + assert df._mgr._has_no_reference(1) is not exp + assert not df._mgr._has_no_reference(2) + tm.assert_frame_equal(view, df_orig) + elif val == 5: + # Without CoW the original will be modified, the other case upcasts, e.g. copy + assert np.shares_memory(get_array(view, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(view, "c"), get_array(df, "c")) + assert view.iloc[0, 0] == 5 + + def test_asfreq_noop(using_copy_on_write): df = DataFrame( {"a": [0.0, None, 2.0, 3.0]},
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51268
2023-02-09T17:20:02Z
2023-02-10T18:35:10Z
2023-02-10T18:35:10Z
2023-02-10T18:40:30Z
WEB: Obfuscating workgroup email addresses to fix Issue #51209
diff --git a/web/pandas/about/team.md b/web/pandas/about/team.md index a21e8a3142497..49b8a26ab56e8 100644 --- a/web/pandas/about/team.md +++ b/web/pandas/about/team.md @@ -52,7 +52,15 @@ The project governance is available in the [project governance page]({{ base_url ### {{ workgroup.name }} <ul> - <li><b>Contact:</b> <a href="mailto:{{ workgroup.contact }}">{{ workgroup.contact }}</a></li> + <li><b>Contact:</b> + <a id="{{ workgroup.name|replace(' ', '-') }}" href="mailto:asp.{{ workgroup.contact }}">asp.{{ workgroup.contact }}</a> + <script TYPE="text/javascript"> + var mail_tag_id = '{{ workgroup.name|replace(' ', '-') }}'; + var mail_tag_element = document.getElementById( mail_tag_id ); + mail_tag_element.innerHTML = mail_tag_element.innerHTML.replace(/^asp./, ""); + mail_tag_element.setAttribute('href', "mailto:"+mail_tag_element.innerHTML); + </script> + </li> <li><b>Responsibilities:</b> {{ workgroup.responsibilities }}</li> <li><b>Members:</b> <ul>
Hi, As defined by the scope of this Issue #51209 , I have implemented a JavaScript based solution for obfuscating ```workgroup``` emails: If required, please let me know whether any Tests/Code Checks need to be added/passed for this or if any other change needs to be implemented to close this PR successfully . Thanks --- - [x] closes #51209 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51266
2023-02-09T17:04:48Z
2023-02-24T22:12:48Z
2023-02-24T22:12:47Z
2023-02-25T04:46:42Z
ENH: Implement CoW for convert_dtypes
diff --git a/doc/source/whatsnew/v2.0.0.rst b/doc/source/whatsnew/v2.0.0.rst index b10f201e79318..850391522dbff 100644 --- a/doc/source/whatsnew/v2.0.0.rst +++ b/doc/source/whatsnew/v2.0.0.rst @@ -225,6 +225,7 @@ Copy-on-Write improvements - :meth:`DataFrame.tz_convert` / :meth:`Series.tz_localize` - :meth:`DataFrame.infer_objects` / :meth:`Series.infer_objects` - :meth:`DataFrame.astype` / :meth:`Series.astype` + - :meth:`DataFrame.convert_dtypes` / :meth:`Series.convert_dtypes` - :func:`concat` These methods return views when Copy-on-Write is enabled, which provides a significant diff --git a/pandas/core/generic.py b/pandas/core/generic.py index aaf1d0e022fdf..1b96ff57a6efc 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6642,7 +6642,7 @@ def convert_dtypes( # https://github.com/python/mypy/issues/8354 return cast(NDFrameT, result) else: - return self.copy() + return self.copy(deep=None) # ---------------------------------------------------------------------- # Filling NA's diff --git a/pandas/core/series.py b/pandas/core/series.py index 80dd0dd19f96f..a88dd224068ac 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5468,7 +5468,7 @@ def _convert_dtypes( if infer_objects: input_series = input_series.infer_objects() if is_object_dtype(input_series): - input_series = input_series.copy() + input_series = input_series.copy(deep=None) if convert_string or convert_integer or convert_boolean or convert_floating: dtype_backend = get_option("mode.dtype_backend") @@ -5483,7 +5483,7 @@ def _convert_dtypes( ) result = input_series.astype(inferred_dtype) else: - result = input_series.copy() + result = input_series.copy(deep=None) return result # error: Cannot determine type of 'isna' diff --git a/pandas/tests/copy_view/test_astype.py b/pandas/tests/copy_view/test_astype.py index a485275a28ac4..73343976e92fb 100644 --- a/pandas/tests/copy_view/test_astype.py +++ b/pandas/tests/copy_view/test_astype.py @@ -193,3 +193,42 @@ def test_astype_arrow_timestamp(using_copy_on_write): if using_copy_on_write: assert not result._mgr._has_no_reference(0) assert np.shares_memory(get_array(df, "a").asi8, get_array(result, "a")._data) + + +def test_convert_dtypes_infer_objects(using_copy_on_write): + ser = Series(["a", "b", "c"]) + ser_orig = ser.copy() + result = ser.convert_dtypes( + convert_integer=False, + convert_boolean=False, + convert_floating=False, + convert_string=False, + ) + + if using_copy_on_write: + assert np.shares_memory(get_array(ser), get_array(result)) + else: + assert not np.shares_memory(get_array(ser), get_array(result)) + + result.iloc[0] = "x" + tm.assert_series_equal(ser, ser_orig) + + +def test_convert_dtypes(using_copy_on_write): + df = DataFrame({"a": ["a", "b"], "b": [1, 2], "c": [1.5, 2.5], "d": [True, False]}) + df_orig = df.copy() + df2 = df.convert_dtypes() + + if using_copy_on_write: + assert np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert np.shares_memory(get_array(df2, "d"), get_array(df, "d")) + assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + else: + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) + assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert not np.shares_memory(get_array(df2, "c"), get_array(df, "c")) + assert not np.shares_memory(get_array(df2, "d"), get_array(df, "d")) + + df2.iloc[0, 0] = "x" + tm.assert_frame_equal(df, df_orig) diff --git a/pandas/tests/copy_view/util.py b/pandas/tests/copy_view/util.py index b5f4f74fc7e5e..8e53c1644b0a2 100644 --- a/pandas/tests/copy_view/util.py +++ b/pandas/tests/copy_view/util.py @@ -2,7 +2,7 @@ from pandas.core.arrays import BaseMaskedArray -def get_array(obj, col): +def get_array(obj, col=None): """ Helper method to get array for a DataFrame column or a Series. @@ -10,8 +10,9 @@ def get_array(obj, col): which triggers tracking references / CoW (and we might be testing that this is done by some other operation). """ - if isinstance(obj, Series) and obj.name == col: + if isinstance(obj, Series) and (obj is None or obj.name == col): return obj._values + assert col is not None icol = obj.columns.get_loc(col) assert isinstance(icol, int) arr = obj._get_column_array(icol)
- [ ] xref #49473 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/51265
2023-02-09T16:40:14Z
2023-02-10T08:00:12Z
2023-02-10T08:00:12Z
2023-02-10T09:44:24Z
DOC Correct EX02 docstring errors
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 08fbe3be9b092..17ad347d58fdf 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -589,9 +589,6 @@ if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then pandas.Series.sparse.sp_values \ pandas.Timestamp.fromtimestamp \ pandas.api.types.infer_dtype \ - pandas.api.types.is_bool_dtype \ - pandas.api.types.is_categorical_dtype \ - pandas.api.types.is_complex_dtype \ pandas.api.types.is_datetime64_any_dtype \ pandas.api.types.is_datetime64_dtype \ pandas.api.types.is_datetime64_ns_dtype \ diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 2b21cee06a632..ce6ed6ca60238 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -469,6 +469,8 @@ def is_categorical_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_categorical_dtype + >>> from pandas import CategoricalDtype >>> is_categorical_dtype(object) False >>> is_categorical_dtype(CategoricalDtype()) @@ -1253,6 +1255,7 @@ def is_bool_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_bool_dtype >>> is_bool_dtype(str) False >>> is_bool_dtype(int) @@ -1405,6 +1408,7 @@ def is_complex_dtype(arr_or_dtype) -> bool: Examples -------- + >>> from pandas.api.types import is_complex_dtype >>> is_complex_dtype(str) False >>> is_complex_dtype(int)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Towards #51236
https://api.github.com/repos/pandas-dev/pandas/pulls/51264
2023-02-09T14:09:45Z
2023-02-09T16:00:39Z
2023-02-09T16:00:39Z
2023-02-09T16:08:35Z