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
STY: Fix whatsnew ordering
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 64d5f3ead3345..98926712ac7ce 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -355,8 +355,8 @@ Datetimelike - Bug in addition or subtraction of :class:`DateOffset` objects with microsecond components to ``datetime64`` :class:`Index`, :class:`Series`, or :class:`DataFrame` columns with non-nanosecond resolution (:issue:`55595`) - Bug in addition or subtraction of very large :class:`Tick` objects with :class:`Timestamp` or :class:`Timedelta` objects raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`) - Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond :class:`DatetimeTZDtype` and inputs that would be out of bounds with nanosecond resolution incorrectly raising ``OutOfBoundsDatetime`` (:issue:`54620`) -- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` dtype and inputs that would be out of bounds for a ``datetime64[ns]`` incorrectly raising ``OutOfBoundsDatetime`` (:issue:`55756`) - Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` (or :class:`DatetimeTZDtype`) from mixed-numeric inputs treating those as nanoseconds instead of as multiples of the dtype's unit (which would happen with non-mixed numeric inputs) (:issue:`56004`) +- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` dtype and inputs that would be out of bounds for a ``datetime64[ns]`` incorrectly raising ``OutOfBoundsDatetime`` (:issue:`55756`) - Timedelta
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56026
2023-11-17T19:00:11Z
2023-11-17T19:03:54Z
2023-11-17T19:03:54Z
2023-11-17T19:03:57Z
REF: use conditional-nogil in libalgos
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index b330b37aebd8d..3ac257327ffcd 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -1145,107 +1145,7 @@ cdef void rank_sorted_1d( # that sorted value for retrieval back from the original # values / masked_vals arrays # TODO(cython3): de-duplicate once cython supports conditional nogil - if numeric_object_t is object: - with gil: - for i in range(N): - at_end = i == N - 1 - - # dups and sum_ranks will be incremented each loop where - # the value / group remains the same, and should be reset - # when either of those change. Used to calculate tiebreakers - dups += 1 - sum_ranks += i - grp_start + 1 - - next_val_diff = at_end or are_diff(masked_vals[sort_indexer[i]], - masked_vals[sort_indexer[i+1]]) - - # We'll need this check later anyway to determine group size, so just - # compute it here since shortcircuiting won't help - group_changed = at_end or (check_labels and - (labels[sort_indexer[i]] - != labels[sort_indexer[i+1]])) - - # Update out only when there is a transition of values or labels. - # When a new value or group is encountered, go back #dups steps( - # the number of occurrence of current value) and assign the ranks - # based on the starting index of the current group (grp_start) - # and the current index - if (next_val_diff or group_changed or (check_mask and - (mask[sort_indexer[i]] - ^ mask[sort_indexer[i+1]]))): - - # If keep_na, check for missing values and assign back - # to the result where appropriate - if keep_na and check_mask and mask[sort_indexer[i]]: - grp_na_count = dups - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = NaN - elif tiebreak == TIEBREAK_AVERAGE: - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = sum_ranks / <float64_t>dups - elif tiebreak == TIEBREAK_MIN: - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = i - grp_start - dups + 2 - elif tiebreak == TIEBREAK_MAX: - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = i - grp_start + 1 - - # With n as the previous rank in the group and m as the number - # of duplicates in this stretch, if TIEBREAK_FIRST and ascending, - # then rankings should be n + 1, n + 2 ... n + m - elif tiebreak == TIEBREAK_FIRST: - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = j + 1 - grp_start - - # If TIEBREAK_FIRST and descending, the ranking should be - # n + m, n + (m - 1) ... n + 1. This is equivalent to - # (i - dups + 1) + (i - j + 1) - grp_start - elif tiebreak == TIEBREAK_FIRST_DESCENDING: - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = 2 * i - j - dups + 2 - grp_start - elif tiebreak == TIEBREAK_DENSE: - for j in range(i - dups + 1, i + 1): - out[sort_indexer[j]] = grp_vals_seen - - # Look forward to the next value (using the sorting in - # lexsort_indexer). If the value does not equal the current - # value then we need to reset the dups and sum_ranks, knowing - # that a new value is coming up. The conditional also needs - # to handle nan equality and the end of iteration. If group - # changes we do not record seeing a new value in the group - if not group_changed and (next_val_diff or (check_mask and - (mask[sort_indexer[i]] - ^ mask[sort_indexer[i+1]]))): - dups = sum_ranks = 0 - grp_vals_seen += 1 - - # Similar to the previous conditional, check now if we are - # moving to a new group. If so, keep track of the index where - # the new group occurs, so the tiebreaker calculations can - # decrement that from their position. Fill in the size of each - # group encountered (used by pct calculations later). Also be - # sure to reset any of the items helping to calculate dups - if group_changed: - - # If not dense tiebreak, group size used to compute - # percentile will be # of non-null elements in group - if tiebreak != TIEBREAK_DENSE: - grp_size = i - grp_start + 1 - grp_na_count - - # Otherwise, it will be the number of distinct values - # in the group, subtracting 1 if NaNs are present - # since that is a distinct value we shouldn't count - else: - grp_size = grp_vals_seen - (grp_na_count > 0) - - for j in range(grp_start, i + 1): - grp_sizes[sort_indexer[j]] = grp_size - - dups = sum_ranks = 0 - grp_na_count = 0 - grp_start = i + 1 - grp_vals_seen = 1 - else: + with gil(numeric_object_t is object): for i in range(N): at_end = i == N - 1 @@ -1255,8 +1155,12 @@ cdef void rank_sorted_1d( dups += 1 sum_ranks += i - grp_start + 1 - next_val_diff = at_end or (masked_vals[sort_indexer[i]] - != masked_vals[sort_indexer[i+1]]) + if numeric_object_t is object: + next_val_diff = at_end or are_diff(masked_vals[sort_indexer[i]], + masked_vals[sort_indexer[i+1]]) + else: + next_val_diff = at_end or (masked_vals[sort_indexer[i]] + != masked_vals[sort_indexer[i+1]]) # We'll need this check later anyway to determine group size, so just # compute it here since shortcircuiting won't help @@ -1269,10 +1173,9 @@ cdef void rank_sorted_1d( # the number of occurrence of current value) and assign the ranks # based on the starting index of the current group (grp_start) # and the current index - if (next_val_diff or group_changed - or (check_mask and - (mask[sort_indexer[i]] ^ mask[sort_indexer[i+1]]))): - + if (next_val_diff or group_changed or (check_mask and + (mask[sort_indexer[i]] + ^ mask[sort_indexer[i+1]]))): # If keep_na, check for missing values and assign back # to the result where appropriate if keep_na and check_mask and mask[sort_indexer[i]]:
- [ ] 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/56025
2023-11-17T18:20:29Z
2023-11-17T20:12:56Z
2023-11-17T20:12:56Z
2023-11-17T20:14:23Z
[Docstring] Update a link to SQLAlchemy documentation to be compatible with 2.0
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index c77567214a692..d854ea09a5335 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -564,7 +564,7 @@ def read_sql( library. If a DBAPI2 object, only sqlite3 is supported. The user is responsible for engine disposal and connection closure for the SQLAlchemy connectable; str connections are closed automatically. See - `here <https://docs.sqlalchemy.org/en/13/core/connections.html>`_. + `here <https://docs.sqlalchemy.org/en/20/core/connections.html>`_. index_col : str or list of str, optional, default: None Column(s) to set as index(MultiIndex). coerce_float : bool, default True
While reading that docstring I found that the link to SQLAlchemy documentation was outdated. I propose to change it to link to a documentation of SQLAlchemy version that is actually supported (>=2.0). Quick search in repo for string `https://docs.sqlalchemy.org/en/13` yields just that single string to be outdated. Cheers, Damian
https://api.github.com/repos/pandas-dev/pandas/pulls/56023
2023-11-17T15:42:29Z
2023-11-17T17:19:09Z
2023-11-17T17:19:09Z
2023-11-17T17:19:10Z
CoW warning mode: setting values into single column of DataFrame
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index ce0c50a810ab1..0c99e5e7bdc54 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -389,6 +389,9 @@ def eval( # to use a non-numeric indexer try: with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", "Setting a value on a view", FutureWarning + ) # TODO: Filter the warnings we actually care about here. if inplace and isinstance(target, NDFrame): target.loc[:, assigner] = ret diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c3696be0579b0..956e84867709f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4857,6 +4857,7 @@ def eval(self, expr: str, *, inplace: bool = False, **kwargs) -> Any | None: inplace = validate_bool_kwarg(inplace, "inplace") kwargs["level"] = kwargs.pop("level", 0) + 1 + # TODO(CoW) those index/column resolvers create unnecessary refs to `self` index_resolvers = self._get_index_resolvers() column_resolvers = self._get_cleaned_column_resolvers() resolvers = column_resolvers, index_resolvers diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index a3c2ede55dabf..ab9209d509995 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1737,13 +1737,14 @@ def round(self, decimals: int, using_cow: bool = False) -> Self: # has no attribute "round" values = self.values.round(decimals) # type: ignore[union-attr] if values is self.values: - refs = self.refs if not using_cow: # Normally would need to do this before, but # numpy only returns same array when round operation # is no-op # https://github.com/numpy/numpy/blob/486878b37fc7439a3b2b87747f50db9b62fea8eb/numpy/core/src/multiarray/calculation.c#L625-L636 values = values.copy() + else: + refs = self.refs return self.make_block_same_class(values, refs=refs) # --------------------------------------------------------------------- diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 13c039cef3f91..2e20e97ca53b2 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1332,7 +1332,13 @@ def column_setitem( This is a method on the BlockManager level, to avoid creating an intermediate Series at the DataFrame level (`s = df[loc]; s[idx] = value`) """ - if using_copy_on_write() and not self._has_no_reference(loc): + if warn_copy_on_write() and not self._has_no_reference(loc): + warnings.warn( + COW_WARNING_GENERAL_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) + elif using_copy_on_write() and not self._has_no_reference(loc): blkno = self.blknos[loc] # Split blocks to only copy the column we want to modify blk_loc = self.blklocs[loc] diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 2311ce928ee27..40c3069dfeebf 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -1164,7 +1164,9 @@ def test_assignment_single_assign_new(self): df.eval("c = a + b", inplace=True) tm.assert_frame_equal(df, expected) - def test_assignment_single_assign_local_overlap(self): + # TODO(CoW-warn) this should not warn (DataFrame.eval creates refs to self) + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") + def test_assignment_single_assign_local_overlap(self, warn_copy_on_write): df = DataFrame( np.random.default_rng(2).standard_normal((5, 2)), columns=list("ab") ) @@ -1218,6 +1220,8 @@ def test_column_in(self): tm.assert_series_equal(result, expected, check_names=False) @pytest.mark.xfail(reason="Unknown: Omitted test_ in name prior.") + # TODO(CoW-warn) this should not warn (DataFrame.eval creates refs to self) + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") def test_assignment_not_inplace(self): # see gh-9297 df = DataFrame( @@ -1897,13 +1901,14 @@ def test_eval_no_support_column_name(request, column): tm.assert_frame_equal(result, expected) -def test_set_inplace(using_copy_on_write): +def test_set_inplace(using_copy_on_write, warn_copy_on_write): # https://github.com/pandas-dev/pandas/issues/47449 # Ensure we don't only update the DataFrame inplace, but also the actual # column values, such that references to this column also get updated df = DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) result_view = df[:] ser = df["A"] + # with tm.assert_cow_warning(warn_copy_on_write): df.eval("A = B + C", inplace=True) expected = DataFrame({"A": [11, 13, 15], "B": [4, 5, 6], "C": [7, 8, 9]}) tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/copy_view/test_constructors.py b/pandas/tests/copy_view/test_constructors.py index 221bf8759875f..89384a4ef6ba6 100644 --- a/pandas/tests/copy_view/test_constructors.py +++ b/pandas/tests/copy_view/test_constructors.py @@ -242,8 +242,8 @@ def test_dataframe_from_dict_of_series( assert np.shares_memory(get_array(result, "a"), get_array(s1)) # mutating the new dataframe doesn't mutate original - # TODO(CoW-warn) this should also warn - result.iloc[0, 0] = 10 + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0, 0] = 10 if using_copy_on_write: assert not np.shares_memory(get_array(result, "a"), get_array(s1)) tm.assert_series_equal(s1, s1_orig) diff --git a/pandas/tests/copy_view/test_core_functionalities.py b/pandas/tests/copy_view/test_core_functionalities.py index bfdf2b92fd326..97d77ef33d849 100644 --- a/pandas/tests/copy_view/test_core_functionalities.py +++ b/pandas/tests/copy_view/test_core_functionalities.py @@ -28,27 +28,32 @@ def test_setitem_dont_track_unnecessary_references(using_copy_on_write): assert np.shares_memory(arr, get_array(df, "a")) -def test_setitem_with_view_copies(using_copy_on_write): +def test_setitem_with_view_copies(using_copy_on_write, warn_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1}) view = df[:] expected = df.copy() df["b"] = 100 arr = get_array(df, "a") - df.iloc[0, 0] = 100 # Check that we correctly track reference + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 # Check that we correctly track reference if using_copy_on_write: assert not np.shares_memory(arr, get_array(df, "a")) tm.assert_frame_equal(view, expected) -def test_setitem_with_view_invalidated_does_not_copy(using_copy_on_write, request): +def test_setitem_with_view_invalidated_does_not_copy( + using_copy_on_write, warn_copy_on_write, request +): df = DataFrame({"a": [1, 2, 3], "b": 1, "c": 1}) view = df[:] df["b"] = 100 arr = get_array(df, "a") view = None # noqa: F841 - df.iloc[0, 0] = 100 + # TODO(CoW-warn) false positive? + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 if using_copy_on_write: # Setitem split the block. Since the old block shared data with view # all the new blocks are referencing view and each other. When view diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py index c4d5e9dbce72a..5a0ebff64a803 100644 --- a/pandas/tests/copy_view/test_indexing.py +++ b/pandas/tests/copy_view/test_indexing.py @@ -101,7 +101,7 @@ def test_subset_column_selection_modify_parent(backend, using_copy_on_write): tm.assert_frame_equal(subset, expected) -def test_subset_row_slice(backend, using_copy_on_write): +def test_subset_row_slice(backend, using_copy_on_write, warn_copy_on_write): # Case: taking a subset of the rows of a DataFrame using a slice # + afterwards modifying the subset _, DataFrame, _ = backend @@ -121,7 +121,8 @@ def test_subset_row_slice(backend, using_copy_on_write): # INFO this no longer raise warning since pandas 1.4 # with pd.option_context("chained_assignment", "warn"): # with tm.assert_produces_warning(SettingWithCopyWarning): - subset.iloc[0, 0] = 0 + with tm.assert_cow_warning(warn_copy_on_write): + subset.iloc[0, 0] = 0 subset._mgr._verify_integrity() @@ -334,8 +335,11 @@ def test_subset_set_with_row_indexer( pytest.skip("setitem with labels selects on columns") # TODO(CoW-warn) should warn - if using_copy_on_write or warn_copy_on_write: + if using_copy_on_write: indexer_si(subset)[indexer] = 0 + elif warn_copy_on_write: + with tm.assert_cow_warning(): + indexer_si(subset)[indexer] = 0 else: # INFO iloc no longer raises warning since pandas 1.4 warn = SettingWithCopyWarning if indexer_si is tm.setitem else None @@ -419,7 +423,7 @@ def test_subset_set_column(backend, using_copy_on_write, warn_copy_on_write): "dtype", ["int64", "float64"], ids=["single-block", "mixed-block"] ) def test_subset_set_column_with_loc( - backend, using_copy_on_write, using_array_manager, dtype + backend, using_copy_on_write, warn_copy_on_write, using_array_manager, dtype ): # Case: setting a single column with loc on a viewing subset # -> subset.loc[:, col] = value @@ -432,6 +436,9 @@ def test_subset_set_column_with_loc( if using_copy_on_write: subset.loc[:, "a"] = np.array([10, 11], dtype="int64") + elif warn_copy_on_write: + with tm.assert_cow_warning(): + subset.loc[:, "a"] = np.array([10, 11], dtype="int64") else: with pd.option_context("chained_assignment", "warn"): with tm.assert_produces_warning( @@ -455,7 +462,9 @@ def test_subset_set_column_with_loc( tm.assert_frame_equal(df, df_orig) -def test_subset_set_column_with_loc2(backend, using_copy_on_write, using_array_manager): +def test_subset_set_column_with_loc2( + backend, using_copy_on_write, warn_copy_on_write, using_array_manager +): # Case: setting a single column with loc on a viewing subset # -> subset.loc[:, col] = value # separate test for case of DataFrame of a single column -> takes a separate @@ -467,6 +476,9 @@ def test_subset_set_column_with_loc2(backend, using_copy_on_write, using_array_m if using_copy_on_write: subset.loc[:, "a"] = 0 + elif warn_copy_on_write: + with tm.assert_cow_warning(): + subset.loc[:, "a"] = 0 else: with pd.option_context("chained_assignment", "warn"): with tm.assert_produces_warning( @@ -528,7 +540,9 @@ def test_subset_set_columns(backend, using_copy_on_write, warn_copy_on_write, dt [slice("a", "b"), np.array([True, True, False]), ["a", "b"]], ids=["slice", "mask", "array"], ) -def test_subset_set_with_column_indexer(backend, indexer, using_copy_on_write): +def test_subset_set_with_column_indexer( + backend, indexer, using_copy_on_write, warn_copy_on_write +): # Case: setting multiple columns with a column indexer on a viewing subset # -> subset.loc[:, [col1, col2]] = value _, DataFrame, _ = backend @@ -538,6 +552,9 @@ def test_subset_set_with_column_indexer(backend, indexer, using_copy_on_write): if using_copy_on_write: subset.loc[:, indexer] = 0 + elif warn_copy_on_write: + with tm.assert_cow_warning(): + subset.loc[:, indexer] = 0 else: with pd.option_context("chained_assignment", "warn"): # As of 2.0, this setitem attempts (successfully) to set values @@ -659,10 +676,7 @@ def test_subset_chained_getitem_column( # modify parent -> don't modify subset subset = df[:]["a"][0:2] df._clear_item_cache() - # TODO(CoW-warn) should also warn for mixed block and nullable dtypes - with tm.assert_cow_warning( - warn_copy_on_write and dtype == "int64" and dtype_backend == "numpy" - ): + with tm.assert_cow_warning(warn_copy_on_write): df.iloc[0, 0] = 0 expected = Series([1, 2], name="a") if using_copy_on_write: @@ -765,8 +779,7 @@ def test_null_slice(backend, method, using_copy_on_write, warn_copy_on_write): assert df2 is not df # and those trigger CoW when mutated - # TODO(CoW-warn) should also warn for nullable dtypes - with tm.assert_cow_warning(warn_copy_on_write and dtype_backend == "numpy"): + with tm.assert_cow_warning(warn_copy_on_write): df2.iloc[0, 0] = 0 if using_copy_on_write: tm.assert_frame_equal(df, df_orig) @@ -884,10 +897,10 @@ def test_series_subset_set_with_indexer( # del operator -def test_del_frame(backend, using_copy_on_write): +def test_del_frame(backend, using_copy_on_write, warn_copy_on_write): # Case: deleting a column with `del` on a viewing child dataframe should # not modify parent + update the references - _, DataFrame, _ = backend + dtype_backend, DataFrame, _ = backend df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = df[:] @@ -901,11 +914,14 @@ def test_del_frame(backend, using_copy_on_write): tm.assert_frame_equal(df2, df_orig[["a", "c"]]) df2._mgr._verify_integrity() - df.loc[0, "b"] = 200 + # TODO(CoW-warn) false positive, this should not warn? + with tm.assert_cow_warning(warn_copy_on_write and dtype_backend == "numpy"): + df.loc[0, "b"] = 200 assert np.shares_memory(get_array(df, "a"), get_array(df2, "a")) df_orig = df.copy() - df2.loc[0, "a"] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + df2.loc[0, "a"] = 100 if using_copy_on_write: # modifying child after deleting a column still doesn't update parent tm.assert_frame_equal(df, df_orig) @@ -1109,7 +1125,6 @@ def test_set_value_copy_only_necessary_column( ): # When setting inplace, only copy column that is modified instead of the whole # block (by splitting the block) - single_block = isinstance(col[0], int) df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": col}) df_orig = df.copy() view = df[:] @@ -1120,11 +1135,7 @@ def test_set_value_copy_only_necessary_column( ): indexer_func(df)[indexer] = val else: - # TODO(CoW-warn) should also warn in the other cases - with tm.assert_cow_warning( - warn_copy_on_write - and not (indexer[0] == slice(None) or (not single_block and val == 100)) - ): + with tm.assert_cow_warning(warn_copy_on_write): indexer_func(df)[indexer] = val if using_copy_on_write: diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index 5507e81d04e2a..b2f3312abf8b5 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -324,11 +324,12 @@ def test_fillna_ea_noop_shares_memory( def test_fillna_inplace_ea_noop_shares_memory( - using_copy_on_write, any_numeric_ea_and_arrow_dtype + using_copy_on_write, warn_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[:] + # TODO(CoW-warn) df.fillna(100, inplace=True) if isinstance(df["a"].dtype, ArrowDtype) or using_copy_on_write: @@ -342,7 +343,9 @@ def test_fillna_inplace_ea_noop_shares_memory( assert not df._mgr._has_no_reference(1) assert not view._mgr._has_no_reference(1) - df.iloc[0, 1] = 100 + # TODO(CoW-warn) should this warn for ArrowDtype? + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 1] = 100 if isinstance(df["a"].dtype, ArrowDtype) or using_copy_on_write: tm.assert_frame_equal(df_orig, view) else: diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index 73bb9b4a71741..faa1eec09d30b 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -39,7 +39,7 @@ def test_copy(using_copy_on_write): assert df.iloc[0, 0] == 1 -def test_copy_shallow(using_copy_on_write): +def test_copy_shallow(using_copy_on_write, warn_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_copy = df.copy(deep=False) @@ -69,7 +69,8 @@ def test_copy_shallow(using_copy_on_write): assert np.shares_memory(get_array(df_copy, "c"), get_array(df, "c")) else: # mutating shallow copy does mutate original - df_copy.iloc[0, 0] = 0 + with tm.assert_cow_warning(warn_copy_on_write): + df_copy.iloc[0, 0] = 0 assert df.iloc[0, 0] == 0 # and still shares memory assert np.shares_memory(get_array(df_copy, "a"), get_array(df, "a")) @@ -546,7 +547,7 @@ def test_shift_columns(using_copy_on_write, warn_copy_on_write): tm.assert_frame_equal(df2, expected) -def test_pop(using_copy_on_write): +def test_pop(using_copy_on_write, warn_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() view_original = df[:] @@ -558,7 +559,8 @@ def test_pop(using_copy_on_write): if using_copy_on_write: result.iloc[0] = 0 assert not np.shares_memory(result.values, get_array(view_original, "a")) - df.iloc[0, 0] = 0 + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 0 if using_copy_on_write: assert not np.shares_memory(get_array(df, "b"), get_array(view_original, "b")) tm.assert_frame_equal(view_original, df_orig) @@ -744,7 +746,7 @@ def test_swapaxes_read_only_array(): ], ids=["shallow-copy", "reset_index", "rename", "select_dtypes"], ) -def test_chained_methods(request, method, idx, using_copy_on_write): +def test_chained_methods(request, method, idx, using_copy_on_write, warn_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [0.1, 0.2, 0.3]}) df_orig = df.copy() @@ -753,13 +755,15 @@ def test_chained_methods(request, method, idx, using_copy_on_write): # modify df2 -> don't modify df df2 = method(df) - df2.iloc[0, idx] = 0 + with tm.assert_cow_warning(warn_copy_on_write and df2_is_view): + df2.iloc[0, idx] = 0 if not df2_is_view: tm.assert_frame_equal(df, df_orig) # modify df -> don't modify df2 df2 = method(df) - df.iloc[0, 0] = 0 + with tm.assert_cow_warning(warn_copy_on_write and df2_is_view): + df.iloc[0, 0] = 0 if not df2_is_view: tm.assert_frame_equal(df2.iloc[:, idx:], df_orig) @@ -908,7 +912,7 @@ def test_dropna_series(using_copy_on_write, val): lambda df: df.tail(3), ], ) -def test_head_tail(method, using_copy_on_write): +def test_head_tail(method, using_copy_on_write, warn_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]}) df_orig = df.copy() df2 = method(df) @@ -921,14 +925,16 @@ def test_head_tail(method, using_copy_on_write): assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) # modify df2 to trigger CoW for that block - df2.iloc[0, 0] = 0 + with tm.assert_cow_warning(warn_copy_on_write): + df2.iloc[0, 0] = 0 if using_copy_on_write: assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) else: # without CoW enabled, head and tail return views. Mutating df2 also mutates df. assert np.shares_memory(get_array(df2, "b"), get_array(df, "b")) - df2.iloc[0, 0] = 1 + with tm.assert_cow_warning(warn_copy_on_write): + df2.iloc[0, 0] = 1 tm.assert_frame_equal(df, df_orig) @@ -1160,7 +1166,7 @@ def test_sort_values_inplace(using_copy_on_write, obj, kwargs, warn_copy_on_writ @pytest.mark.parametrize("decimals", [-1, 0, 1]) -def test_round(using_copy_on_write, decimals): +def test_round(using_copy_on_write, warn_copy_on_write, decimals): df = DataFrame({"a": [1, 2], "b": "c"}) df_orig = df.copy() df2 = df.round(decimals=decimals) @@ -1175,6 +1181,7 @@ def test_round(using_copy_on_write, decimals): assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) else: assert not np.shares_memory(get_array(df2, "b"), get_array(df, "b")) + assert not np.shares_memory(get_array(df2, "a"), get_array(df, "a")) df2.iloc[0, 1] = "d" df2.iloc[0, 0] = 4 @@ -1756,13 +1763,15 @@ def test_xs_multiindex( tm.assert_frame_equal(df, df_orig) -def test_update_frame(using_copy_on_write): +def test_update_frame(using_copy_on_write, warn_copy_on_write): df1 = DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]}) df2 = DataFrame({"b": [100.0]}, index=[1]) df1_orig = df1.copy() view = df1[:] - df1.update(df2) + # TODO(CoW) better warning message? + with tm.assert_cow_warning(warn_copy_on_write): + df1.update(df2) expected = DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 100.0, 6.0]}) tm.assert_frame_equal(df1, expected) @@ -1947,7 +1956,7 @@ def test_eval(using_copy_on_write): tm.assert_frame_equal(df, df_orig) -def test_eval_inplace(using_copy_on_write): +def test_eval_inplace(using_copy_on_write, warn_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": 1}) df_orig = df.copy() df_view = df[:] @@ -1955,6 +1964,7 @@ def test_eval_inplace(using_copy_on_write): df.eval("c = a+b", inplace=True) assert np.shares_memory(get_array(df, "a"), get_array(df_view, "a")) - df.iloc[0, 0] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 if using_copy_on_write: tm.assert_frame_equal(df_view, df_orig) diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index 83e2c795b8b5e..b8ede450b3c1a 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -402,7 +402,7 @@ def test_setitem_frame_2d_values(self, data): orig = df.copy() - df.iloc[:] = df + df.iloc[:] = df.copy() tm.assert_frame_equal(df, orig) df.iloc[:-1] = df.iloc[:-1].copy() diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 93f391b16817c..d76bfd2d7ae7c 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -561,7 +561,7 @@ def test_getitem_setitem_integer_slice_keyerrors(self): @td.skip_array_manager_invalid_test # already covered in test_iloc_col_slice_view def test_fancy_getitem_slice_mixed( - self, float_frame, float_string_frame, using_copy_on_write + self, float_frame, float_string_frame, using_copy_on_write, warn_copy_on_write ): sliced = float_string_frame.iloc[:, -3:] assert sliced["D"].dtype == np.float64 @@ -573,7 +573,8 @@ def test_fancy_getitem_slice_mixed( assert np.shares_memory(sliced["C"]._values, float_frame["C"]._values) - sliced.loc[:, "C"] = 4.0 + with tm.assert_cow_warning(warn_copy_on_write): + sliced.loc[:, "C"] = 4.0 if not using_copy_on_write: assert (float_frame["C"] == 4).all() @@ -1049,7 +1050,7 @@ def test_iloc_row(self): expected = df.reindex(df.index[[1, 2, 4, 6]]) tm.assert_frame_equal(result, expected) - def test_iloc_row_slice_view(self, using_copy_on_write, request): + def test_iloc_row_slice_view(self, using_copy_on_write, warn_copy_on_write): df = DataFrame( np.random.default_rng(2).standard_normal((10, 4)), index=range(0, 20, 2) ) @@ -1062,9 +1063,9 @@ def test_iloc_row_slice_view(self, using_copy_on_write, request): assert np.shares_memory(df[2], subset[2]) exp_col = original[2].copy() - subset.loc[:, 2] = 0.0 - if not using_copy_on_write: + with tm.assert_cow_warning(warn_copy_on_write): subset.loc[:, 2] = 0.0 + if not using_copy_on_write: exp_col._values[4:8] = 0.0 # With the enforcement of GH#45333 in 2.0, this remains a view @@ -1094,7 +1095,9 @@ def test_iloc_col(self): expected = df.reindex(columns=df.columns[[1, 2, 4, 6]]) tm.assert_frame_equal(result, expected) - def test_iloc_col_slice_view(self, using_array_manager, using_copy_on_write): + def test_iloc_col_slice_view( + self, using_array_manager, using_copy_on_write, warn_copy_on_write + ): df = DataFrame( np.random.default_rng(2).standard_normal((4, 10)), columns=range(0, 20, 2) ) @@ -1105,7 +1108,8 @@ def test_iloc_col_slice_view(self, using_array_manager, using_copy_on_write): # verify slice is view assert np.shares_memory(df[8]._values, subset[8]._values) - subset.loc[:, 8] = 0.0 + with tm.assert_cow_warning(warn_copy_on_write): + subset.loc[:, 8] = 0.0 assert (df[8] == 0).all() @@ -1388,12 +1392,13 @@ def test_loc_setitem_rhs_frame(self, idxr, val, warn): tm.assert_frame_equal(df, expected) @td.skip_array_manager_invalid_test - def test_iloc_setitem_enlarge_no_warning(self): + def test_iloc_setitem_enlarge_no_warning(self, warn_copy_on_write): # GH#47381 df = DataFrame(columns=["a", "b"]) expected = df.copy() view = df[:] - with tm.assert_produces_warning(None): + # TODO(CoW-warn) false positive: shouldn't warn in case of enlargement? + with tm.assert_produces_warning(FutureWarning if warn_copy_on_write else None): df.iloc[:, 0] = np.array([1, 2], dtype=np.float64) tm.assert_frame_equal(view, expected) diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 49dd7a3c4df9b..4e37d8ff3c024 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -816,7 +816,7 @@ def test_setitem_object_array_of_tzaware_datetimes(self, idx, expected): class TestDataFrameSetItemWithExpansion: - def test_setitem_listlike_views(self, using_copy_on_write): + def test_setitem_listlike_views(self, using_copy_on_write, warn_copy_on_write): # GH#38148 df = DataFrame({"a": [1, 2, 3], "b": [4, 4, 6]}) @@ -827,7 +827,8 @@ def test_setitem_listlike_views(self, using_copy_on_write): df[["c", "d"]] = np.array([[0.1, 0.2], [0.3, 0.4], [0.4, 0.5]]) # edit in place the first column to check view semantics - df.iloc[0, 0] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + df.iloc[0, 0] = 100 if using_copy_on_write: expected = Series([1, 2, 3], name="a") diff --git a/pandas/tests/frame/methods/test_diff.py b/pandas/tests/frame/methods/test_diff.py index 1b7e669232592..bef18dbaf8a8a 100644 --- a/pandas/tests/frame/methods/test_diff.py +++ b/pandas/tests/frame/methods/test_diff.py @@ -89,7 +89,7 @@ def test_diff_datetime_with_nat_zero_periods(self, tz): # diff on NaT values should give NaT, not timedelta64(0) dti = date_range("2016-01-01", periods=4, tz=tz) ser = Series(dti) - df = ser.to_frame() + df = ser.to_frame().copy() df[1] = ser.copy() diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 52b4b64ee279f..a32f290d3aa12 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -20,14 +20,18 @@ class TestFillNA: - def test_fillna_dict_inplace_nonunique_columns(self, using_copy_on_write): + def test_fillna_dict_inplace_nonunique_columns( + self, using_copy_on_write, warn_copy_on_write + ): df = DataFrame( {"A": [np.nan] * 3, "B": [NaT, Timestamp(1), NaT], "C": [np.nan, "foo", 2]} ) df.columns = ["A", "A", "A"] orig = df[:] - df.fillna({"A": 2}, inplace=True) + # TODO(CoW-warn) better warning message + with tm.assert_cow_warning(warn_copy_on_write): + df.fillna({"A": 2}, inplace=True) # The first and third columns can be set inplace, while the second cannot. expected = DataFrame( @@ -733,12 +737,16 @@ def test_fillna_inplace_with_columns_limit_and_value(self): @td.skip_array_manager_invalid_test @pytest.mark.parametrize("val", [-1, {"x": -1, "y": -1}]) - def test_inplace_dict_update_view(self, val, using_copy_on_write): + def test_inplace_dict_update_view( + self, val, using_copy_on_write, warn_copy_on_write + ): # GH#47188 df = DataFrame({"x": [np.nan, 2], "y": [np.nan, 2]}) df_orig = df.copy() result_view = df[:] - df.fillna(val, inplace=True) + # TODO(CoW-warn) better warning message + should warn in all cases + with tm.assert_cow_warning(warn_copy_on_write and not isinstance(val, int)): + df.fillna(val, inplace=True) expected = DataFrame({"x": [-1, 2.0], "y": [-1.0, 2]}) tm.assert_frame_equal(df, expected) if using_copy_on_write: diff --git a/pandas/tests/frame/methods/test_rename.py b/pandas/tests/frame/methods/test_rename.py index b965a5d973fb6..c3bc96b44c807 100644 --- a/pandas/tests/frame/methods/test_rename.py +++ b/pandas/tests/frame/methods/test_rename.py @@ -164,12 +164,13 @@ def test_rename_multiindex(self): renamed = df.rename(index={"foo1": "foo3", "bar2": "bar3"}, level=0) tm.assert_index_equal(renamed.index, new_index) - def test_rename_nocopy(self, float_frame, using_copy_on_write): + def test_rename_nocopy(self, float_frame, using_copy_on_write, warn_copy_on_write): renamed = float_frame.rename(columns={"C": "foo"}, copy=False) assert np.shares_memory(renamed["foo"]._values, float_frame["C"]._values) - renamed.loc[:, "foo"] = 1.0 + with tm.assert_cow_warning(warn_copy_on_write): + renamed.loc[:, "foo"] = 1.0 if using_copy_on_write: assert not (float_frame["C"] == 1.0).all() else: diff --git a/pandas/tests/frame/methods/test_to_dict_of_blocks.py b/pandas/tests/frame/methods/test_to_dict_of_blocks.py index 471b9eaf936ad..28973fe0d7900 100644 --- a/pandas/tests/frame/methods/test_to_dict_of_blocks.py +++ b/pandas/tests/frame/methods/test_to_dict_of_blocks.py @@ -30,6 +30,7 @@ def test_copy_blocks(self, float_frame): # make sure we did not change the original DataFrame assert _last_df is not None and not _last_df[column].equals(df[column]) + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") def test_no_copy_blocks(self, float_frame, using_copy_on_write): # GH#9607 df = DataFrame(float_frame, copy=True) diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index 5738a25f26fcb..0d32788b04b03 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -154,13 +154,15 @@ def test_update_with_different_dtype(self, using_copy_on_write): tm.assert_frame_equal(df, expected) @td.skip_array_manager_invalid_test - def test_update_modify_view(self, using_copy_on_write): + def test_update_modify_view(self, using_copy_on_write, warn_copy_on_write): # GH#47188 df = DataFrame({"A": ["1", np.nan], "B": ["100", np.nan]}) df2 = DataFrame({"A": ["a", "x"], "B": ["100", "200"]}) df2_orig = df2.copy() result_view = df2[:] - df2.update(df) + # TODO(CoW-warn) better warning message + with tm.assert_cow_warning(warn_copy_on_write): + df2.update(df) expected = DataFrame({"A": ["1", "x"], "B": ["100", "200"]}) tm.assert_frame_equal(df2, expected) if using_copy_on_write: diff --git a/pandas/tests/groupby/methods/test_nth.py b/pandas/tests/groupby/methods/test_nth.py index e3005c9b971ec..4a5571d0daa42 100644 --- a/pandas/tests/groupby/methods/test_nth.py +++ b/pandas/tests/groupby/methods/test_nth.py @@ -44,7 +44,9 @@ def test_first_last_nth(df): grouped["B"].last() grouped["B"].nth(0) + df = df.copy() df.loc[df["A"] == "foo", "B"] = np.nan + grouped = df.groupby("A") assert isna(grouped["B"].first()["foo"]) assert isna(grouped["B"].last()["foo"]) assert isna(grouped["B"].nth(0).iloc[0]) diff --git a/pandas/tests/groupby/methods/test_quantile.py b/pandas/tests/groupby/methods/test_quantile.py index d949e5e36fa81..361a8c27fbf9d 100644 --- a/pandas/tests/groupby/methods/test_quantile.py +++ b/pandas/tests/groupby/methods/test_quantile.py @@ -447,8 +447,7 @@ def test_timestamp_groupby_quantile(unit): 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 = pd.Series(dti).to_frame().copy() df[1] = dti.tz_localize("US/Pacific") df[2] = dti.to_period("D") df[3] = dti - dti[0] diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 3237c8f52797a..e31b675efb69a 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -201,7 +201,9 @@ def test_multiindex_assignment(self): df.loc[4, "d"] = arr tm.assert_series_equal(df.loc[4, "d"], Series(arr, index=[8, 10], name="d")) - def test_multiindex_assignment_single_dtype(self, using_copy_on_write): + def test_multiindex_assignment_single_dtype( + self, using_copy_on_write, warn_copy_on_write + ): # GH3777 part 2b # single dtype arr = np.array([0.0, 1.0]) @@ -215,6 +217,8 @@ def test_multiindex_assignment_single_dtype(self, using_copy_on_write): view = df["c"].iloc[:2].values # arr can be losslessly cast to int, so this setitem is inplace + # INFO(CoW-warn) this does not warn because we directly took .values + # above, so no reference to a pandas object is alive for `view` df.loc[4, "c"] = arr exp = Series(arr, index=[8, 10], name="c", dtype="int64") result = df.loc[4, "c"] @@ -234,7 +238,8 @@ def test_multiindex_assignment_single_dtype(self, using_copy_on_write): tm.assert_series_equal(result, exp) # scalar ok - df.loc[4, "c"] = 10 + with tm.assert_cow_warning(warn_copy_on_write): + df.loc[4, "c"] = 10 exp = Series(10, index=[8, 10], name="c", dtype="float64") tm.assert_series_equal(df.loc[4, "c"], exp) @@ -248,7 +253,8 @@ def test_multiindex_assignment_single_dtype(self, using_copy_on_write): # But with a length-1 listlike column indexer this behaves like # `df.loc[4, "c"] = 0 - df.loc[4, ["c"]] = [0] + with tm.assert_cow_warning(warn_copy_on_write): + df.loc[4, ["c"]] = [0] assert (df.loc[4, "c"] == 0).all() def test_groupby_example(self): diff --git a/pandas/tests/indexing/test_iat.py b/pandas/tests/indexing/test_iat.py index b4c4b81ac9cfb..5b8c4f2d4b9b9 100644 --- a/pandas/tests/indexing/test_iat.py +++ b/pandas/tests/indexing/test_iat.py @@ -41,11 +41,10 @@ def test_iat_setitem_item_cache_cleared( # previously this iat setting would split the block and fail to clear # the item_cache. - with tm.assert_cow_warning(warn_copy_on_write and indexer_ial is tm.iloc): + with tm.assert_cow_warning(warn_copy_on_write): indexer_ial(df)[7, 0] = 9999 - # TODO(CoW-warn) should also warn for iat? - with tm.assert_cow_warning(warn_copy_on_write and indexer_ial is tm.iloc): + with tm.assert_cow_warning(warn_copy_on_write): indexer_ial(df)[7, 1] = 1234 assert df.iat[7, 1] == 1234 diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 5c0c1b42ca963..b3f93cbfd4113 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -850,9 +850,8 @@ def test_identity_slice_returns_new_object( # Setting using .loc[:, "a"] sets inplace so alters both sliced and orig # depending on CoW - # TODO(CoW-warn) this should warn - # with tm.assert_cow_warning(warn_copy_on_write): - original_df.loc[:, "a"] = [4, 4, 4] + with tm.assert_cow_warning(warn_copy_on_write): + original_df.loc[:, "a"] = [4, 4, 4] if using_copy_on_write: assert (sliced_df["a"] == [1, 2, 3]).all() else: @@ -1142,7 +1141,7 @@ def test_iloc_getitem_with_duplicates2(self): expected = df.take([0], axis=1) tm.assert_frame_equal(result, expected) - def test_iloc_interval(self): + def test_iloc_interval(self, warn_copy_on_write): # GH#17130 df = DataFrame({Interval(1, 2): [1, 2]}) @@ -1155,7 +1154,9 @@ def test_iloc_interval(self): tm.assert_series_equal(result, expected) result = df.copy() - result.iloc[:, 0] += 1 + # TODO(CoW-warn) false positive + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[:, 0] += 1 expected = DataFrame({Interval(1, 2): [2, 3]}) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 35c50d6c705d1..96fd3f4e6fca0 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -828,7 +828,8 @@ def test_loc_setitem_frame_mixed_labels(self): df.loc[0, [1, 2]] = [5, 6] tm.assert_frame_equal(df, expected) - def test_loc_setitem_frame_multiples(self): + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") + def test_loc_setitem_frame_multiples(self, warn_copy_on_write): # multiple setting df = DataFrame( {"A": ["foo", "bar", "baz"], "B": Series(range(3), dtype=np.int64)} @@ -1097,9 +1098,8 @@ def test_identity_slice_returns_new_object( # Setting using .loc[:, "a"] sets inplace so alters both sliced and orig # depending on CoW - # TODO(CoW-warn) should warn - # with tm.assert_cow_warning(warn_copy_on_write): - original_df.loc[:, "a"] = [4, 4, 4] + with tm.assert_cow_warning(warn_copy_on_write): + original_df.loc[:, "a"] = [4, 4, 4] if using_copy_on_write: assert (sliced_df["a"] == [1, 2, 3]).all() else: diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 018400fcfe0cf..26035d1af7f90 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -288,6 +288,8 @@ def test_read_expands_user_home_dir( ): reader(path) + # TODO(CoW-warn) avoid warnings in the stata reader code + @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") @pytest.mark.parametrize( "reader, module, path", [ diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 0a72fd7bbec7d..cd4075076062c 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -721,21 +721,15 @@ def test_basic_subset_columns(self, pa, df_full): def test_to_bytes_without_path_or_buf_provided(self, pa, df_full): # GH 37105 - msg = "Mismatched null-like values nan and None found" - warn = None - if using_copy_on_write(): - warn = FutureWarning - buf_bytes = df_full.to_parquet(engine=pa) assert isinstance(buf_bytes, bytes) buf_stream = BytesIO(buf_bytes) res = read_parquet(buf_stream) - expected = df_full.copy(deep=False) + expected = df_full.copy() expected.loc[1, "string_with_nan"] = None - with tm.assert_produces_warning(warn, match=msg): - tm.assert_frame_equal(df_full, res) + tm.assert_frame_equal(res, expected) def test_duplicate_columns(self, pa): # not currently able to handle duplicate columns diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index c8ff42509505a..82e6c2964b8c5 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -32,6 +32,11 @@ read_stata, ) +# TODO(CoW-warn) avoid warnings in the stata reader code +pytestmark = pytest.mark.filterwarnings( + "ignore:Setting a value on a view:FutureWarning" +) + @pytest.fixture def mixed_frame(): @@ -178,11 +183,13 @@ def test_read_dta2(self, datapath): path2 = datapath("io", "data", "stata", "stata2_115.dta") path3 = datapath("io", "data", "stata", "stata2_117.dta") - with tm.assert_produces_warning(UserWarning): + # TODO(CoW-warn) avoid warnings in the stata reader code + # once fixed -> remove `raise_on_extra_warnings=False` again + with tm.assert_produces_warning(UserWarning, raise_on_extra_warnings=False): parsed_114 = self.read_dta(path1) - with tm.assert_produces_warning(UserWarning): + with tm.assert_produces_warning(UserWarning, raise_on_extra_warnings=False): parsed_115 = self.read_dta(path2) - with tm.assert_produces_warning(UserWarning): + with tm.assert_produces_warning(UserWarning, raise_on_extra_warnings=False): parsed_117 = self.read_dta(path3) # FIXME: don't leave commented-out # 113 is buggy due to limits of date format support in Stata
Next subtask of https://github.com/pandas-dev/pandas/issues/56019. This tackles `mgr.column_setitem`, which is used to set values into a single column (but not setting the full column, so like `df.loc[idx, "col"] = ..`)
https://api.github.com/repos/pandas-dev/pandas/pulls/56020
2023-11-17T10:06:57Z
2023-11-17T19:03:38Z
2023-11-17T19:03:38Z
2023-11-27T11:37:57Z
remove ctypedef class from lib.pyx
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 5b705e80f97f5..42b5c18f3d444 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -67,23 +67,6 @@ from numpy cimport ( cnp.import_array() -cdef extern from "numpy/arrayobject.h": - # cython's numpy.dtype specification is incorrect, which leads to - # errors in issubclass(self.dtype.type, np.bool_), so we directly - # include the correct version - # https://github.com/cython/cython/issues/2022 - - ctypedef class numpy.dtype [object PyArray_Descr]: - # Use PyDataType_* macros when possible, however there are no macros - # for accessing some of the fields, so some are defined. Please - # ask on cython-dev if you need more. - cdef: - int type_num - int itemsize "elsize" - char byteorder - object fields - tuple names - cdef extern from "pandas/parser/pd_parser.h": int floatify(object, float64_t *result, int *maybe_int) except -1 void PandasParser_IMPORT() @@ -1736,10 +1719,10 @@ cdef class Validator: cdef: Py_ssize_t n - dtype dtype + cnp.dtype dtype bint skipna - def __cinit__(self, Py_ssize_t n, dtype dtype=np.dtype(np.object_), + def __cinit__(self, Py_ssize_t n, cnp.dtype dtype=np.dtype(np.object_), bint skipna=False): self.n = n self.dtype = dtype @@ -1820,7 +1803,7 @@ cdef class BoolValidator(Validator): return util.is_bool_object(value) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.bool_) + return cnp.PyDataType_ISBOOL(self.dtype) cpdef bint is_bool_array(ndarray values, bint skipna=False): @@ -1837,7 +1820,7 @@ cdef class IntegerValidator(Validator): return util.is_integer_object(value) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.integer) + return cnp.PyDataType_ISINTEGER(self.dtype) # Note: only python-exposed for tests @@ -1869,7 +1852,7 @@ cdef class IntegerFloatValidator(Validator): return util.is_integer_object(value) or util.is_float_object(value) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.integer) + return cnp.PyDataType_ISINTEGER(self.dtype) cdef bint is_integer_float_array(ndarray values, bint skipna=True): @@ -1886,7 +1869,7 @@ cdef class FloatValidator(Validator): return util.is_float_object(value) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.floating) + return cnp.PyDataType_ISFLOAT(self.dtype) # Note: only python-exposed for tests @@ -1905,7 +1888,7 @@ cdef class ComplexValidator(Validator): ) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.complexfloating) + return cnp.PyDataType_ISCOMPLEX(self.dtype) cdef bint is_complex_array(ndarray values): @@ -1934,7 +1917,7 @@ cdef class StringValidator(Validator): return isinstance(value, str) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.str_) + return self.dtype.type_num == cnp.NPY_UNICODE cpdef bint is_string_array(ndarray values, bint skipna=False): @@ -1951,7 +1934,7 @@ cdef class BytesValidator(Validator): return isinstance(value, bytes) cdef bint is_array_typed(self) except -1: - return issubclass(self.dtype.type, np.bytes_) + return self.dtype.type_num == cnp.NPY_STRING cdef bint is_bytes_array(ndarray values, bint skipna=False): @@ -1966,7 +1949,7 @@ cdef class TemporalValidator(Validator): cdef: bint all_generic_na - def __cinit__(self, Py_ssize_t n, dtype dtype=np.dtype(np.object_), + def __cinit__(self, Py_ssize_t n, cnp.dtype dtype=np.dtype(np.object_), bint skipna=False): self.n = n self.dtype = dtype
@jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/56018
2023-11-17T05:39:51Z
2023-11-17T22:54:11Z
2023-11-17T22:54:11Z
2023-11-17T23:00:14Z
BUG: Bad shift_forward around UTC+0 when DST
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index efa4a52993a90..1c2a37cb829b9 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -360,7 +360,7 @@ Timezones ^^^^^^^^^ - Bug in :class:`AbstractHolidayCalendar` where timezone data was not propagated when computing holiday observances (:issue:`54580`) - Bug in :class:`Timestamp` construction with an ambiguous value and a ``pytz`` timezone failing to raise ``pytz.AmbiguousTimeError`` (:issue:`55657`) -- +- Bug in :meth:`Timestamp.tz_localize` with ``nonexistent="shift_forward`` around UTC+0 during DST (:issue:`51501`) Numeric ^^^^^^^ diff --git a/pandas/_libs/tslibs/tzconversion.pyx b/pandas/_libs/tslibs/tzconversion.pyx index e77a385113e93..2c4f0cd14db13 100644 --- a/pandas/_libs/tslibs/tzconversion.pyx +++ b/pandas/_libs/tslibs/tzconversion.pyx @@ -416,8 +416,13 @@ timedelta-like} else: delta_idx = bisect_right_i8(info.tdata, new_local, info.ntrans) - - delta_idx = delta_idx - delta_idx_offset + # Logic similar to the precompute section. But check the current + # delta in case we are moving between UTC+0 and non-zero timezone + if (shift_forward or shift_delta > 0) and \ + info.deltas[delta_idx - 1] >= 0: + delta_idx = delta_idx - 1 + else: + delta_idx = delta_idx - delta_idx_offset result[i] = new_local - info.deltas[delta_idx] elif fill_nonexist: result[i] = NPY_NAT diff --git a/pandas/tests/scalar/timestamp/methods/test_tz_localize.py b/pandas/tests/scalar/timestamp/methods/test_tz_localize.py index 247a583bc38f3..9df0a023730de 100644 --- a/pandas/tests/scalar/timestamp/methods/test_tz_localize.py +++ b/pandas/tests/scalar/timestamp/methods/test_tz_localize.py @@ -123,6 +123,44 @@ def test_tz_localize_nonexistent(self, stamp, tz): ts.tz_localize(tz, nonexistent="raise") assert ts.tz_localize(tz, nonexistent="NaT") is NaT + @pytest.mark.parametrize( + "stamp, tz, forward_expected, backward_expected", + [ + ( + "2015-03-29 02:00:00", + "Europe/Warsaw", + "2015-03-29 03:00:00", + "2015-03-29 01:59:59", + ), # utc+1 -> utc+2 + ( + "2023-03-12 02:00:00", + "America/Los_Angeles", + "2023-03-12 03:00:00", + "2023-03-12 01:59:59", + ), # utc-8 -> utc-7 + ( + "2023-03-26 01:00:00", + "Europe/London", + "2023-03-26 02:00:00", + "2023-03-26 00:59:59", + ), # utc+0 -> utc+1 + ( + "2023-03-26 00:00:00", + "Atlantic/Azores", + "2023-03-26 01:00:00", + "2023-03-25 23:59:59", + ), # utc-1 -> utc+0 + ], + ) + def test_tz_localize_nonexistent_shift( + self, stamp, tz, forward_expected, backward_expected + ): + ts = Timestamp(stamp) + forward_ts = ts.tz_localize(tz, nonexistent="shift_forward") + assert forward_ts == Timestamp(forward_expected, tz=tz) + backward_ts = ts.tz_localize(tz, nonexistent="shift_backward") + assert backward_ts == Timestamp(backward_expected, tz=tz) + def test_tz_localize_ambiguous_raise(self): # GH#13057 ts = Timestamp("2015-11-1 01:00")
- [ ] closes #51501 - [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 an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. - The algo originates from https://github.com/pandas-dev/pandas/pull/22644. - A related bug fix later in https://github.com/pandas-dev/pandas/pull/23406 but failed to take care of edge cases where we move in/out of UTC+0. - The 3rd and 4th test case related to utc+0 all fail on main - More tests added.
https://api.github.com/repos/pandas-dev/pandas/pulls/56017
2023-11-17T04:55:07Z
2023-11-21T15:36:17Z
2023-11-21T15:36:17Z
2023-11-21T15:36:26Z
BUG: GroupBy.value_counts sorting order
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 93b0ccad9f2aa..18c9d2fb8e3ba 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -444,6 +444,9 @@ Groupby/resample/rolling - Bug in :meth:`DataFrame.resample` not respecting ``closed`` and ``label`` arguments for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55282`) - Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55281`) - Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.MonthBegin` (:issue:`55271`) +- Bug in :meth:`DataFrameGroupBy.value_counts` and :meth:`SeriesGroupBy.value_count` could result in incorrect sorting if the columns of the DataFrame or name of the Series are integers (:issue:`56007`) +- Bug in :meth:`DataFrameGroupBy.value_counts` and :meth:`SeriesGroupBy.value_count` would not respect ``sort=False`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` (:issue:`56007`) +- Bug in :meth:`DataFrameGroupBy.value_counts` and :meth:`SeriesGroupBy.value_count` would sort by proportions rather than frequencies when ``sort=True`` and ``normalize=True`` (:issue:`56007`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 3412f18a40313..c17badccfb59a 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2821,11 +2821,27 @@ def _value_counts( for grouping in groupings ): levels_list = [ping.result_index for ping in groupings] - multi_index, _ = MultiIndex.from_product( + multi_index = MultiIndex.from_product( levels_list, names=[ping.name for ping in groupings] - ).sortlevel() + ) result_series = result_series.reindex(multi_index, fill_value=0) + if sort: + # Sort by the values + result_series = result_series.sort_values( + ascending=ascending, kind="stable" + ) + if self.sort: + # Sort by the groupings + names = result_series.index.names + # GH#56007 - Temporarily replace names in case they are integers + result_series.index.names = range(len(names)) + index_level = list(range(len(self.grouper.groupings))) + result_series = result_series.sort_index( + level=index_level, sort_remaining=False + ) + result_series.index.names = names + if normalize: # Normalize the results by dividing by the original group sizes. # We are guaranteed to have the first N levels be the @@ -2845,13 +2861,6 @@ def _value_counts( # Handle groups of non-observed categories result_series = result_series.fillna(0.0) - if sort: - # Sort the values and then resort by the main grouping - index_level = range(len(self.grouper.groupings)) - result_series = result_series.sort_values(ascending=ascending).sort_index( - level=index_level, sort_remaining=False - ) - result: Series | DataFrame if self.as_index: result = result_series diff --git a/pandas/tests/groupby/methods/test_value_counts.py b/pandas/tests/groupby/methods/test_value_counts.py index 200fa5fd4367d..2fa79c815d282 100644 --- a/pandas/tests/groupby/methods/test_value_counts.py +++ b/pandas/tests/groupby/methods/test_value_counts.py @@ -385,8 +385,8 @@ def test_against_frame_and_seriesgroupby( "sort, ascending, expected_rows, expected_count, expected_group_size", [ (False, None, [0, 1, 2, 3, 4], [1, 1, 1, 2, 1], [1, 3, 1, 3, 1]), - (True, False, [4, 3, 1, 2, 0], [1, 2, 1, 1, 1], [1, 3, 3, 1, 1]), - (True, True, [4, 1, 3, 2, 0], [1, 1, 2, 1, 1], [1, 3, 3, 1, 1]), + (True, False, [3, 0, 1, 2, 4], [2, 1, 1, 1, 1], [3, 1, 3, 1, 1]), + (True, True, [0, 1, 2, 4, 3], [1, 1, 1, 1, 2], [1, 3, 1, 1, 3]), ], ) def test_compound( @@ -811,19 +811,19 @@ def test_categorical_single_grouper_observed_false( ("FR", "female", "high"), ("FR", "male", "medium"), ("FR", "female", "low"), - ("FR", "male", "high"), ("FR", "female", "medium"), + ("FR", "male", "high"), ("US", "female", "high"), ("US", "male", "low"), - ("US", "male", "medium"), - ("US", "male", "high"), - ("US", "female", "medium"), ("US", "female", "low"), - ("ASIA", "male", "low"), - ("ASIA", "male", "high"), - ("ASIA", "female", "medium"), - ("ASIA", "female", "low"), + ("US", "female", "medium"), + ("US", "male", "high"), + ("US", "male", "medium"), ("ASIA", "female", "high"), + ("ASIA", "female", "low"), + ("ASIA", "female", "medium"), + ("ASIA", "male", "high"), + ("ASIA", "male", "low"), ("ASIA", "male", "medium"), ] @@ -1177,3 +1177,65 @@ def test_value_counts_integer_columns(): {1: ["a", "a", "a"], 2: ["a", "a", "d"], 3: ["a", "b", "c"], "count": 1} ) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("vc_sort", [True, False]) +@pytest.mark.parametrize("normalize", [True, False]) +def test_value_counts_sort(sort, vc_sort, normalize): + # GH#55951 + df = DataFrame({"a": [2, 1, 1, 1], 0: [3, 4, 3, 3]}) + gb = df.groupby("a", sort=sort) + result = gb.value_counts(sort=vc_sort, normalize=normalize) + + if normalize: + values = [2 / 3, 1 / 3, 1.0] + else: + values = [2, 1, 1] + index = MultiIndex( + levels=[[1, 2], [3, 4]], codes=[[0, 0, 1], [0, 1, 0]], names=["a", 0] + ) + expected = Series(values, index=index, name="proportion" if normalize else "count") + if sort and vc_sort: + taker = [0, 1, 2] + elif sort and not vc_sort: + taker = [0, 1, 2] + elif not sort and vc_sort: + taker = [0, 2, 1] + else: + taker = [2, 1, 0] + expected = expected.take(taker) + + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("vc_sort", [True, False]) +@pytest.mark.parametrize("normalize", [True, False]) +def test_value_counts_sort_categorical(sort, vc_sort, normalize): + # GH#55951 + df = DataFrame({"a": [2, 1, 1, 1], 0: [3, 4, 3, 3]}, dtype="category") + gb = df.groupby("a", sort=sort, observed=True) + result = gb.value_counts(sort=vc_sort, normalize=normalize) + + if normalize: + values = [2 / 3, 1 / 3, 1.0, 0.0] + else: + values = [2, 1, 1, 0] + name = "proportion" if normalize else "count" + expected = DataFrame( + { + "a": Categorical([1, 1, 2, 2]), + 0: Categorical([3, 4, 3, 4]), + name: values, + } + ).set_index(["a", 0])[name] + if sort and vc_sort: + taker = [0, 1, 2, 3] + elif sort and not vc_sort: + taker = [0, 1, 2, 3] + elif not sort and vc_sort: + taker = [0, 2, 1, 3] + else: + taker = [2, 3, 0, 1] + expected = expected.take(taker) + + tm.assert_series_equal(result, expected)
- [x] closes #56007 (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/56016
2023-11-17T04:15:58Z
2023-11-17T22:55:31Z
2023-11-17T22:55:31Z
2023-12-19T11:36:28Z
CI/TST: Skip pyarrow csv tests where parsing fails
diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 9785b81ae9e0b..e156b1e0aeca2 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -23,7 +23,7 @@ defaults: jobs: ubuntu: runs-on: ubuntu-22.04 - timeout-minutes: 180 + timeout-minutes: 90 strategy: matrix: env_file: [actions-39.yaml, actions-310.yaml, actions-311.yaml] @@ -177,7 +177,7 @@ jobs: if: ${{ matrix.pattern == '' && (always() && steps.build.outcome == 'success')}} macos-windows: - timeout-minutes: 180 + timeout-minutes: 90 strategy: matrix: os: [macos-latest, windows-latest] @@ -322,7 +322,7 @@ jobs: matrix: os: [ubuntu-22.04, macOS-latest, windows-latest] - timeout-minutes: 180 + timeout-minutes: 90 concurrency: #https://github.community/t/concurrecy-not-work-for-push/183068/7 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 a6e68cb984ef4..69c39fdf4cdbe 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -222,8 +222,10 @@ def test_eof_states(all_parsers, data, kwargs, expected, msg, request): return if parser.engine == "pyarrow" and "\r" not in data: - mark = pytest.mark.xfail(reason="Mismatched exception type/message") - request.applymarker(mark) + # pandas.errors.ParserError: CSV parse error: Expected 3 columns, got 1: + # ValueError: skiprows argument must be an integer when using engine='pyarrow' + # AssertionError: Regex pattern did not match. + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") if expected is None: with pytest.raises(ParserError, match=msg): diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py index 3580c040688d8..36d7a19cf6781 100644 --- a/pandas/tests/io/parser/test_encoding.py +++ b/pandas/tests/io/parser/test_encoding.py @@ -130,8 +130,8 @@ def _encode_data_with_bom(_data): and data == "\n1" and kwargs.get("skip_blank_lines", True) ): - # Manually xfail, since we don't have mechanism to xfail specific version - request.applymarker(pytest.mark.xfail(reason="Pyarrow can't read blank lines")) + # CSV parse error: Empty CSV file or block: cannot infer number of columns + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") result = parser.read_csv(_encode_data_with_bom(data), encoding=utf8, **kwargs) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py index f55f8497f318c..86162bf90db8b 100644 --- a/pandas/tests/io/parser/test_header.py +++ b/pandas/tests/io/parser/test_header.py @@ -411,7 +411,7 @@ def test_header_names_backward_compat(all_parsers, data, header, request): parser = all_parsers if parser.engine == "pyarrow" and header is not None: - mark = pytest.mark.xfail(reason="mismatched index") + mark = pytest.mark.xfail(reason="DataFrame.columns are different") request.applymarker(mark) expected = parser.read_csv(StringIO("1,2,3\n4,5,6"), names=["a", "b", "c"]) @@ -635,7 +635,7 @@ def test_header_none_and_implicit_index(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # regex mismatch "CSV parse error: Expected 2 columns, got " +@skip_pyarrow # regex mismatch "CSV parse error: Expected 2 columns, got " def test_header_none_and_implicit_index_in_second_row(all_parsers): # GH#22144 parser = all_parsers diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 70d9171fa3c22..30580423a3099 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -1753,7 +1753,7 @@ def test_parse_timezone(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # pandas.errors.ParserError: CSV parse error +@skip_pyarrow # pandas.errors.ParserError: CSV parse error @pytest.mark.parametrize( "date_string", ["32/32/2019", "02/30/2019", "13/13/2019", "13/2019", "a3/11/2018", "10/11/2o17"], @@ -1787,8 +1787,8 @@ def test_parse_delimited_date_swap_no_warning( expected = DataFrame({0: [expected]}, dtype="datetime64[ns]") if parser.engine == "pyarrow": if not dayfirst: - mark = pytest.mark.xfail(reason="CSV parse error: Empty CSV file or block") - request.applymarker(mark) + # "CSV parse error: Empty CSV file or block" + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") msg = "The 'dayfirst' option is not supported with the 'pyarrow' engine" with pytest.raises(ValueError, match=msg): parser.read_csv( @@ -1802,7 +1802,8 @@ def test_parse_delimited_date_swap_no_warning( tm.assert_frame_equal(result, expected) -@xfail_pyarrow +# ArrowInvalid: CSV parse error: Empty CSV file or block: cannot infer number of columns +@skip_pyarrow @pytest.mark.parametrize( "date_string,dayfirst,expected", [ @@ -1887,7 +1888,8 @@ def test_hypothesis_delimited_date( assert result == expected -@xfail_pyarrow # KeyErrors +# ArrowKeyError: Column 'fdate1' in include_columns does not exist in CSV file +@skip_pyarrow @pytest.mark.parametrize( "names, usecols, parse_dates, missing_cols", [ diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py index 055be81d2996d..ded6b91a26eca 100644 --- a/pandas/tests/io/parser/usecols/test_usecols_basic.py +++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py @@ -95,10 +95,8 @@ def test_usecols_relative_to_names(all_parsers, names, usecols, request): 10,11,12""" parser = all_parsers if parser.engine == "pyarrow" and not isinstance(usecols[0], int): - mark = pytest.mark.xfail( - reason="ArrowKeyError: Column 'fb' in include_columns does not exist" - ) - request.applymarker(mark) + # ArrowKeyError: Column 'fb' in include_columns does not exist + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") result = parser.read_csv(StringIO(data), names=names, header=None, usecols=usecols) @@ -438,10 +436,8 @@ def test_raises_on_usecols_names_mismatch( usecols is not None and expected is not None ): # everything but the first case - mark = pytest.mark.xfail( - reason="e.g. Column 'f' in include_columns does not exist in CSV file" - ) - request.applymarker(mark) + # ArrowKeyError: Column 'f' in include_columns does not exist in CSV file + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") if expected is None: with pytest.raises(ValueError, match=msg):
Follow up to https://github.com/pandas-dev/pandas/pull/55943 Also reduces our CI timeout from 180 minutes to 90 since tests have been running a lot faster lately
https://api.github.com/repos/pandas-dev/pandas/pulls/56015
2023-11-17T03:07:01Z
2023-11-17T15:20:05Z
2023-11-17T15:20:05Z
2023-11-17T17:29:26Z
REF: use conditional-nogil in libgroupby
diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 6f9b33b042959..a73e37b9cfe1f 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -695,54 +695,37 @@ def group_sum( N, K = (<object>values).shape - if sum_t is object: - # NB: this does not use 'compensation' like the non-object track does. + with nogil(sum_t is not object): for i in range(N): lab = labels[i] if lab < 0: continue counts[lab] += 1 - for j in range(K): - val = values[i, j] - - # not nan - if not checknull(val): - nobs[lab, j] += 1 - - if nobs[lab, j] == 1: - # i.e. we haven't added anything yet; avoid TypeError - # if e.g. val is a str and sumx[lab, j] is 0 - t = val - else: - t = sumx[lab, j] + val - sumx[lab, j] = t - for i in range(ncounts): for j in range(K): - if nobs[i, j] < min_count: - out[i, j] = None + val = values[i, j] + if uses_mask: + isna_entry = mask[i, j] else: - out[i, j] = sumx[i, j] - else: - with nogil: - for i in range(N): - lab = labels[i] - if lab < 0: - continue + isna_entry = _treat_as_na(val, is_datetimelike) - counts[lab] += 1 - for j in range(K): - val = values[i, j] + if not isna_entry: + nobs[lab, j] += 1 - if uses_mask: - isna_entry = mask[i, j] - else: - isna_entry = _treat_as_na(val, is_datetimelike) + if sum_t is object: + # NB: this does not use 'compensation' like the non-object + # track does. + if nobs[lab, j] == 1: + # i.e. we haven't added anything yet; avoid TypeError + # if e.g. val is a str and sumx[lab, j] is 0 + t = val + else: + t = sumx[lab, j] + val + sumx[lab, j] = t - if not isna_entry: - nobs[lab, j] += 1 + else: y = val - compensation[lab, j] t = sumx[lab, j] + y compensation[lab, j] = t - sumx[lab, j] - y @@ -755,9 +738,9 @@ def group_sum( compensation[lab, j] = 0 sumx[lab, j] = t - _check_below_mincount( - out, uses_mask, result_mask, ncounts, K, nobs, min_count, sumx - ) + _check_below_mincount( + out, uses_mask, result_mask, ncounts, K, nobs, min_count, sumx + ) @cython.wraparound(False) @@ -809,9 +792,9 @@ def group_prod( nobs[lab, j] += 1 prodx[lab, j] *= val - _check_below_mincount( - out, uses_mask, result_mask, ncounts, K, nobs, min_count, prodx - ) + _check_below_mincount( + out, uses_mask, result_mask, ncounts, K, nobs, min_count, prodx + ) @cython.wraparound(False) @@ -1320,9 +1303,8 @@ ctypedef fused numeric_object_complex_t: cdef bint _treat_as_na(numeric_object_complex_t val, bint is_datetimelike) noexcept nogil: if numeric_object_complex_t is object: - # Should never be used, but we need to avoid the `val != val` below - # or else cython will raise about gil acquisition. - raise NotImplementedError + with gil: + return checknull(val) elif numeric_object_complex_t is int64_t: return is_datetimelike and val == NPY_NAT @@ -1369,7 +1351,7 @@ cdef numeric_t _get_na_val(numeric_t val, bint is_datetimelike): ctypedef fused mincount_t: - numeric_t + numeric_object_t complex64_t complex128_t @@ -1385,7 +1367,7 @@ cdef inline void _check_below_mincount( int64_t[:, ::1] nobs, int64_t min_count, mincount_t[:, ::1] resx, -) noexcept nogil: +) noexcept: """ Check if the number of observations for a group is below min_count, and if so set the result for that group to the appropriate NA-like value. @@ -1393,38 +1375,40 @@ cdef inline void _check_below_mincount( cdef: Py_ssize_t i, j - for i in range(ncounts): - for j in range(K): - - if nobs[i, j] < min_count: - # if we are integer dtype, not is_datetimelike, and - # not uses_mask, then getting here implies that - # counts[i] < min_count, which means we will - # be cast to float64 and masked at the end - # of WrappedCythonOp._call_cython_op. So we can safely - # set a placeholder value in out[i, j]. - if uses_mask: - result_mask[i, j] = True - # set out[i, j] to 0 to be deterministic, as - # it was initialized with np.empty. Also ensures - # we can downcast out if appropriate. - out[i, j] = 0 - elif ( - mincount_t is float32_t - or mincount_t is float64_t - or mincount_t is complex64_t - or mincount_t is complex128_t - ): - out[i, j] = NAN - elif mincount_t is int64_t: - # Per above, this is a placeholder in - # non-is_datetimelike cases. - out[i, j] = NPY_NAT + with nogil(mincount_t is not object): + for i in range(ncounts): + for j in range(K): + if nobs[i, j] >= min_count: + out[i, j] = resx[i, j] else: - # placeholder, see above - out[i, j] = 0 - else: - out[i, j] = resx[i, j] + # if we are integer dtype, not is_datetimelike, and + # not uses_mask, then getting here implies that + # counts[i] < min_count, which means we will + # be cast to float64 and masked at the end + # of WrappedCythonOp._call_cython_op. So we can safely + # set a placeholder value in out[i, j]. + if uses_mask: + result_mask[i, j] = True + # set out[i, j] to 0 to be deterministic, as + # it was initialized with np.empty. Also ensures + # we can downcast out if appropriate. + out[i, j] = 0 + elif ( + mincount_t is float32_t + or mincount_t is float64_t + or mincount_t is complex64_t + or mincount_t is complex128_t + ): + out[i, j] = NAN + elif mincount_t is int64_t: + # Per above, this is a placeholder in + # non-is_datetimelike cases. + out[i, j] = NPY_NAT + elif mincount_t is object: + out[i, j] = None + else: + # placeholder, see above + out[i, j] = 0 # TODO(cython3): GH#31710 use memorviews once cython 0.30 is released so we can @@ -1466,8 +1450,7 @@ def group_last( N, K = (<object>values).shape - if numeric_object_t is object: - # TODO(cython3): De-duplicate once conditional-nogil is available + with nogil(numeric_object_t is not object): for i in range(N): lab = labels[i] if lab < 0: @@ -1480,43 +1463,15 @@ def group_last( if uses_mask: isna_entry = mask[i, j] else: - isna_entry = checknull(val) + isna_entry = _treat_as_na(val, is_datetimelike) if not isna_entry: - # TODO(cython3): use _treat_as_na here once - # conditional-nogil is available. nobs[lab, j] += 1 resx[lab, j] = val - for i in range(ncounts): - for j in range(K): - if nobs[i, j] < min_count: - out[i, j] = None - else: - out[i, j] = resx[i, j] - else: - with nogil: - for i in range(N): - lab = labels[i] - if lab < 0: - continue - - counts[lab] += 1 - for j in range(K): - val = values[i, j] - - if uses_mask: - isna_entry = mask[i, j] - else: - isna_entry = _treat_as_na(val, is_datetimelike) - - if not isna_entry: - nobs[lab, j] += 1 - resx[lab, j] = val - - _check_below_mincount( - out, uses_mask, result_mask, ncounts, K, nobs, min_count, resx - ) + _check_below_mincount( + out, uses_mask, result_mask, ncounts, K, nobs, min_count, resx + ) # TODO(cython3): GH#31710 use memorviews once cython 0.30 is released so we can @@ -1559,8 +1514,7 @@ def group_nth( N, K = (<object>values).shape - if numeric_object_t is object: - # TODO(cython3): De-duplicate once conditional-nogil is available + with nogil(numeric_object_t is not object): for i in range(N): lab = labels[i] if lab < 0: @@ -1573,46 +1527,16 @@ def group_nth( if uses_mask: isna_entry = mask[i, j] else: - isna_entry = checknull(val) + isna_entry = _treat_as_na(val, is_datetimelike) if not isna_entry: - # TODO(cython3): use _treat_as_na here once - # conditional-nogil is available. nobs[lab, j] += 1 if nobs[lab, j] == rank: resx[lab, j] = val - for i in range(ncounts): - for j in range(K): - if nobs[i, j] < min_count: - out[i, j] = None - else: - out[i, j] = resx[i, j] - - else: - with nogil: - for i in range(N): - lab = labels[i] - if lab < 0: - continue - - counts[lab] += 1 - for j in range(K): - val = values[i, j] - - if uses_mask: - isna_entry = mask[i, j] - else: - isna_entry = _treat_as_na(val, is_datetimelike) - - if not isna_entry: - nobs[lab, j] += 1 - if nobs[lab, j] == rank: - resx[lab, j] = val - - _check_below_mincount( - out, uses_mask, result_mask, ncounts, K, nobs, min_count, resx - ) + _check_below_mincount( + out, uses_mask, result_mask, ncounts, K, nobs, min_count, resx + ) @cython.boundscheck(False) @@ -1789,9 +1713,9 @@ cdef group_min_max( if val < group_min_or_max[lab, j]: group_min_or_max[lab, j] = val - _check_below_mincount( - out, uses_mask, result_mask, ngroups, K, nobs, min_count, group_min_or_max - ) + _check_below_mincount( + out, uses_mask, result_mask, ngroups, K, nobs, min_count, group_min_or_max + ) @cython.wraparound(False) @@ -1876,8 +1800,7 @@ def group_idxmin_idxmax( # a category is not observed; these values will be dropped out[:] = 0 - # TODO(cython3): De-duplicate once conditional-nogil is available - if numeric_object_t is object: + with nogil(numeric_object_t is not object): for i in range(N): lab = labels[i] if lab < 0: @@ -1892,8 +1815,7 @@ def group_idxmin_idxmax( if uses_mask: isna_entry = mask[i, j] else: - # TODO(cython3): use _treat_as_na here - isna_entry = checknull(val) + isna_entry = _treat_as_na(val, is_datetimelike) if isna_entry: if not skipna: @@ -1907,36 +1829,6 @@ def group_idxmin_idxmax( if val < group_min_or_max[lab, j]: group_min_or_max[lab, j] = val out[lab, j] = i - else: - with nogil: - for i in range(N): - lab = labels[i] - if lab < 0: - continue - - for j in range(K): - if not skipna and out[lab, j] == -1: - # Once we've hit NA there is no going back - continue - val = values[i, j] - - if uses_mask: - isna_entry = mask[i, j] - else: - isna_entry = _treat_as_na(val, is_datetimelike) - - if isna_entry: - if not skipna: - out[lab, j] = -1 - else: - if compute_max: - if val > group_min_or_max[lab, j]: - group_min_or_max[lab, j] = val - out[lab, j] = i - else: - if val < group_min_or_max[lab, j]: - group_min_or_max[lab, j] = val - out[lab, j] = i @cython.wraparound(False)
There is a perf/verbosity tradeoff here that this PR chooses to leave some perf on the table, primarily in object dtype cases. Namely makes object dtype cases go through _treat_as_na with a `with gil:` context rather than keep duplicated ``` if numeric_object_t is object: # TODO(cython3): use _treat_as_na here once # conditional-nogil is available. isna_entry = checknull(val) else: isna_entry = _treat_as_na(val, is_datetimelike) ``` Similarly this removes the nogil from `_check_below_mincount` and re-releases the gil inside the function. bc _check_below_mincount is only called once at the end of each function and not inside the loop, i think this is benign. Opened https://github.com/cython/cython/issues/5831 to get back the sliver of perf this leaves on the table.
https://api.github.com/repos/pandas-dev/pandas/pulls/56011
2023-11-16T23:07:14Z
2023-11-17T02:03:13Z
2023-11-17T02:03:13Z
2023-11-17T02:04:45Z
PERF: assert_produces_warning
diff --git a/pandas/_testing/_warnings.py b/pandas/_testing/_warnings.py index 11cf60ef36a9c..4b087c75f5d74 100644 --- a/pandas/_testing/_warnings.py +++ b/pandas/_testing/_warnings.py @@ -4,6 +4,7 @@ contextmanager, nullcontext, ) +import inspect import re import sys from typing import ( @@ -206,15 +207,14 @@ def _is_unexpected_warning( def _assert_raised_with_correct_stacklevel( actual_warning: warnings.WarningMessage, ) -> None: - from inspect import ( - getframeinfo, - stack, - ) - - caller = getframeinfo(stack()[4][0]) + # https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow + frame = inspect.currentframe() + for _ in range(4): + frame = frame.f_back # type: ignore[union-attr] + caller_filename = inspect.getfile(frame) # type: ignore[arg-type] msg = ( "Warning not set with correct stacklevel. " f"File where warning is raised: {actual_warning.filename} != " - f"{caller.filename}. Warning message: {actual_warning.message}" + f"{caller_filename}. Warning message: {actual_warning.message}" ) - assert actual_warning.filename == caller.filename, msg + assert actual_warning.filename == caller_filename, msg
Similar to the implementation in `pandas.util._exceptions.find_stack_level`. Seems like it may save a little testing time: ``` > pytest pandas/tests/series/ 160.85s <- main 135.46s <- PR ``` ``` > pytest pandas/tests/arithmetic/ 309.48s <- main 276.90s <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/56009
2023-11-16T23:02:07Z
2023-11-17T02:04:56Z
2023-11-17T02:04:56Z
2023-11-22T01:59:56Z
CLN: remove cython<3 reversed-op pattern
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 691fd05fe5ded..a37ab45dd57ed 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -495,17 +495,6 @@ cdef class Interval(IntervalMixin): or cnp.is_timedelta64_object(y) ): return Interval(self.left + y, self.right + y, closed=self.closed) - elif ( - # __radd__ pattern - # TODO(cython3): remove this - isinstance(y, Interval) - and ( - isinstance(self, numbers.Number) - or PyDelta_Check(self) - or cnp.is_timedelta64_object(self) - ) - ): - return Interval(y.left + self, y.right + self, closed=y.closed) return NotImplemented def __radd__(self, other): @@ -529,10 +518,6 @@ cdef class Interval(IntervalMixin): def __mul__(self, y): if isinstance(y, numbers.Number): return Interval(self.left * y, self.right * y, closed=self.closed) - elif isinstance(y, Interval) and isinstance(self, numbers.Number): - # __radd__ semantics - # TODO(cython3): remove this - return Interval(y.left * self, y.right * self, closed=y.closed) return NotImplemented def __rmul__(self, other): diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 3416c68a23f63..65db0e05f859c 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -124,11 +124,6 @@ cdef class _NaT(datetime): return NotImplemented def __add__(self, other): - if self is not c_NaT: - # TODO(cython3): remove this it moved to __radd__ - # cython __radd__ semantics - self, other = other, self - if PyDateTime_Check(other): return c_NaT elif PyDelta_Check(other): @@ -158,14 +153,6 @@ cdef class _NaT(datetime): def __sub__(self, other): # Duplicate some logic from _Timestamp.__sub__ to avoid needing # to subclass; allows us to @final(_Timestamp.__sub__) - cdef: - bint is_rsub = False - - if self is not c_NaT: - # cython __rsub__ semantics - # TODO(cython3): remove __rsub__ logic from here - self, other = other, self - is_rsub = True if PyDateTime_Check(other): return c_NaT @@ -180,19 +167,9 @@ cdef class _NaT(datetime): elif util.is_array(other): if other.dtype.kind == "m": - if not is_rsub: - # NaT - timedelta64 we treat NaT as datetime64, so result - # is datetime64 - result = np.empty(other.shape, dtype="datetime64[ns]") - result.fill("NaT") - return result - - # __rsub__ logic here - # TODO(cython3): remove this, move above code out of - # ``if not is_rsub`` block - # timedelta64 - NaT we have to treat NaT as timedelta64 - # for this to be meaningful, and the result is timedelta64 - result = np.empty(other.shape, dtype="timedelta64[ns]") + # NaT - timedelta64 we treat NaT as datetime64, so result + # is datetime64 + result = np.empty(other.shape, dtype="datetime64[ns]") result.fill("NaT") return result diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 9b93fde1f4f8d..1fb8936336a18 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -489,12 +489,7 @@ cdef class BaseOffset: return type(self)(n=1, normalize=self.normalize, **self.kwds) def __add__(self, other): - if not isinstance(self, BaseOffset): - # cython semantics; this is __radd__ - # TODO(cython3): remove this, this moved to __radd__ - return other.__add__(self) - - elif util.is_array(other) and other.dtype == object: + if util.is_array(other) and other.dtype == object: return np.array([self + x for x in other]) try: @@ -511,10 +506,6 @@ cdef class BaseOffset: elif type(other) is type(self): return type(self)(self.n - other.n, normalize=self.normalize, **self.kwds) - elif not isinstance(self, BaseOffset): - # TODO(cython3): remove, this moved to __rsub__ - # cython semantics, this is __rsub__ - return (-other).__add__(self) else: # e.g. PeriodIndex return NotImplemented @@ -528,10 +519,6 @@ cdef class BaseOffset: elif is_integer_object(other): return type(self)(n=other * self.n, normalize=self.normalize, **self.kwds) - elif not isinstance(self, BaseOffset): - # TODO(cython3): remove this, this moved to __rmul__ - # cython semantics, this is __rmul__ - return other.__mul__(self) return NotImplemented def __rmul__(self, other): @@ -1025,10 +1012,6 @@ cdef class Tick(SingleConstructorOffset): return self.delta.__gt__(other) def __mul__(self, other): - if not isinstance(self, Tick): - # TODO(cython3), remove this, this moved to __rmul__ - # cython semantics, this is __rmul__ - return other.__mul__(self) if is_float_object(other): n = other * self.n # If the new `n` is an integer, we can represent it using the @@ -1056,11 +1039,6 @@ cdef class Tick(SingleConstructorOffset): return _wrap_timedelta_result(result) def __add__(self, other): - if not isinstance(self, Tick): - # cython semantics; this is __radd__ - # TODO(cython3): remove this, this moved to __radd__ - return other.__add__(self) - if isinstance(other, Tick): if type(self) is type(other): return type(self)(self.n + other.n) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 318e018689a78..22f96f8f6c3fa 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1855,13 +1855,6 @@ cdef class _Period(PeriodMixin): @cython.overflowcheck(True) def __add__(self, other): - if not is_period_object(self): - # cython semantics; this is analogous to a call to __radd__ - # TODO(cython3): remove this - if self is NaT: - return NaT - return other.__add__(self) - if is_any_td_scalar(other): return self._add_timedeltalike_scalar(other) elif is_offset_object(other): @@ -1893,14 +1886,7 @@ cdef class _Period(PeriodMixin): return self.__add__(other) def __sub__(self, other): - if not is_period_object(self): - # cython semantics; this is like a call to __rsub__ - # TODO(cython3): remove this - if self is NaT: - return NaT - return NotImplemented - - elif ( + if ( is_any_td_scalar(other) or is_offset_object(other) or util.is_integer_object(other) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 491e6662e319c..c4693be8c11c6 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -475,11 +475,6 @@ cdef class _Timestamp(ABCTimestamp): dtype=object, ) - elif not isinstance(self, _Timestamp): - # cython semantics, args have been switched and this is __radd__ - # TODO(cython3): remove this it moved to __radd__ - return other.__add__(self) - return NotImplemented def __radd__(self, other):
- [ ] 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/56006
2023-11-16T22:18:10Z
2023-11-17T02:06:01Z
2023-11-17T02:06:01Z
2023-11-17T02:07:56Z
CI: Debug timeout
diff --git a/ci/run_tests.sh b/ci/run_tests.sh index 6a70ea1df3e71..39c885afbe1ef 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -11,7 +11,7 @@ echo PYTHONHASHSEED=$PYTHONHASHSEED COVERAGE="-s --cov=pandas --cov-report=xml --cov-append --cov-config=pyproject.toml" # TODO: Support NEP 50 and remove NPY_PROMOTION_STATE -PYTEST_CMD="NPY_PROMOTION_STATE=legacy MESONPY_EDITABLE_VERBOSE=1 PYTHONDEVMODE=1 PYTHONWARNDEFAULTENCODING=1 pytest -r fEs -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" +PYTEST_CMD="NPY_PROMOTION_STATE=legacy MESONPY_EDITABLE_VERBOSE=1 PYTHONDEVMODE=1 PYTHONWARNDEFAULTENCODING=1 pytest -v -r fEs -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" if [[ "$PATTERN" ]]; then PYTEST_CMD="$PYTEST_CMD -m \"$PATTERN\""
Looks like a test(s) are still timing out the Ubuntu single cpu jobs
https://api.github.com/repos/pandas-dev/pandas/pulls/56005
2023-11-16T21:58:22Z
2023-11-17T18:58:56Z
null
2023-11-17T18:58:58Z
BUG: DatetimeIndex with non-nano dtype and mixed numeric inputs
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 93b0ccad9f2aa..8529ff885690a 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -355,6 +355,7 @@ Datetimelike - Bug in addition or subtraction of very large :class:`Tick` objects with :class:`Timestamp` or :class:`Timedelta` objects raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`) - Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond :class:`DatetimeTZDtype` and inputs that would be out of bounds with nanosecond resolution incorrectly raising ``OutOfBoundsDatetime`` (:issue:`54620`) - Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` dtype and inputs that would be out of bounds for a ``datetime64[ns]`` incorrectly raising ``OutOfBoundsDatetime`` (:issue:`55756`) +- Bug in creating a :class:`Index`, :class:`Series`, or :class:`DataFrame` with a non-nanosecond ``datetime64`` (or :class:`DatetimeTZDtype`) from mixed-numeric inputs treating those as nanoseconds instead of as multiples of the dtype's unit (which would happen with non-mixed numeric inputs) (:issue:`56004`) - Timedelta diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index b5f448aa32fad..8736b9d5ec8d6 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -530,7 +530,9 @@ cpdef array_to_datetime( state.update_creso(item_reso) if infer_reso: creso = state.creso - iresult[i] = cast_from_unit(val, "ns", out_reso=creso) + + # we now need to parse this as if unit=abbrev + iresult[i] = cast_from_unit(val, abbrev, out_reso=creso) state.found_other = True elif isinstance(val, str): @@ -779,6 +781,13 @@ def array_to_datetime_with_tz( _TSObject tsobj bint infer_reso = creso == NPY_DATETIMEUNIT.NPY_FR_GENERIC DatetimeParseState state = DatetimeParseState(creso) + str abbrev + + if infer_reso: + # We treat ints/floats as nanoseconds + abbrev = "ns" + else: + abbrev = npy_unit_to_abbrev(creso) for i in range(n): # Analogous to `item = values[i]` @@ -790,7 +799,12 @@ def array_to_datetime_with_tz( else: tsobj = convert_to_tsobject( - item, tz=tz, unit="ns", dayfirst=dayfirst, yearfirst=yearfirst, nanos=0 + item, + tz=tz, + unit=abbrev, + dayfirst=dayfirst, + yearfirst=yearfirst, + nanos=0, ) if tsobj.value != NPY_NAT: state.update_creso(tsobj.creso) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index b100a6a80f8ed..9079e33e08dc7 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2220,6 +2220,7 @@ def _sequence_to_dt64( data = cast(np.ndarray, data) copy = False if lib.infer_dtype(data, skipna=False) == "integer": + # Much more performant than going through array_to_datetime data = data.astype(np.int64) elif tz is not None and ambiguous == "raise": obj_data = np.asarray(data, dtype=object) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 7110a428544d5..35c3604de3d63 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -1012,11 +1012,17 @@ def test_dti_constructor_with_non_nano_dtype(self, tz): dtype = "M8[us]" if tz is not None: dtype = f"M8[us, {tz}]" - # NB: the 2500 is interpreted as nanoseconds and rounded *down* - # to 2 microseconds vals = [ts, "2999-01-02 03:04:05.678910", 2500] result = DatetimeIndex(vals, dtype=dtype) - exp_vals = [Timestamp(x, tz=tz).as_unit("us").asm8 for x in vals] + # The 2500 is interpreted as microseconds, consistent with what + # we would get if we created DatetimeIndexes from vals[:2] and vals[2:] + # and concated the results. + pointwise = [ + vals[0].tz_localize(tz), + Timestamp(vals[1], tz=tz), + to_datetime(vals[2], unit="us", utc=True).tz_convert(tz), + ] + exp_vals = [x.as_unit("us").asm8 for x in pointwise] exp_arr = np.array(exp_vals, dtype="M8[us]") expected = DatetimeIndex(exp_arr, dtype="M8[us]") if tz is not None: @@ -1054,6 +1060,36 @@ def test_dti_constructor_object_float_matches_float_dtype(self): dti2 = DatetimeIndex(arr2, tz="CET") tm.assert_index_equal(dti1, dti2) + @pytest.mark.parametrize("dtype", ["M8[us]", "M8[us, US/Pacific]"]) + def test_dti_constructor_with_dtype_object_int_matches_int_dtype(self, dtype): + # Going through the object path should match the non-object path + + vals1 = np.arange(5, dtype="i8") * 1000 + vals1[0] = pd.NaT.value + + vals2 = vals1.astype(np.float64) + vals2[0] = np.nan + + vals3 = vals1.astype(object) + # change lib.infer_dtype(vals3) from "integer" so we go through + # array_to_datetime in _sequence_to_dt64 + vals3[0] = pd.NaT + + vals4 = vals2.astype(object) + + res1 = DatetimeIndex(vals1, dtype=dtype) + res2 = DatetimeIndex(vals2, dtype=dtype) + res3 = DatetimeIndex(vals3, dtype=dtype) + res4 = DatetimeIndex(vals4, dtype=dtype) + + expected = DatetimeIndex(vals1.view("M8[us]")) + if res1.tz is not None: + expected = expected.tz_localize("UTC").tz_convert(res1.tz) + tm.assert_index_equal(res1, expected) + tm.assert_index_equal(res2, expected) + tm.assert_index_equal(res3, expected) + tm.assert_index_equal(res4, expected) + class TestTimeSeries: def test_dti_constructor_preserve_dti_freq(self): diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index 7d4ad99deab38..aca06a2f91c32 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -25,6 +25,7 @@ Timestamp, cut, date_range, + to_datetime, ) import pandas._testing as tm @@ -114,13 +115,19 @@ def test_astype_object_to_dt64_non_nano(self, tz): dtype = "M8[us]" if tz is not None: dtype = f"M8[us, {tz}]" - # NB: the 2500 is interpreted as nanoseconds and rounded *down* - # to 2 microseconds vals = [ts, "2999-01-02 03:04:05.678910", 2500] ser = Series(vals, dtype=object) result = ser.astype(dtype) - exp_vals = [Timestamp(x, tz=tz).as_unit("us").asm8 for x in vals] + # The 2500 is interpreted as microseconds, consistent with what + # we would get if we created DatetimeIndexes from vals[:2] and vals[2:] + # and concated the results. + pointwise = [ + vals[0].tz_localize(tz), + Timestamp(vals[1], tz=tz), + to_datetime(vals[2], unit="us", utc=True).tz_convert(tz), + ] + exp_vals = [x.as_unit("us").asm8 for x in pointwise] exp_arr = np.array(exp_vals, dtype="M8[us]") expected = Series(exp_arr, dtype="M8[us]") if tz is not 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/56004
2023-11-16T19:13:31Z
2023-11-17T18:34:37Z
2023-11-17T18:34:37Z
2023-11-17T20:00:39Z
BUG: Return numpy types from ArrowExtensionArray.to_numpy for temporal types when possible
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index acec8379ee5b3..c2aa46208cb7d 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -107,11 +107,11 @@ documentation. .. _whatsnew_220.enhancements.to_numpy_ea: -ExtensionArray.to_numpy converts to suitable NumPy dtype -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +``to_numpy`` for NumPy nullable and Arrow types converts to suitable NumPy dtype +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -:meth:`ExtensionArray.to_numpy` will now convert to a suitable NumPy dtype instead -of ``object`` dtype for nullable extension dtypes. +``to_numpy`` for NumPy nullable and Arrow types will now convert to a +suitable NumPy dtype instead of ``object`` dtype for nullable extension dtypes. *Old behavior:* @@ -128,6 +128,9 @@ of ``object`` dtype for nullable extension dtypes. ser = pd.Series([1, 2, 3], dtype="Int64") ser.to_numpy() + ser = pd.Series([1, 2, 3], dtype="timestamp[ns][pyarrow]") + ser.to_numpy() + The default NumPy dtype (without any arguments) is determined as follows: - float dtypes are cast to NumPy floats @@ -135,6 +138,7 @@ The default NumPy dtype (without any arguments) is determined as follows: - integer dtypes with missing values are cast to NumPy float dtypes and ``NaN`` is used as missing value indicator - boolean dtypes without missing values are cast to NumPy bool dtype - boolean dtypes with missing values keep object dtype +- datetime and timedelta types are cast to Numpy datetime64 and timedelta64 types respectively and ``NaT`` is used as missing value indicator .. _whatsnew_220.enhancements.struct_accessor: diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index d8b074fe61322..5e4d2901454b0 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -47,6 +47,7 @@ from pandas.core import ( algorithms as algos, missing, + ops, roperator, ) from pandas.core.arraylike import OpsMixin @@ -655,7 +656,11 @@ def _cmp_method(self, other, op): mask = isna(self) | isna(other) valid = ~mask result = np.zeros(len(self), dtype="bool") - result[valid] = op(np.array(self)[valid], other) + np_array = np.array(self) + try: + result[valid] = op(np_array[valid], other) + except TypeError: + result = ops.invalid_comparison(np_array, other, op) result = pa.array(result, type=pa.bool_()) result = pc.if_else(valid, result, None) else: @@ -1130,7 +1135,16 @@ def searchsorted( if isinstance(value, ExtensionArray): value = value.astype(object) # Base class searchsorted would cast to object, which is *much* slower. - return self.to_numpy().searchsorted(value, side=side, sorter=sorter) + dtype = None + if isinstance(self.dtype, ArrowDtype): + pa_dtype = self.dtype.pyarrow_dtype + if ( + pa.types.is_timestamp(pa_dtype) or pa.types.is_duration(pa_dtype) + ) and pa_dtype.unit == "ns": + # np.array[datetime/timedelta].searchsorted(datetime/timedelta) + # erroneously fails when numpy type resolution is nanoseconds + dtype = object + return self.to_numpy(dtype=dtype).searchsorted(value, side=side, sorter=sorter) def take( self, @@ -1281,10 +1295,15 @@ def to_numpy( if pa.types.is_timestamp(pa_type) or pa.types.is_duration(pa_type): result = data._maybe_convert_datelike_array() - if dtype is None or dtype.kind == "O": - result = result.to_numpy(dtype=object, na_value=na_value) + if (pa.types.is_timestamp(pa_type) and pa_type.tz is not None) or ( + dtype is not None and dtype.kind == "O" + ): + dtype = object else: - result = result.to_numpy(dtype=dtype) + # GH 55997 + dtype = None + na_value = pa_type.to_pandas_dtype().type("nat", pa_type.unit) + result = result.to_numpy(dtype=dtype, na_value=na_value) elif pa.types.is_time(pa_type) or pa.types.is_date(pa_type): # convert to list of python datetime.time objects before # wrapping in ndarray diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index ecb09aa6cacf1..cc83e51fb2bd6 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -61,7 +61,6 @@ ) from pandas.core.arrays import ( - BaseMaskedArray, Categorical, DatetimeArray, ExtensionArray, @@ -1528,10 +1527,8 @@ def _format_strings(self) -> list[str]: if isinstance(values, Categorical): # Categorical is special for now, so that we can preserve tzinfo array = values._internal_get_values() - elif isinstance(values, BaseMaskedArray): - array = values.to_numpy(dtype=object) else: - array = np.asarray(values) + array = np.asarray(values, dtype=object) fmt_values = format_array( array, diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index d015e899c4231..3f30559918ee5 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -263,7 +263,7 @@ def test_comparison_methods_scalar_not_string(comparison_op, dtype): other = 42 if op_name not in ["__eq__", "__ne__"]: - with pytest.raises(TypeError, match="not supported between"): + with pytest.raises(TypeError, match="Invalid comparison|not supported between"): getattr(a, op_name)(other) return diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index 75e5fb00586e6..5104e5449ca69 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -41,6 +41,7 @@ pa_version_under13p0, pa_version_under14p0, ) +import pandas.util._test_decorators as td from pandas.core.dtypes.dtypes import ( ArrowDtype, @@ -266,6 +267,19 @@ def data_for_twos(data): class TestArrowArray(base.ExtensionTests): + def test_compare_scalar(self, data, comparison_op): + ser = pd.Series(data) + self._compare_other(ser, data, comparison_op, data[0]) + + @pytest.mark.parametrize("na_action", [None, "ignore"]) + def test_map(self, data_missing, na_action): + if data_missing.dtype.kind in "mM": + result = data_missing.map(lambda x: x, na_action=na_action) + expected = data_missing.to_numpy(dtype=object) + tm.assert_numpy_array_equal(result, expected) + else: + super().test_map(data_missing, na_action) + def test_astype_str(self, data, request): pa_dtype = data.dtype.pyarrow_dtype if pa.types.is_binary(pa_dtype): @@ -274,8 +288,35 @@ def test_astype_str(self, data, request): reason=f"For {pa_dtype} .astype(str) decodes.", ) ) + elif ( + pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None + ) or pa.types.is_duration(pa_dtype): + request.applymarker( + pytest.mark.xfail( + reason="pd.Timestamp/pd.Timedelta repr different from numpy repr", + ) + ) super().test_astype_str(data) + @pytest.mark.parametrize( + "nullable_string_dtype", + [ + "string[python]", + pytest.param("string[pyarrow]", marks=td.skip_if_no("pyarrow")), + ], + ) + def test_astype_string(self, data, nullable_string_dtype, request): + pa_dtype = data.dtype.pyarrow_dtype + if ( + pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None + ) or pa.types.is_duration(pa_dtype): + request.applymarker( + pytest.mark.xfail( + reason="pd.Timestamp/pd.Timedelta repr different from numpy repr", + ) + ) + super().test_astype_string(data, nullable_string_dtype) + def test_from_dtype(self, data, request): pa_dtype = data.dtype.pyarrow_dtype if pa.types.is_string(pa_dtype) or pa.types.is_decimal(pa_dtype): @@ -1511,11 +1552,9 @@ def test_to_numpy_with_defaults(data): result = data.to_numpy() pa_type = data._pa_array.type - if ( - pa.types.is_duration(pa_type) - or pa.types.is_timestamp(pa_type) - or pa.types.is_date(pa_type) - ): + if pa.types.is_duration(pa_type) or pa.types.is_timestamp(pa_type): + pytest.skip("Tested in test_to_numpy_temporal") + elif pa.types.is_date(pa_type): expected = np.array(list(data)) else: expected = np.array(data._pa_array) @@ -2937,26 +2976,28 @@ def test_groupby_series_size_returns_pa_int(data): @pytest.mark.parametrize( - "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES + "pa_type", tm.DATETIME_PYARROW_DTYPES + tm.TIMEDELTA_PYARROW_DTYPES, ids=repr ) -def test_to_numpy_temporal(pa_type): +@pytest.mark.parametrize("dtype", [None, object]) +def test_to_numpy_temporal(pa_type, dtype): # GH 53326 + # GH 55997: Return datetime64/timedelta64 types with NaT if possible arr = ArrowExtensionArray(pa.array([1, None], type=pa_type)) - result = arr.to_numpy() + result = arr.to_numpy(dtype=dtype) if pa.types.is_duration(pa_type): - expected = [ - pd.Timedelta(1, unit=pa_type.unit).as_unit(pa_type.unit), - pd.NA, - ] - assert isinstance(result[0], pd.Timedelta) + value = pd.Timedelta(1, unit=pa_type.unit).as_unit(pa_type.unit) else: - expected = [ - pd.Timestamp(1, unit=pa_type.unit, tz=pa_type.tz).as_unit(pa_type.unit), - pd.NA, - ] - assert isinstance(result[0], pd.Timestamp) - expected = np.array(expected, dtype=object) - assert result[0].unit == expected[0].unit + value = pd.Timestamp(1, unit=pa_type.unit, tz=pa_type.tz).as_unit(pa_type.unit) + + if dtype == object or (pa.types.is_timestamp(pa_type) and pa_type.tz is not None): + na = pd.NA + expected = np.array([value, na], dtype=object) + assert result[0].unit == value.unit + else: + na = pa_type.to_pandas_dtype().type("nat", pa_type.unit) + value = value.to_numpy() + expected = np.array([value, na]) + assert np.datetime_data(result[0])[0] == pa_type.unit tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index f5738b83a8e64..4748a2a4aa00e 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1921,7 +1921,7 @@ def dtype(self): series = Series(ExtTypeStub(), copy=False) res = repr(series) # This line crashed before #33770 was fixed. expected = "\n".join( - ["0 [False True]", "1 [ True False]", "dtype: DtypeStub"] + ["0 [False True]", "1 [True False]", "dtype: DtypeStub"] ) assert res == expected
- [x] closes #55997 (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). - [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/56003
2023-11-16T19:12:32Z
2023-12-11T18:43:02Z
null
2023-12-11T18:43:05Z
CLN: use cimports for type checks
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 67e0224b64d7f..5b705e80f97f5 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -25,7 +25,6 @@ from cpython.object cimport ( Py_EQ, PyObject, PyObject_RichCompareBool, - PyTypeObject, ) from cpython.ref cimport Py_INCREF from cpython.sequence cimport PySequence_Check @@ -67,10 +66,6 @@ from numpy cimport ( cnp.import_array() -cdef extern from "Python.h": - # Note: importing extern-style allows us to declare these as nogil - # functions, whereas `from cpython cimport` does not. - bint PyObject_TypeCheck(object obj, PyTypeObject* type) nogil cdef extern from "numpy/arrayobject.h": # cython's numpy.dtype specification is incorrect, which leads to @@ -89,9 +84,6 @@ cdef extern from "numpy/arrayobject.h": object fields tuple names - PyTypeObject PySignedIntegerArrType_Type - PyTypeObject PyUnsignedIntegerArrType_Type - cdef extern from "pandas/parser/pd_parser.h": int floatify(object, float64_t *result, int *maybe_int) except -1 void PandasParser_IMPORT() @@ -1437,14 +1429,12 @@ cdef class Seen: self.sint_ = ( self.sint_ or (oINT64_MIN <= val < 0) - # Cython equivalent of `isinstance(val, np.signedinteger)` - or PyObject_TypeCheck(val, &PySignedIntegerArrType_Type) + or isinstance(val, cnp.signedinteger) ) self.uint_ = ( self.uint_ or (oINT64_MAX < val <= oUINT64_MAX) - # Cython equivalent of `isinstance(val, np.unsignedinteger)` - or PyObject_TypeCheck(val, &PyUnsignedIntegerArrType_Type) + or isinstance(val, cnp.unsignedinteger) ) @property diff --git a/pandas/_libs/tslibs/util.pxd b/pandas/_libs/tslibs/util.pxd index 44ff322060dcb..2c39a2b4699b2 100644 --- a/pandas/_libs/tslibs/util.pxd +++ b/pandas/_libs/tslibs/util.pxd @@ -22,6 +22,7 @@ cdef extern from "Python.h": object PyUnicode_DecodeLocale(const char *str, const char *errors) nogil +cimport numpy as cnp from numpy cimport ( PyArray_Check, float64_t, @@ -54,7 +55,7 @@ cdef inline bint is_integer_object(object obj) noexcept: """ Cython equivalent of - `isinstance(val, (int, long, np.integer)) and not isinstance(val, bool)` + `isinstance(val, (int, np.integer)) and not isinstance(val, (bool, np.timedelta64))` Parameters ---------- @@ -68,13 +69,13 @@ cdef inline bint is_integer_object(object obj) noexcept: ----- This counts np.timedelta64 objects as integers. """ - return (not PyBool_Check(obj) and PyArray_IsIntegerScalar(obj) + return (not PyBool_Check(obj) and isinstance(obj, (int, cnp.integer)) and not is_timedelta64_object(obj)) cdef inline bint is_float_object(object obj) noexcept nogil: """ - Cython equivalent of `isinstance(val, (float, np.float64))` + Cython equivalent of `isinstance(val, (float, np.floating))` Parameters ---------- @@ -90,7 +91,7 @@ cdef inline bint is_float_object(object obj) noexcept nogil: cdef inline bint is_complex_object(object obj) noexcept nogil: """ - Cython equivalent of `isinstance(val, (complex, np.complex128))` + Cython equivalent of `isinstance(val, (complex, np.complexfloating))` Parameters ----------
The generated C corresponding to the cnp.integer check in is_integer_object is `__Pyx_TypeCheck(__pyx_v_obj, __pyx_ptype_5numpy_integer)` which looks to me like it goes through python-space paths, can you comment @WillAyd ? Despite that, perf seems neutral-to-improved: ``` import numpy as np from pandas._libs.lib import is_integer item1 = 2 item2 = np.int64(1) item3 = "foo" %timeit is_integer(item1) 63.6 ns ± 1.17 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # <- main 62.9 ns ± 0.992 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # <- PR %timeit is_integer(item2) 70.5 ns ± 2.78 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # <- main 68.9 ns ± 1.37 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # <- PR %timeit is_integer(item3) 64.7 ns ± 2.95 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # <- main 61.6 ns ± 0.469 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each) # <- PR ``` Also for @WillAyd: we could make similar simplifications in util.is_float_object and util.is_complex_object but that would require removing their `nogil`ness. IIRC that was something you thought we should do regardless?
https://api.github.com/repos/pandas-dev/pandas/pulls/56002
2023-11-16T18:46:56Z
2023-11-17T18:38:36Z
2023-11-17T18:38:36Z
2023-11-17T19:59:52Z
Fix apply na overflow
diff --git a/pandas/core/methods/selectn.py b/pandas/core/methods/selectn.py index 894791cb46371..843c54de25bc9 100644 --- a/pandas/core/methods/selectn.py +++ b/pandas/core/methods/selectn.py @@ -139,7 +139,8 @@ def compute(self, method: str) -> Series: # arr passed into kth_smallest must be contiguous. We copy # here because kth_smallest will modify its input - kth_val = libalgos.kth_smallest(arr.copy(order="C"), n - 1) + # avoid OOB access with kth_smallest_c when n <= 0 + kth_val = libalgos.kth_smallest(arr.copy(order="C"), max(n - 1, 0)) (ns,) = np.nonzero(arr <= kth_val) inds = ns[arr[ns].argsort(kind="mergesort")]
Another thing flagged by ASAN. I am not very familiar with this algorithm so there may be a better way of doing this, but when `n=0` the cython code ends up reading memory one byte to the left of the array
https://api.github.com/repos/pandas-dev/pandas/pulls/56000
2023-11-16T18:08:22Z
2023-11-17T20:08:57Z
2023-11-17T20:08:57Z
2023-11-17T20:09:05Z
Refactored pandas_timedelta_to_timedeltastruct
diff --git a/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c b/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c index 934c54fafb634..f854f7b9210d8 100644 --- a/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c +++ b/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c @@ -710,355 +710,121 @@ void pandas_datetime_to_datetimestruct(npy_datetime dt, NPY_DATETIMEUNIT base, void pandas_timedelta_to_timedeltastruct(npy_timedelta td, NPY_DATETIMEUNIT base, pandas_timedeltastruct *out) { - npy_int64 frac; - npy_int64 sfrac; - npy_int64 ifrac; - int sign; - npy_int64 per_day; - npy_int64 per_sec; - /* Initialize the output to all zeros */ memset(out, 0, sizeof(pandas_timedeltastruct)); - switch (base) { - case NPY_FR_ns: - - per_day = 86400000000000LL; - per_sec = 1000LL * 1000LL * 1000LL; - - // put frac in seconds - if (td < 0 && td % per_sec != 0) - frac = td / per_sec - 1; - else - frac = td / per_sec; - - if (frac < 0) { - sign = -1; - - // even fraction - if ((-frac % 86400LL) != 0) { - out->days = -frac / 86400LL + 1; - frac += 86400LL * out->days; - } else { - frac = -frac; - } - } else { - sign = 1; - out->days = 0; - } - - if (frac >= 86400) { - out->days += frac / 86400LL; - frac -= out->days * 86400LL; - } - - if (frac >= 3600) { - out->hrs = (npy_int32)(frac / 3600LL); - frac -= out->hrs * 3600LL; - } else { - out->hrs = 0; - } - - if (frac >= 60) { - out->min = (npy_int32)(frac / 60LL); - frac -= out->min * 60LL; - } else { - out->min = 0; - } - - if (frac >= 0) { - out->sec = (npy_int32)frac; - frac -= out->sec; - } else { - out->sec = 0; - } + const npy_int64 sec_per_hour = 3600; + const npy_int64 sec_per_min = 60; - sfrac = (out->hrs * 3600LL + out->min * 60LL + out->sec) * per_sec; - - if (sign < 0) - out->days = -out->days; - - ifrac = td - (out->days * per_day + sfrac); - - if (ifrac != 0) { - out->ms = (npy_int32)(ifrac / (1000LL * 1000LL)); - ifrac -= out->ms * 1000LL * 1000LL; - out->us = (npy_int32)(ifrac / 1000LL); - ifrac -= out->us * 1000LL; - out->ns = (npy_int32)ifrac; - } else { - out->ms = 0; - out->us = 0; - out->ns = 0; - } + switch (base) { + case NPY_FR_W: + out->days = 7 * td; break; - - case NPY_FR_us: - - per_day = 86400000000LL; - per_sec = 1000LL * 1000LL; - - // put frac in seconds - if (td < 0 && td % per_sec != 0) - frac = td / per_sec - 1; - else - frac = td / per_sec; - - if (frac < 0) { - sign = -1; - - // even fraction - if ((-frac % 86400LL) != 0) { - out->days = -frac / 86400LL + 1; - frac += 86400LL * out->days; - } else { - frac = -frac; - } - } else { - sign = 1; - out->days = 0; - } - - if (frac >= 86400) { - out->days += frac / 86400LL; - frac -= out->days * 86400LL; - } - - if (frac >= 3600) { - out->hrs = (npy_int32)(frac / 3600LL); - frac -= out->hrs * 3600LL; - } else { - out->hrs = 0; - } - - if (frac >= 60) { - out->min = (npy_int32)(frac / 60LL); - frac -= out->min * 60LL; - } else { - out->min = 0; - } - - if (frac >= 0) { - out->sec = (npy_int32)frac; - frac -= out->sec; - } else { - out->sec = 0; - } - - sfrac = (out->hrs * 3600LL + out->min * 60LL + out->sec) * per_sec; - - if (sign < 0) - out->days = -out->days; - - ifrac = td - (out->days * per_day + sfrac); - - if (ifrac != 0) { - out->ms = (npy_int32)(ifrac / 1000LL); - ifrac -= out->ms * 1000LL; - out->us = (npy_int32)(ifrac / 1L); - ifrac -= out->us * 1L; - out->ns = (npy_int32)ifrac; - } else { - out->ms = 0; - out->us = 0; - out->ns = 0; - } + case NPY_FR_D: + out->days = td; break; - + case NPY_FR_h: + out->days = td / 24LL; + td -= out->days * 24LL; + out->hrs = (npy_int32)td; + break; + case NPY_FR_m: + out->days = td / 1440LL; + td -= out->days * 1440LL; + out->hrs = (npy_int32)(td / 60LL); + td -= out->hrs * 60LL; + out->min = (npy_int32)td; + break; + case NPY_FR_s: case NPY_FR_ms: - - per_day = 86400000LL; - per_sec = 1000LL; - - // put frac in seconds - if (td < 0 && td % per_sec != 0) - frac = td / per_sec - 1; - else - frac = td / per_sec; - - if (frac < 0) { - sign = -1; - - // even fraction - if ((-frac % 86400LL) != 0) { - out->days = -frac / 86400LL + 1; - frac += 86400LL * out->days; - } else { - frac = -frac; - } - } else { - sign = 1; - out->days = 0; - } - - if (frac >= 86400) { - out->days += frac / 86400LL; - frac -= out->days * 86400LL; - } - - if (frac >= 3600) { - out->hrs = (npy_int32)(frac / 3600LL); - frac -= out->hrs * 3600LL; - } else { - out->hrs = 0; - } - - if (frac >= 60) { - out->min = (npy_int32)(frac / 60LL); - frac -= out->min * 60LL; - } else { - out->min = 0; - } - - if (frac >= 0) { - out->sec = (npy_int32)frac; - frac -= out->sec; - } else { - out->sec = 0; - } - - sfrac = (out->hrs * 3600LL + out->min * 60LL + out->sec) * per_sec; - - if (sign < 0) - out->days = -out->days; - - ifrac = td - (out->days * per_day + sfrac); - - if (ifrac != 0) { - out->ms = (npy_int32)ifrac; - out->us = 0; - out->ns = 0; + case NPY_FR_us: + case NPY_FR_ns: { + const npy_int64 sec_per_day = 86400; + npy_int64 per_sec; + if (base == NPY_FR_s) { + per_sec = 1; + } else if (base == NPY_FR_ms) { + per_sec = 1000; + } else if (base == NPY_FR_us) { + per_sec = 1000000; } else { - out->ms = 0; - out->us = 0; - out->ns = 0; + per_sec = 1000000000; } - break; - - case NPY_FR_s: - // special case where we can simplify many expressions bc per_sec=1 - - per_day = 86400LL; - per_sec = 1L; + const npy_int64 per_day = sec_per_day * per_sec; + npy_int64 frac; // put frac in seconds if (td < 0 && td % per_sec != 0) frac = td / per_sec - 1; else frac = td / per_sec; + const int sign = frac < 0 ? -1 : 1; if (frac < 0) { - sign = -1; - // even fraction - if ((-frac % 86400LL) != 0) { - out->days = -frac / 86400LL + 1; - frac += 86400LL * out->days; + if ((-frac % sec_per_day) != 0) { + out->days = -frac / sec_per_day + 1; + frac += sec_per_day * out->days; } else { frac = -frac; } - } else { - sign = 1; - out->days = 0; } - if (frac >= 86400) { - out->days += frac / 86400LL; - frac -= out->days * 86400LL; + if (frac >= sec_per_day) { + out->days += frac / sec_per_day; + frac -= out->days * sec_per_day; } - if (frac >= 3600) { - out->hrs = (npy_int32)(frac / 3600LL); - frac -= out->hrs * 3600LL; - } else { - out->hrs = 0; + if (frac >= sec_per_hour) { + out->hrs = (npy_int32)(frac / sec_per_hour); + frac -= out->hrs * sec_per_hour; } - if (frac >= 60) { - out->min = (npy_int32)(frac / 60LL); - frac -= out->min * 60LL; - } else { - out->min = 0; + if (frac >= sec_per_min) { + out->min = (npy_int32)(frac / sec_per_min); + frac -= out->min * sec_per_min; } if (frac >= 0) { out->sec = (npy_int32)frac; frac -= out->sec; - } else { - out->sec = 0; } - sfrac = (out->hrs * 3600LL + out->min * 60LL + out->sec) * per_sec; - if (sign < 0) out->days = -out->days; - ifrac = td - (out->days * per_day + sfrac); - - if (ifrac != 0) { - out->ms = 0; - out->us = 0; - out->ns = 0; - } else { - out->ms = 0; - out->us = 0; - out->ns = 0; + if (base > NPY_FR_s) { + const npy_int64 sfrac = + (out->hrs * sec_per_hour + out->min * sec_per_min + out->sec) * + per_sec; + + npy_int64 ifrac = td - (out->days * per_day + sfrac); + + if (base == NPY_FR_ms) { + out->ms = (npy_int32)ifrac; + } else if (base == NPY_FR_us) { + out->ms = (npy_int32)(ifrac / 1000LL); + ifrac = ifrac % 1000LL; + out->us = (npy_int32)ifrac; + } else if (base == NPY_FR_ns) { + out->ms = (npy_int32)(ifrac / (1000LL * 1000LL)); + ifrac = ifrac % (1000LL * 1000LL); + out->us = (npy_int32)(ifrac / 1000LL); + ifrac = ifrac % 1000LL; + out->ns = (npy_int32)ifrac; + } } - break; - - case NPY_FR_m: - - out->days = td / 1440LL; - td -= out->days * 1440LL; - out->hrs = (npy_int32)(td / 60LL); - td -= out->hrs * 60LL; - out->min = (npy_int32)td; - - out->sec = 0; - out->ms = 0; - out->us = 0; - out->ns = 0; - break; - - case NPY_FR_h: - out->days = td / 24LL; - td -= out->days * 24LL; - out->hrs = (npy_int32)td; - - out->min = 0; - out->sec = 0; - out->ms = 0; - out->us = 0; - out->ns = 0; - break; - - case NPY_FR_D: - out->days = td; - out->hrs = 0; - out->min = 0; - out->sec = 0; - out->ms = 0; - out->us = 0; - out->ns = 0; - break; - - case NPY_FR_W: - out->days = 7 * td; - out->hrs = 0; - out->min = 0; - out->sec = 0; - out->ms = 0; - out->us = 0; - out->ns = 0; - break; + } break; default: PyErr_SetString(PyExc_RuntimeError, "NumPy timedelta metadata is corrupted with " "invalid base unit"); + break; } - out->seconds = out->hrs * 3600 + out->min * 60 + out->sec; + out->seconds = + (npy_int32)(out->hrs * sec_per_hour + out->min * sec_per_min + out->sec); out->microseconds = out->ms * 1000 + out->us; out->nanoseconds = out->ns; }
this mostly cuts down on copy paste, but also implements `const` where it can be done on some variables
https://api.github.com/repos/pandas-dev/pandas/pulls/55999
2023-11-16T18:05:16Z
2024-03-20T16:58:27Z
2024-03-20T16:58:27Z
2024-03-22T15:35:28Z
create pull req
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 78b99a00d43ce..c2b4056015722 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -1,5 +1,5 @@ """ -test .agg behavior / note that .apply is tested generally in test_groupby.py +test .agg behavior / note that .apply is tested generally in test_groupby.py__ """ import datetime import functools diff --git a/pandas/tests/groupby/methods/test_describe.py b/pandas/tests/groupby/methods/test_describe.py index c2ffcb04caa60..d63ec9ed6de75 100644 --- a/pandas/tests/groupby/methods/test_describe.py +++ b/pandas/tests/groupby/methods/test_describe.py @@ -276,7 +276,7 @@ def test_describe(self, df, gb, gni): ], ) def test_groupby_empty_dataset(dtype, kwargs): - # GH#41575 + # GH#41575__ df = DataFrame([[1, 2, 3]], columns=["A", "B", "C"], dtype=dtype) df["B"] = df["B"].astype(int) df["C"] = df["C"].astype(float)
- [ ] 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/55998
2023-11-16T17:27:20Z
2023-11-16T17:36:36Z
null
2023-11-16T17:36:36Z
REF: use numpy cimports
diff --git a/pandas/_libs/interval.pyx b/pandas/_libs/interval.pyx index 82f69c1dedd53..691fd05fe5ded 100644 --- a/pandas/_libs/interval.pyx +++ b/pandas/_libs/interval.pyx @@ -39,7 +39,6 @@ from pandas._libs.tslibs.timezones cimport tz_compare from pandas._libs.tslibs.util cimport ( is_float_object, is_integer_object, - is_timedelta64_object, ) VALID_CLOSED = frozenset(["left", "right", "both", "neither"]) @@ -493,7 +492,7 @@ cdef class Interval(IntervalMixin): if ( isinstance(y, numbers.Number) or PyDelta_Check(y) - or is_timedelta64_object(y) + or cnp.is_timedelta64_object(y) ): return Interval(self.left + y, self.right + y, closed=self.closed) elif ( @@ -503,7 +502,7 @@ cdef class Interval(IntervalMixin): and ( isinstance(self, numbers.Number) or PyDelta_Check(self) - or is_timedelta64_object(self) + or cnp.is_timedelta64_object(self) ) ): return Interval(y.left + self, y.right + self, closed=y.closed) @@ -513,7 +512,7 @@ cdef class Interval(IntervalMixin): if ( isinstance(other, numbers.Number) or PyDelta_Check(other) - or is_timedelta64_object(other) + or cnp.is_timedelta64_object(other) ): return Interval(self.left + other, self.right + other, closed=self.closed) return NotImplemented @@ -522,7 +521,7 @@ cdef class Interval(IntervalMixin): if ( isinstance(y, numbers.Number) or PyDelta_Check(y) - or is_timedelta64_object(y) + or cnp.is_timedelta64_object(y) ): return Interval(self.left - y, self.right - y, closed=self.closed) return NotImplemented diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index e8a69891c6093..eac0b4418540e 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -92,9 +92,6 @@ cdef extern from "numpy/arrayobject.h": PyTypeObject PySignedIntegerArrType_Type PyTypeObject PyUnsignedIntegerArrType_Type -cdef extern from "numpy/ndarrayobject.h": - bint PyArray_CheckScalar(obj) nogil - cdef extern from "pandas/parser/pd_parser.h": int floatify(object, float64_t *result, int *maybe_int) except -1 void PandasParser_IMPORT() @@ -272,7 +269,7 @@ cdef int64_t get_itemsize(object val): ------- is_ndarray : bool """ - if PyArray_CheckScalar(val): + if cnp.PyArray_CheckScalar(val): return cnp.PyArray_DescrFromScalar(val).itemsize else: return -1 diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index c2d2acd95ce43..d5fb860d9cc82 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -23,7 +23,6 @@ import_datetime() cimport numpy as cnp from numpy cimport ( int64_t, - is_datetime64_object, ndarray, ) @@ -513,7 +512,7 @@ cpdef array_to_datetime( iresult[i] = pydate_to_dt64(val, &dts, reso=creso) state.found_other = True - elif is_datetime64_object(val): + elif cnp.is_datetime64_object(val): item_reso = get_supported_reso(get_datetime64_unit(val)) state.update_creso(item_reso) if infer_reso: diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 89b420b18a980..23352bc81e12a 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -5,7 +5,6 @@ from libc.math cimport log10 from numpy cimport ( int32_t, int64_t, - is_datetime64_object, ) cnp.import_array() @@ -285,7 +284,7 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, if checknull_with_nat_and_na(ts): obj.value = NPY_NAT - elif is_datetime64_object(ts): + elif cnp.is_datetime64_object(ts): reso = get_supported_reso(get_datetime64_unit(ts)) obj.creso = reso obj.value = get_datetime64_nanos(ts, reso) diff --git a/pandas/_libs/tslibs/np_datetime.pxd b/pandas/_libs/tslibs/np_datetime.pxd index 9cc211b748f68..a87c3d3f0955d 100644 --- a/pandas/_libs/tslibs/np_datetime.pxd +++ b/pandas/_libs/tslibs/np_datetime.pxd @@ -6,25 +6,12 @@ from cpython.datetime cimport ( from numpy cimport ( int32_t, int64_t, + npy_datetime, + npy_timedelta, ) # TODO(cython3): most of these can be cimported directly from numpy -cdef extern from "numpy/ndarrayobject.h": - ctypedef int64_t npy_timedelta - ctypedef int64_t npy_datetime - -cdef extern from "numpy/ndarraytypes.h": - ctypedef struct PyArray_DatetimeMetaData: - NPY_DATETIMEUNIT base - int64_t num - -cdef extern from "numpy/arrayscalars.h": - ctypedef struct PyDatetimeScalarObject: - # PyObject_HEAD - npy_datetime obval - PyArray_DatetimeMetaData obmeta - cdef extern from "numpy/ndarraytypes.h": ctypedef struct npy_datetimestruct: int64_t year diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index fa9b82fe46634..73a3540c8d6b8 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -28,6 +28,8 @@ cimport numpy as cnp cnp.import_array() from numpy cimport ( + PyArray_DatetimeMetaData, + PyDatetimeScalarObject, int64_t, ndarray, uint8_t, diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 7f3a72178a359..bf18a4d435573 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -25,7 +25,6 @@ import numpy as np cimport numpy as cnp from numpy cimport ( int64_t, - is_datetime64_object, ndarray, ) @@ -159,7 +158,7 @@ def apply_wraps(func): ): # timedelta path return func(self, other) - elif is_datetime64_object(other) or PyDate_Check(other): + elif cnp.is_datetime64_object(other) or PyDate_Check(other): # PyDate_Check includes date, datetime other = Timestamp(other) else: @@ -1087,7 +1086,7 @@ cdef class Tick(SingleConstructorOffset): return other + self.delta elif other is NaT: return NaT - elif is_datetime64_object(other) or PyDate_Check(other): + elif cnp.is_datetime64_object(other) or PyDate_Check(other): # PyDate_Check includes date, datetime return Timestamp(other) + self diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 8966c9e81699b..acfcd1cbd217a 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -43,7 +43,6 @@ import pytz cimport numpy as cnp from numpy cimport ( int64_t, - is_datetime64_object, ndarray, ) @@ -377,7 +376,7 @@ def array_strptime( creso = state.creso iresult[i] = pydate_to_dt64(val, &dts, reso=creso) continue - elif is_datetime64_object(val): + elif cnp.is_datetime64_object(val): item_reso = get_supported_reso(get_datetime64_unit(val)) state.update_creso(item_reso) if infer_reso: diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 0a9bd2ac2770b..5852a7d95d994 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -20,8 +20,6 @@ import numpy as np cimport numpy as cnp from numpy cimport ( int64_t, - is_datetime64_object, - is_timedelta64_object, ndarray, ) @@ -253,7 +251,7 @@ cpdef int64_t delta_to_nanoseconds( n = delta._value in_reso = delta._creso - elif is_timedelta64_object(delta): + elif cnp.is_timedelta64_object(delta): in_reso = get_datetime64_unit(delta) if in_reso == NPY_DATETIMEUNIT.NPY_FR_Y or in_reso == NPY_DATETIMEUNIT.NPY_FR_M: raise ValueError( @@ -347,7 +345,7 @@ cdef convert_to_timedelta64(object ts, str unit): ts = ts.as_unit("ns").asm8 else: ts = np.timedelta64(ts._value, "ns") - elif is_timedelta64_object(ts): + elif cnp.is_timedelta64_object(ts): ts = ensure_td64ns(ts) elif is_integer_object(ts): if ts == NPY_NAT: @@ -367,7 +365,7 @@ cdef convert_to_timedelta64(object ts, str unit): if PyDelta_Check(ts): ts = np.timedelta64(delta_to_nanoseconds(ts), "ns") - elif not is_timedelta64_object(ts): + elif not cnp.is_timedelta64_object(ts): raise TypeError(f"Invalid type for timedelta scalar: {type(ts)}") return ts.astype("timedelta64[ns]") @@ -764,7 +762,7 @@ def _binary_op_method_timedeltalike(op, name): if other is NaT: return NaT - elif is_datetime64_object(other) or ( + elif cnp.is_datetime64_object(other) or ( PyDateTime_Check(other) and not isinstance(other, ABCTimestamp) ): # this case is for a datetime object that is specifically @@ -1853,7 +1851,7 @@ class Timedelta(_Timedelta): return cls._from_value_and_reso( new_value, reso=NPY_DATETIMEUNIT.NPY_FR_us ) - elif is_timedelta64_object(value): + elif cnp.is_timedelta64_object(value): # Retain the resolution if possible, otherwise cast to the nearest # supported resolution. new_value = cnp.get_timedelta64_value(value) @@ -1904,7 +1902,7 @@ class Timedelta(_Timedelta): f"float, timedelta or convertible, not {type(value).__name__}" ) - if is_timedelta64_object(value): + if cnp.is_timedelta64_object(value): value = value.view("i8") # nat @@ -2279,7 +2277,7 @@ cdef bint is_any_td_scalar(object obj): bool """ return ( - PyDelta_Check(obj) or is_timedelta64_object(obj) or is_tick_object(obj) + PyDelta_Check(obj) or cnp.is_timedelta64_object(obj) or is_tick_object(obj) ) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 56a6885d4a9e0..e953945d76f45 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -16,7 +16,6 @@ import numpy as np cimport numpy as cnp from numpy cimport ( int64_t, - is_datetime64_object, ndarray, uint8_t, ) @@ -329,7 +328,7 @@ cdef class _Timestamp(ABCTimestamp): ots = other elif other is NaT: return op == Py_NE - elif is_datetime64_object(other): + elif cnp.is_datetime64_object(other): ots = Timestamp(other) elif PyDateTime_Check(other): if self.nanosecond == 0: @@ -510,7 +509,7 @@ cdef class _Timestamp(ABCTimestamp): # coerce if necessary if we are a Timestamp-like if (PyDateTime_Check(self) - and (PyDateTime_Check(other) or is_datetime64_object(other))): + and (PyDateTime_Check(other) or cnp.is_datetime64_object(other))): # both_timestamps is to determine whether Timedelta(self - other) # should raise the OOB error, or fall back returning a timedelta. # TODO(cython3): clean out the bits that moved to __rsub__ @@ -549,7 +548,7 @@ cdef class _Timestamp(ABCTimestamp): # We get here in stata tests, fall back to stdlib datetime # method and return stdlib timedelta object pass - elif is_datetime64_object(self): + elif cnp.is_datetime64_object(self): # GH#28286 cython semantics for __rsub__, `other` is actually # the Timestamp # TODO(cython3): remove this, this moved to __rsub__ @@ -565,7 +564,7 @@ cdef class _Timestamp(ABCTimestamp): # We get here in stata tests, fall back to stdlib datetime # method and return stdlib timedelta object pass - elif is_datetime64_object(other): + elif cnp.is_datetime64_object(other): return type(self)(other) - self return NotImplemented diff --git a/pandas/_libs/tslibs/util.pxd b/pandas/_libs/tslibs/util.pxd index ddd07276c7a7e..44ff322060dcb 100644 --- a/pandas/_libs/tslibs/util.pxd +++ b/pandas/_libs/tslibs/util.pxd @@ -23,6 +23,7 @@ cdef extern from "Python.h": from numpy cimport ( + PyArray_Check, float64_t, int64_t, is_timedelta64_object, @@ -37,7 +38,6 @@ cdef extern from "numpy/ndarrayobject.h": PyTypeObject PyBoolArrType_Type bint PyArray_IsIntegerScalar(obj) nogil - bint PyArray_Check(obj) nogil cdef extern from "numpy/npy_common.h": int64_t NPY_MIN_INT64
Works locally, will see on the CI if min-versions checks out.
https://api.github.com/repos/pandas-dev/pandas/pulls/55995
2023-11-16T15:32:30Z
2023-11-16T17:07:11Z
2023-11-16T17:07:11Z
2023-11-16T17:56:58Z
CI fix ci whatsnew items
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 38804d9b07878..93b0ccad9f2aa 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -263,6 +263,7 @@ Other Deprecations ^^^^^^^^^^^^^^^^^^ - Changed :meth:`Timedelta.resolution_string` to return ``h``, ``min``, ``s``, ``ms``, ``us``, and ``ns`` instead of ``H``, ``T``, ``S``, ``L``, ``U``, and ``N``, for compatibility with respective deprecations in frequency aliases (:issue:`52536`) - Deprecated :func:`read_gbq` and :meth:`DataFrame.to_gbq`. Use ``pandas_gbq.read_gbq`` and ``pandas_gbq.to_gbq`` instead https://pandas-gbq.readthedocs.io/en/latest/api.html (:issue:`55525`) +- Deprecated :meth:`.DataFrameGroupBy.fillna` and :meth:`.SeriesGroupBy.fillna`; use :meth:`.DataFrameGroupBy.ffill`, :meth:`.DataFrameGroupBy.bfill` for forward and backward filling or :meth:`.DataFrame.fillna` to fill with a single value (or the Series equivalents) (:issue:`55718`) - Deprecated :meth:`Index.format`, use ``index.astype(str)`` or ``index.map(formatter)`` instead (:issue:`55413`) - Deprecated ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard`. (:issue:`54229`) @@ -300,7 +301,6 @@ Other Deprecations - Deprecated the option ``mode.data_manager`` and the ``ArrayManager``; only the ``BlockManager`` will be available in future versions (:issue:`55043`) - Deprecated the previous implementation of :class:`DataFrame.stack`; specify ``future_stack=True`` to adopt the future version (:issue:`53515`) - Deprecating downcasting the results of :meth:`DataFrame.fillna`, :meth:`Series.fillna`, :meth:`DataFrame.ffill`, :meth:`Series.ffill`, :meth:`DataFrame.bfill`, :meth:`Series.bfill` in object-dtype cases. To opt in to the future version, use ``pd.set_option("future.no_silent_downcasting", True)`` (:issue:`54261`) -- Deprecated :meth:`.DataFrameGroupBy.fillna` and :meth:`.SeriesGroupBy.fillna`; use :meth:`.DataFrameGroupBy.ffill`, :meth:`.DataFrameGroupBy.bfill` for forward and backward filling or :meth:`.DataFrame.fillna` to fill with a single value (or the Series equivalents) (:issue:`55718`) - .. ---------------------------------------------------------------------------
- [ ] 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/55994
2023-11-16T14:00:53Z
2023-11-16T14:06:00Z
2023-11-16T14:06:00Z
2023-11-16T14:06:00Z
TST update and simplify consortium api test
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index fe5bd33e15f15..c2e39dc38d5ff 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -337,11 +337,9 @@ def test_dataframe_consortium() -> None: expected_1 = ["a", "b"] assert result_1 == expected_1 - ser = Series([1, 2, 3]) + ser = Series([1, 2, 3], name="a") col = ser.__column_consortium_standard__() - result_2 = col.get_value(1) - expected_2 = 2 - assert result_2 == expected_2 + assert col.name == "a" def test_xarray_coerce_unit():
It's quite likely that the dataframe api will have a `Scalar` class, and that `Column.get_value` will return that I'm suggesting to just simplify the test to make an assertion about `Column.name`, which realistically isn't going to change --- Docs CI failure is unrelated and due to https://github.com/scipy/docs.scipy.org/issues/80
https://api.github.com/repos/pandas-dev/pandas/pulls/55993
2023-11-16T13:50:15Z
2023-11-16T17:09:26Z
2023-11-16T17:09:26Z
2023-11-22T07:59:54Z
REF: de-duplicate freq pinning/validation
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 33b2f65340a3b..c3b4ce8a9f7d4 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1938,7 +1938,7 @@ def __init__( freq = values.freq elif freq and values.freq: freq = to_offset(freq) - freq, _ = validate_inferred_freq(freq, values.freq, False) + freq = _validate_inferred_freq(freq, values.freq) if dtype is not None and dtype != values.dtype: # TODO: we only have tests for this for DTA, not TDA (2022-07-01) @@ -2025,6 +2025,39 @@ def freq(self, value) -> None: self._freq = value + @final + def _maybe_pin_freq(self, freq, validate_kwds: dict): + """ + Constructor helper to pin the appropriate `freq` attribute. Assumes + that self._freq is currently set to any freq inferred in + _from_sequence_not_strict. + """ + if freq is None: + # user explicitly passed None -> override any inferred_freq + self._freq = None + elif freq == "infer": + # if self._freq is *not* None then we already inferred a freq + # and there is nothing left to do + if self._freq is None: + # Set _freq directly to bypass duplicative _validate_frequency + # check. + self._freq = to_offset(self.inferred_freq) + elif freq is lib.no_default: + # user did not specify anything, keep inferred freq if the original + # data had one, otherwise do nothing + pass + elif self._freq is None: + # We cannot inherit a freq from the data, so we need to validate + # the user-passed freq + freq = to_offset(freq) + type(self)._validate_frequency(self, freq, **validate_kwds) + self._freq = freq + else: + # Otherwise we just need to check that the user-passed freq + # doesn't conflict with the one we already have. + freq = to_offset(freq) + _validate_inferred_freq(freq, self._freq) + @final @classmethod def _validate_frequency(cls, index, freq: BaseOffset, **kwargs): @@ -2353,7 +2386,9 @@ def _is_dates_only(self) -> bool: # Shared Constructor Helpers -def ensure_arraylike_for_datetimelike(data, copy: bool, cls_name: str): +def ensure_arraylike_for_datetimelike( + data, copy: bool, cls_name: str +) -> tuple[ArrayLike, bool]: if not hasattr(data, "dtype"): # e.g. list, tuple if not isinstance(data, (list, tuple)) and np.ndim(data) == 0: @@ -2426,9 +2461,9 @@ def validate_periods(periods: int | float | None) -> int | None: return periods -def validate_inferred_freq( - freq, inferred_freq, freq_infer -) -> tuple[BaseOffset | None, bool]: +def _validate_inferred_freq( + freq: BaseOffset | None, inferred_freq: BaseOffset | None +) -> BaseOffset | None: """ If the user passes a freq and another freq is inferred from passed data, require that they match. @@ -2437,12 +2472,10 @@ def validate_inferred_freq( ---------- freq : DateOffset or None inferred_freq : DateOffset or None - freq_infer : bool Returns ------- freq : DateOffset or None - freq_infer : bool Notes ----- @@ -2458,12 +2491,11 @@ def validate_inferred_freq( ) if freq is None: freq = inferred_freq - freq_infer = False - return freq, freq_infer + return freq -def maybe_infer_freq(freq): +def maybe_infer_freq(freq) -> tuple[BaseOffset | None, bool]: """ Comparing a DateOffset to the string "infer" raises, so we need to be careful about comparisons. Make a dummy variable `freq_infer` to diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 6efff2483e1ae..b100a6a80f8ed 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -76,6 +76,7 @@ from collections.abc import Iterator from pandas._typing import ( + ArrayLike, DateTimeErrorChoices, DtypeObj, IntervalClosedType, @@ -327,13 +328,10 @@ def _from_sequence_not_strict( dayfirst: bool = False, yearfirst: bool = False, ambiguous: TimeAmbiguous = "raise", - ): + ) -> Self: """ A non-strict version of _from_sequence, called from DatetimeIndex.__new__. """ - explicit_none = freq is None - freq = freq if freq is not lib.no_default else None - freq, freq_infer = dtl.maybe_infer_freq(freq) # if the user either explicitly passes tz=None or a tz-naive dtype, we # disallows inferring a tz. @@ -349,13 +347,16 @@ def _from_sequence_not_strict( unit = None if dtype is not None: - if isinstance(dtype, np.dtype): - unit = np.datetime_data(dtype)[0] - else: - # DatetimeTZDtype - unit = dtype.unit + unit = dtl.dtype_to_unit(dtype) + + data, copy = dtl.ensure_arraylike_for_datetimelike( + data, copy, cls_name="DatetimeArray" + ) + inferred_freq = None + if isinstance(data, DatetimeArray): + inferred_freq = data.freq - subarr, tz, inferred_freq = _sequence_to_dt64( + subarr, tz = _sequence_to_dt64( data, copy=copy, tz=tz, @@ -372,26 +373,15 @@ def _from_sequence_not_strict( "Use obj.tz_localize(None) instead." ) - freq, freq_infer = dtl.validate_inferred_freq(freq, inferred_freq, freq_infer) - if explicit_none: - freq = None - data_unit = np.datetime_data(subarr.dtype)[0] data_dtype = tz_to_dtype(tz, data_unit) - result = cls._simple_new(subarr, freq=freq, dtype=data_dtype) + result = cls._simple_new(subarr, freq=inferred_freq, dtype=data_dtype) if unit is not None and unit != result.unit: # If unit was specified in user-passed dtype, cast to it here result = result.as_unit(unit) - if inferred_freq is None and freq is not None: - # this condition precludes `freq_infer` - cls._validate_frequency(result, freq, ambiguous=ambiguous) - - elif freq_infer: - # Set _freq directly to bypass duplicative _validate_frequency - # check. - result._freq = to_offset(result.inferred_freq) - + validate_kwds = {"ambiguous": ambiguous} + result._maybe_pin_freq(freq, validate_kwds) return result # error: Signature of "_generate_range" incompatible with supertype @@ -2180,7 +2170,7 @@ def std( def _sequence_to_dt64( - data, + data: ArrayLike, *, copy: bool = False, tz: tzinfo | None = None, @@ -2192,7 +2182,8 @@ def _sequence_to_dt64( """ Parameters ---------- - data : list-like + data : np.ndarray or ExtensionArray + dtl.ensure_arraylike_for_datetimelike has already been called. copy : bool, default False tz : tzinfo or None, default None dayfirst : bool, default False @@ -2209,21 +2200,11 @@ def _sequence_to_dt64( Where `unit` is "ns" unless specified otherwise by `out_unit`. tz : tzinfo or None Either the user-provided tzinfo or one inferred from the data. - inferred_freq : Tick or None - The inferred frequency of the sequence. Raises ------ TypeError : PeriodDType data is passed """ - inferred_freq = None - - data, copy = dtl.ensure_arraylike_for_datetimelike( - data, copy, cls_name="DatetimeArray" - ) - - if isinstance(data, DatetimeArray): - inferred_freq = data.freq # By this point we are assured to have either a numpy array or Index data, copy = maybe_convert_dtype(data, copy, tz=tz) @@ -2236,6 +2217,7 @@ def _sequence_to_dt64( if data_dtype == object or is_string_dtype(data_dtype): # TODO: We do not have tests specific to string-dtypes, # also complex or categorical or other extension + data = cast(np.ndarray, data) copy = False if lib.infer_dtype(data, skipna=False) == "integer": data = data.astype(np.int64) @@ -2248,7 +2230,7 @@ def _sequence_to_dt64( yearfirst=yearfirst, creso=abbrev_to_npy_unit(out_unit), ) - return result, tz, None + return result, tz else: converted, inferred_tz = objects_to_datetime64( data, @@ -2273,7 +2255,7 @@ def _sequence_to_dt64( result, _ = _construct_from_dt64_naive( converted, tz=tz, copy=copy, ambiguous=ambiguous ) - return result, tz, None + return result, tz data_dtype = data.dtype @@ -2281,6 +2263,7 @@ def _sequence_to_dt64( # so we need to handle these types. if isinstance(data_dtype, DatetimeTZDtype): # DatetimeArray -> ndarray + data = cast(DatetimeArray, data) tz = _maybe_infer_tz(tz, data.tz) result = data._ndarray @@ -2289,6 +2272,7 @@ def _sequence_to_dt64( if isinstance(data, DatetimeArray): data = data._ndarray + data = cast(np.ndarray, data) result, copy = _construct_from_dt64_naive( data, tz=tz, copy=copy, ambiguous=ambiguous ) @@ -2299,6 +2283,7 @@ def _sequence_to_dt64( if data.dtype != INT64_DTYPE: data = data.astype(np.int64, copy=False) copy = False + data = cast(np.ndarray, data) result = data.view(out_dtype) if copy: @@ -2308,7 +2293,7 @@ def _sequence_to_dt64( assert result.dtype.kind == "M" assert result.dtype != "M8" assert is_supported_unit(get_unit_from_dtype(result.dtype)) - return result, tz, inferred_freq + return result, tz def _construct_from_dt64_naive( diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index b64ab1154ef96..226e2568fdbf8 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -26,7 +26,6 @@ is_supported_unit, npy_unit_to_abbrev, periods_per_second, - to_offset, ) from pandas._libs.tslibs.conversion import precision_from_unit from pandas._libs.tslibs.dtypes import abbrev_to_npy_unit @@ -236,9 +235,7 @@ def _from_sequence(cls, data, *, dtype=None, copy: bool = False) -> Self: if dtype: dtype = _validate_td64_dtype(dtype) - data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=None) - freq, _ = dtl.validate_inferred_freq(None, inferred_freq, False) - freq = cast("Tick | None", freq) + data, freq = sequence_to_td64ns(data, copy=copy, unit=None) if dtype is not None: data = astype_overflowsafe(data, dtype=dtype, copy=False) @@ -256,38 +253,22 @@ def _from_sequence_not_strict( unit=None, ) -> Self: """ - A non-strict version of _from_sequence, called from TimedeltaIndex.__new__. + _from_sequence_not_strict but without responsibility for finding the + result's `freq`. """ if dtype: dtype = _validate_td64_dtype(dtype) assert unit not in ["Y", "y", "M"] # caller is responsible for checking - explicit_none = freq is None - freq = freq if freq is not lib.no_default else None - - freq, freq_infer = dtl.maybe_infer_freq(freq) - data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=unit) - freq, freq_infer = dtl.validate_inferred_freq(freq, inferred_freq, freq_infer) - freq = cast("Tick | None", freq) - if explicit_none: - freq = None if dtype is not None: data = astype_overflowsafe(data, dtype=dtype, copy=False) - result = cls._simple_new(data, dtype=data.dtype, freq=freq) - - if inferred_freq is None and freq is not None: - # this condition precludes `freq_infer` - cls._validate_frequency(result, freq) - - elif freq_infer: - # Set _freq directly to bypass duplicative _validate_frequency - # check. - result._freq = to_offset(result.inferred_freq) + result = cls._simple_new(data, dtype=data.dtype, freq=inferred_freq) + result._maybe_pin_freq(freq, {}) return result # Signature of "_generate_range" incompatible with supertype
- [ ] 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/55987
2023-11-16T06:14:49Z
2023-11-16T17:16:21Z
2023-11-16T17:16:21Z
2023-11-16T17:59:11Z
CLN: remove unused unit argument
diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index c2d2acd95ce43..4201c499cce72 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -551,7 +551,7 @@ cpdef array_to_datetime( continue _ts = convert_str_to_tsobject( - val, None, unit="ns", dayfirst=dayfirst, yearfirst=yearfirst + val, None, dayfirst=dayfirst, yearfirst=yearfirst ) item_reso = _ts.creso state.update_creso(item_reso) @@ -716,7 +716,7 @@ cdef _array_to_datetime_object( try: tsobj = convert_str_to_tsobject( - val, None, unit="ns", dayfirst=dayfirst, yearfirst=yearfirst + val, None, dayfirst=dayfirst, yearfirst=yearfirst ) tsobj.ensure_reso(NPY_FR_ns, val) diff --git a/pandas/_libs/tslibs/conversion.pxd b/pandas/_libs/tslibs/conversion.pxd index e97f4900d20c8..7ffd630d6d8e1 100644 --- a/pandas/_libs/tslibs/conversion.pxd +++ b/pandas/_libs/tslibs/conversion.pxd @@ -37,7 +37,7 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, tzinfo tz, int32_t nanos=*, NPY_DATETIMEUNIT reso=*) -cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, str unit, +cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, bint dayfirst=*, bint yearfirst=*) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 89b420b18a980..036faea0cdc1f 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -281,7 +281,7 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit, obj = _TSObject() if isinstance(ts, str): - return convert_str_to_tsobject(ts, tz, unit, dayfirst, yearfirst) + return convert_str_to_tsobject(ts, tz, dayfirst, yearfirst) if checknull_with_nat_and_na(ts): obj.value = NPY_NAT @@ -473,7 +473,7 @@ cdef _adjust_tsobject_tz_using_offset(_TSObject obj, tzinfo tz): check_overflows(obj, obj.creso) -cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, str unit, +cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, bint dayfirst=False, bint yearfirst=False): """ @@ -489,7 +489,6 @@ cdef _TSObject convert_str_to_tsobject(str ts, tzinfo tz, str unit, Value to be converted to _TSObject tz : tzinfo or None timezone for the timezone-aware output - unit : str or None dayfirst : bool, default False When parsing an ambiguous date string, interpret e.g. "3/4/1975" as April 3, as opposed to the standard US interpretation March 4.
- [ ] 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/55986
2023-11-16T05:07:09Z
2023-11-16T17:10:32Z
2023-11-16T17:10:32Z
2023-11-16T17:56:22Z
CLN: remove unnecessary bits from dtypes.pyx
diff --git a/pandas/_libs/tslibs/ccalendar.pxd b/pandas/_libs/tslibs/ccalendar.pxd index ca9e01ffa3dbe..3c0f7ea824396 100644 --- a/pandas/_libs/tslibs/ccalendar.pxd +++ b/pandas/_libs/tslibs/ccalendar.pxd @@ -15,6 +15,6 @@ cpdef int32_t get_day_of_year(int year, int month, int day) noexcept nogil cpdef int get_lastbday(int year, int month) noexcept nogil cpdef int get_firstbday(int year, int month) noexcept nogil -cdef dict c_MONTH_NUMBERS +cdef dict c_MONTH_NUMBERS, MONTH_TO_CAL_NUM cdef int32_t* month_offset diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index 1db355fa91a20..536fa19f4c5d7 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -38,7 +38,7 @@ MONTHS_FULL = ["", "January", "February", "March", "April", "May", "June", MONTH_NUMBERS = {name: num for num, name in enumerate(MONTHS)} cdef dict c_MONTH_NUMBERS = MONTH_NUMBERS MONTH_ALIASES = {(num + 1): name for num, name in enumerate(MONTHS)} -MONTH_TO_CAL_NUM = {name: num + 1 for num, name in enumerate(MONTHS)} +cdef dict MONTH_TO_CAL_NUM = {name: num + 1 for num, name in enumerate(MONTHS)} DAYS = ["MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"] DAYS_FULL = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", diff --git a/pandas/_libs/tslibs/dtypes.pyi b/pandas/_libs/tslibs/dtypes.pyi index d8680ed2d27b4..1f35075543fde 100644 --- a/pandas/_libs/tslibs/dtypes.pyi +++ b/pandas/_libs/tslibs/dtypes.pyi @@ -1,14 +1,6 @@ from enum import Enum -from pandas._libs.tslibs.timedeltas import UnitChoices - -# These are not public API, but are exposed in the .pyi file because they -# are imported in tests. -_attrname_to_abbrevs: dict[str, str] -_period_code_map: dict[str, int] OFFSET_TO_PERIOD_FREQSTR: dict[str, str] -OFFSET_DEPR_FREQSTR: dict[str, str] -DEPR_ABBREVS: dict[str, UnitChoices] def periods_per_day(reso: int) -> int: ... def periods_per_second(reso: int) -> int: ... diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx index a8dc6b12a54b5..7995668a9b431 100644 --- a/pandas/_libs/tslibs/dtypes.pyx +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -5,6 +5,7 @@ import warnings from pandas.util._exceptions import find_stack_level +from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS from pandas._libs.tslibs.np_datetime cimport ( NPY_DATETIMEUNIT, get_conversion_factor, @@ -46,7 +47,7 @@ cdef class PeriodDtypeBase: def _resolution_obj(self) -> "Resolution": fgc = self._freq_group_code freq_group = FreqGroup(fgc) - abbrev = _reverse_period_code_map[freq_group.value].split("-")[0] + abbrev = _period_code_to_abbrev[freq_group.value].split("-")[0] if abbrev == "B": return Resolution.RESO_DAY attrname = _abbrev_to_attrnames[abbrev] @@ -55,7 +56,7 @@ cdef class PeriodDtypeBase: @property def _freqstr(self) -> str: # Will be passed to to_offset in Period._maybe_convert_freq - out = _reverse_period_code_map.get(self._dtype_code) + out = _period_code_to_abbrev.get(self._dtype_code) if self._n == 1: return out return str(self._n) + out @@ -150,27 +151,13 @@ _period_code_map = { "ns": PeriodDtypeCode.N, # Nanosecondly } -_reverse_period_code_map = { +cdef dict _period_code_to_abbrev = { _period_code_map[key]: key for key in _period_code_map} -# Yearly aliases; careful not to put these in _reverse_period_code_map -_period_code_map.update({"Y" + key[1:]: _period_code_map[key] - for key in _period_code_map - if key.startswith("Y-")}) - -_period_code_map.update({ - "Q": 2000, # Quarterly - December year end (default quarterly) - "Y": PeriodDtypeCode.A, # Annual - "W": 4000, # Weekly - "C": 5000, # Custom Business Day -}) - -cdef set _month_names = { - x.split("-")[-1] for x in _period_code_map.keys() if x.startswith("Y-") -} +cdef set _month_names = set(c_MONTH_NUMBERS.keys()) # Map attribute-name resolutions to resolution abbreviations -_attrname_to_abbrevs = { +cdef dict attrname_to_abbrevs = { "year": "Y", "quarter": "Q", "month": "M", @@ -182,7 +169,6 @@ _attrname_to_abbrevs = { "microsecond": "us", "nanosecond": "ns", } -cdef dict attrname_to_abbrevs = _attrname_to_abbrevs cdef dict _abbrev_to_attrnames = {v: k for k, v in attrname_to_abbrevs.items()} OFFSET_TO_PERIOD_FREQSTR: dict = { @@ -234,7 +220,7 @@ OFFSET_TO_PERIOD_FREQSTR: dict = { "YS": "Y", "BYS": "Y", } -OFFSET_DEPR_FREQSTR: dict[str, str]= { +cdef dict c_OFFSET_DEPR_FREQSTR = { "M": "ME", "Q": "QE", "Q-DEC": "QE-DEC", @@ -277,8 +263,9 @@ OFFSET_DEPR_FREQSTR: dict[str, str]= { "A-NOV": "YE-NOV", } cdef dict c_OFFSET_TO_PERIOD_FREQSTR = OFFSET_TO_PERIOD_FREQSTR -cdef dict c_OFFSET_DEPR_FREQSTR = OFFSET_DEPR_FREQSTR -cdef dict c_REVERSE_OFFSET_DEPR_FREQSTR = {v: k for k, v in OFFSET_DEPR_FREQSTR.items()} +cdef dict c_REVERSE_OFFSET_DEPR_FREQSTR = { + v: k for k, v in c_OFFSET_DEPR_FREQSTR.items() +} cpdef freq_to_period_freqstr(freq_n, freq_name): if freq_n == 1: @@ -290,7 +277,7 @@ cpdef freq_to_period_freqstr(freq_n, freq_name): return freqstr # Map deprecated resolution abbreviations to correct resolution abbreviations -DEPR_ABBREVS: dict[str, str]= { +cdef dict c_DEPR_ABBREVS = { "A": "Y", "a": "Y", "A-DEC": "Y-DEC", @@ -359,7 +346,6 @@ DEPR_ABBREVS: dict[str, str]= { "N": "ns", "n": "ns", } -cdef dict c_DEPR_ABBREVS = DEPR_ABBREVS class FreqGroup(Enum): @@ -406,7 +392,7 @@ class Resolution(Enum): @property def attr_abbrev(self) -> str: # string that we can pass to to_offset - return _attrname_to_abbrevs[self.attrname] + return attrname_to_abbrevs[self.attrname] @property def attrname(self) -> str: @@ -450,16 +436,19 @@ class Resolution(Enum): >>> Resolution.get_reso_from_freqstr('h') == Resolution.RESO_HR True """ + cdef: + str abbrev try: - if freq in DEPR_ABBREVS: + if freq in c_DEPR_ABBREVS: + abbrev = c_DEPR_ABBREVS[freq] warnings.warn( f"\'{freq}\' is deprecated and will be removed in a future " - f"version. Please use \'{DEPR_ABBREVS.get(freq)}\' " + f"version. Please use \'{abbrev}\' " "instead of \'{freq}\'.", FutureWarning, stacklevel=find_stack_level(), ) - freq = DEPR_ABBREVS[freq] + freq = abbrev attr_name = _abbrev_to_attrnames[freq] except KeyError: # For quarterly and yearly resolutions, we need to chop off @@ -470,15 +459,16 @@ class Resolution(Enum): if split_freq[1] not in _month_names: # i.e. we want e.g. "Q-DEC", not "Q-INVALID" raise - if split_freq[0] in DEPR_ABBREVS: + if split_freq[0] in c_DEPR_ABBREVS: + abbrev = c_DEPR_ABBREVS[split_freq[0]] warnings.warn( f"\'{split_freq[0]}\' is deprecated and will be removed in a " - f"future version. Please use \'{DEPR_ABBREVS.get(split_freq[0])}\' " + f"future version. Please use \'{abbrev}\' " f"instead of \'{split_freq[0]}\'.", FutureWarning, stacklevel=find_stack_level(), ) - split_freq[0] = DEPR_ABBREVS[split_freq[0]] + split_freq[0] = abbrev attr_name = _abbrev_to_attrnames[split_freq[0]] return cls.from_attrname(attr_name) diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 7f3a72178a359..3d733dfed3169 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -43,13 +43,13 @@ from pandas._libs.tslibs.util cimport ( from pandas._libs.tslibs.ccalendar import ( MONTH_ALIASES, - MONTH_TO_CAL_NUM, int_to_weekday, weekday_to_int, ) from pandas.util._exceptions import find_stack_level from pandas._libs.tslibs.ccalendar cimport ( + MONTH_TO_CAL_NUM, dayofweek, get_days_in_month, get_firstbday, diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 9590d7511891f..4918de5497c4b 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -51,7 +51,7 @@ from dateutil.tz import ( from pandas._config import get_option -from pandas._libs.tslibs.ccalendar cimport c_MONTH_NUMBERS +from pandas._libs.tslibs.ccalendar cimport MONTH_TO_CAL_NUM from pandas._libs.tslibs.dtypes cimport ( attrname_to_npy_unit, npy_unit_to_attrname, @@ -623,7 +623,7 @@ cpdef quarter_to_myear(int year, int quarter, str freq): raise ValueError("Quarter must be 1 <= q <= 4") if freq is not None: - mnum = c_MONTH_NUMBERS[get_rule_month(freq)] + 1 + mnum = MONTH_TO_CAL_NUM[get_rule_month(freq)] month = (mnum + (quarter - 1) * 3) % 12 + 1 if month > mnum: year -= 1 diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index 7164de0a228d9..4489c307172d7 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -1,6 +1,5 @@ import pytest -from pandas._libs.tslibs.dtypes import _period_code_map from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG from pandas.errors import OutOfBoundsDatetime @@ -828,5 +827,3 @@ def test_asfreq_MS(self): msg = "MonthBegin is not supported as period frequency" with pytest.raises(TypeError, match=msg): Period("2013-01", "MS") - - assert _period_code_map.get("MS") is None diff --git a/pandas/tests/tseries/frequencies/test_freq_code.py b/pandas/tests/tseries/frequencies/test_freq_code.py index 96b71ef4fe662..444f49d07481c 100644 --- a/pandas/tests/tseries/frequencies/test_freq_code.py +++ b/pandas/tests/tseries/frequencies/test_freq_code.py @@ -6,7 +6,6 @@ Resolution, to_offset, ) -from pandas._libs.tslibs.dtypes import _attrname_to_abbrevs import pandas._testing as tm @@ -40,14 +39,9 @@ def test_get_to_timestamp_base(freqstr, exp_freqstr): ], ) def test_get_attrname_from_abbrev(freqstr, expected): - assert Resolution.get_reso_from_freqstr(freqstr).attrname == expected - - -@pytest.mark.parametrize("freq", ["D", "h", "min", "s", "ms", "us", "ns"]) -def test_get_freq_roundtrip2(freq): - obj = Resolution.get_reso_from_freqstr(freq) - result = _attrname_to_abbrevs[obj.attrname] - assert freq == result + reso = Resolution.get_reso_from_freqstr(freqstr) + assert reso.attr_abbrev == freqstr + assert reso.attrname == expected @pytest.mark.parametrize(
- [ ] 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/55985
2023-11-16T03:50:39Z
2023-11-16T17:11:57Z
2023-11-16T17:11:57Z
2023-11-16T17:55:24Z
Remove address violation with safe_sort
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index dd45969a13fd7..d1fa95ed63d09 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -1630,11 +1630,12 @@ def safe_sort( if use_na_sentinel: # take_nd is faster, but only works for na_sentinels of -1 order2 = sorter.argsort() - new_codes = take_nd(order2, codes, fill_value=-1) if verify: mask = (codes < -len(values)) | (codes >= len(values)) + codes[mask] = 0 else: mask = None + new_codes = take_nd(order2, codes, fill_value=-1) else: reverse_indexer = np.empty(len(sorter), dtype=int) reverse_indexer.put(sorter, np.arange(len(sorter))) diff --git a/pandas/tests/test_sorting.py b/pandas/tests/test_sorting.py index 2d21d1200acac..046a4749925d8 100644 --- a/pandas/tests/test_sorting.py +++ b/pandas/tests/test_sorting.py @@ -5,11 +5,6 @@ import numpy as np import pytest -from pandas.compat import ( - is_ci_environment, - is_platform_windows, -) - from pandas import ( NA, DataFrame, @@ -409,11 +404,6 @@ def test_codes(self, verify, codes, exp_codes): tm.assert_numpy_array_equal(result, expected) tm.assert_numpy_array_equal(result_codes, expected_codes) - @pytest.mark.skipif( - is_platform_windows() and is_ci_environment(), - reason="In CI environment can crash thread with: " - "Windows fatal exception: access violation", - ) def test_codes_out_of_bound(self): values = np.array([3, 1, 2, 0, 4]) expected = np.array([0, 1, 2, 3, 4])
flagged with asan
https://api.github.com/repos/pandas-dev/pandas/pulls/55984
2023-11-16T03:21:25Z
2023-11-16T17:13:43Z
2023-11-16T17:13:43Z
2023-11-16T17:13:50Z
ENH: dont hard-code nanoseconds in overflow exception message
diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 89b420b18a980..b123fcf9a6fd5 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -31,6 +31,7 @@ from pandas._libs.tslibs.base cimport ABCTimestamp from pandas._libs.tslibs.dtypes cimport ( abbrev_to_npy_unit, get_supported_reso, + npy_unit_to_attrname, periods_per_second, ) from pandas._libs.tslibs.np_datetime cimport ( @@ -39,6 +40,7 @@ from pandas._libs.tslibs.np_datetime cimport ( NPY_FR_us, check_dts_bounds, convert_reso, + dts_to_iso_string, get_conversion_factor, get_datetime64_unit, get_implementation_bounds, @@ -215,8 +217,9 @@ cdef int64_t get_datetime64_nanos(object val, NPY_DATETIMEUNIT reso) except? -1: try: ival = npy_datetimestruct_to_datetime(reso, &dts) except OverflowError as err: + attrname = npy_unit_to_attrname[reso] raise OutOfBoundsDatetime( - "Out of bounds nanosecond timestamp: {val}" + f"Out of bounds {attrname} timestamp: {val}" ) from err return ival @@ -249,8 +252,9 @@ cdef class _TSObject: ) except OverflowError as err: if val is not None: + attrname = npy_unit_to_attrname[creso] raise OutOfBoundsDatetime( - f"Out of bounds nanosecond timestamp: {val}" + f"Out of bounds {attrname} timestamp: {val}" ) from err raise OutOfBoundsDatetime from err @@ -420,7 +424,8 @@ cdef _TSObject convert_datetime_to_tsobject( try: obj.value = npy_datetimestruct_to_datetime(reso, &obj.dts) except OverflowError as err: - raise OutOfBoundsDatetime("Out of bounds nanosecond timestamp") from err + attrname = npy_unit_to_attrname[reso] + raise OutOfBoundsDatetime(f"Out of bounds {attrname} timestamp") from err if obj.tzinfo is not None and not is_utc(obj.tzinfo): offset = get_utcoffset(obj.tzinfo, ts) @@ -591,18 +596,18 @@ cdef check_overflows(_TSObject obj, NPY_DATETIMEUNIT reso=NPY_FR_ns): if obj.dts.year == lb.year: if not (obj.value < 0): from pandas._libs.tslibs.timestamps import Timestamp - fmt = (f"{obj.dts.year}-{obj.dts.month:02d}-{obj.dts.day:02d} " - f"{obj.dts.hour:02d}:{obj.dts.min:02d}:{obj.dts.sec:02d}") + fmt = dts_to_iso_string(&obj.dts) + min_ts = (<_Timestamp>Timestamp(0))._as_creso(reso).min raise OutOfBoundsDatetime( - f"Converting {fmt} underflows past {Timestamp.min}" + f"Converting {fmt} underflows past {min_ts}" ) elif obj.dts.year == ub.year: if not (obj.value > 0): from pandas._libs.tslibs.timestamps import Timestamp - fmt = (f"{obj.dts.year}-{obj.dts.month:02d}-{obj.dts.day:02d} " - f"{obj.dts.hour:02d}:{obj.dts.min:02d}:{obj.dts.sec:02d}") + fmt = dts_to_iso_string(&obj.dts) + max_ts = (<_Timestamp>Timestamp(0))._as_creso(reso).max raise OutOfBoundsDatetime( - f"Converting {fmt} overflows past {Timestamp.max}" + f"Converting {fmt} overflows past {max_ts}" ) # ---------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index fa9b82fe46634..491716c3a951d 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -22,6 +22,8 @@ from libc.stdint cimport INT64_MAX import_datetime() PandasDateTime_IMPORT +import operator + import numpy as np cimport numpy as cnp @@ -33,6 +35,10 @@ from numpy cimport ( uint8_t, ) +from pandas._libs.tslibs.dtypes cimport ( + npy_unit_to_abbrev, + npy_unit_to_attrname, +) from pandas._libs.tslibs.util cimport get_c_string_buf_and_size @@ -215,8 +221,8 @@ cdef check_dts_bounds(npy_datetimestruct *dts, NPY_DATETIMEUNIT unit=NPY_FR_ns): if error: fmt = dts_to_iso_string(dts) - # TODO: "nanosecond" in the message assumes NPY_FR_ns - raise OutOfBoundsDatetime(f"Out of bounds nanosecond timestamp: {fmt}") + attrname = npy_unit_to_attrname[unit] + raise OutOfBoundsDatetime(f"Out of bounds {attrname} timestamp: {fmt}") # ---------------------------------------------------------------------- @@ -259,8 +265,9 @@ cdef int64_t pydatetime_to_dt64(datetime val, try: result = npy_datetimestruct_to_datetime(reso, dts) except OverflowError as err: + attrname = npy_unit_to_attrname[reso] raise OutOfBoundsDatetime( - f"Out of bounds nanosecond timestamp: {val}" + f"Out of bounds {attrname} timestamp: {val}" ) from err return result @@ -284,7 +291,8 @@ cdef int64_t pydate_to_dt64( try: result = npy_datetimestruct_to_datetime(reso, dts) except OverflowError as err: - raise OutOfBoundsDatetime(f"Out of bounds nanosecond timestamp: {val}") from err + attrname = npy_unit_to_attrname[reso] + raise OutOfBoundsDatetime(f"Out of bounds {attrname} timestamp: {val}") from err return result @@ -423,7 +431,7 @@ cpdef ndarray astype_overflowsafe( return iresult.view(dtype) -# TODO: try to upstream this fix to numpy +# TODO(numpy#16352): try to upstream this fix to numpy def compare_mismatched_resolutions(ndarray left, ndarray right, op): """ Overflow-safe comparison of timedelta64/datetime64 with mismatched resolutions. @@ -481,9 +489,6 @@ def compare_mismatched_resolutions(ndarray left, ndarray right, op): return result -import operator - - cdef int op_to_op_code(op): if op is operator.eq: return Py_EQ @@ -536,8 +541,6 @@ cdef ndarray _astype_overflowsafe_to_smaller_unit( else: new_value, mod = divmod(value, mult) if not round_ok and mod != 0: - # TODO: avoid runtime import - from pandas._libs.tslibs.dtypes import npy_unit_to_abbrev from_abbrev = npy_unit_to_abbrev(from_unit) to_abbrev = npy_unit_to_abbrev(to_unit) raise ValueError( diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 8966c9e81699b..0e197e00800e6 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -52,6 +52,7 @@ from pandas._libs.tslibs.conversion cimport get_datetime64_nanos from pandas._libs.tslibs.dtypes cimport ( get_supported_reso, npy_unit_to_abbrev, + npy_unit_to_attrname, ) from pandas._libs.tslibs.nattype cimport ( NPY_NAT, @@ -413,8 +414,9 @@ def array_strptime( try: value = npy_datetimestruct_to_datetime(creso, &dts) except OverflowError as err: + attrname = npy_unit_to_attrname[creso] raise OutOfBoundsDatetime( - f"Out of bounds nanosecond timestamp: {val}" + f"Out of bounds {attrname} timestamp: {val}" ) from err if out_local == 1: # Store the out_tzoffset in seconds @@ -452,8 +454,9 @@ def array_strptime( try: iresult[i] = npy_datetimestruct_to_datetime(creso, &dts) except OverflowError as err: + attrname = npy_unit_to_attrname[creso] raise OutOfBoundsDatetime( - f"Out of bounds nanosecond timestamp: {val}" + f"Out of bounds {attrname} timestamp: {val}" ) from err result_timezone[i] = tz diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 56a6885d4a9e0..6ef57f630efe4 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -61,6 +61,7 @@ from pandas._libs.tslibs.conversion cimport ( ) from pandas._libs.tslibs.dtypes cimport ( npy_unit_to_abbrev, + npy_unit_to_attrname, periods_per_day, periods_per_second, ) @@ -448,15 +449,15 @@ cdef class _Timestamp(ABCTimestamp): nanos = other._value try: - new_value = self._value+ nanos + new_value = self._value + nanos result = type(self)._from_value_and_reso( new_value, reso=self._creso, tz=self.tzinfo ) except OverflowError as err: - # TODO: don't hard-code nanosecond here new_value = int(self._value) + int(nanos) + attrname = npy_unit_to_attrname[self._creso] raise OutOfBoundsDatetime( - f"Out of bounds nanosecond timestamp: {new_value}" + f"Out of bounds {attrname} timestamp: {new_value}" ) from err return result diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index b0019d2381e47..8798a8904e161 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -814,7 +814,7 @@ def test_bounds_with_different_units(self): # With more extreme cases, we can't even fit inside second resolution info = np.iinfo(np.int64) - msg = "Out of bounds nanosecond timestamp:" + msg = "Out of bounds second timestamp:" for value in [info.min + 1, info.max]: for unit in ["D", "h", "m"]: dt64 = np.datetime64(value, unit) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 3d3ca99f4d26a..ef76d99260764 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1143,7 +1143,7 @@ def test_to_datetime_dt64s_out_of_ns_bounds(self, cache, dt, errors): def test_to_datetime_dt64d_out_of_bounds(self, cache): dt64 = np.datetime64(np.iinfo(np.int64).max, "D") - msg = "Out of bounds nanosecond timestamp" + msg = "Out of bounds second timestamp: 25252734927768524-07-27" with pytest.raises(OutOfBoundsDatetime, match=msg): Timestamp(dt64) with pytest.raises(OutOfBoundsDatetime, match=msg):
- [ ] 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/55983
2023-11-16T03:09:00Z
2023-11-16T17:18:16Z
2023-11-16T17:18:16Z
2023-11-16T17:58:22Z
BUG: resolution inference with NaT ints/floats/strings
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index e8a69891c6093..f4e710a206909 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -2633,6 +2633,7 @@ def maybe_convert_objects(ndarray[object] objects, tsobj = convert_to_tsobject(val, None, None, 0, 0) tsobj.ensure_reso(NPY_FR_ns) except OutOfBoundsDatetime: + # e.g. test_out_of_s_bounds_datetime64 seen.object_ = True break else: diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index c2d2acd95ce43..0ce150786ea63 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -451,12 +451,12 @@ cpdef array_to_datetime( Returns ------- np.ndarray - May be datetime64[ns] or object dtype + May be datetime64[creso_unit] or object dtype tzinfo or None """ cdef: Py_ssize_t i, n = values.size - object val, tz + object val ndarray[int64_t] iresult npy_datetimestruct dts bint utc_convert = bool(utc) @@ -468,7 +468,7 @@ cpdef array_to_datetime( _TSObject _ts float tz_offset set out_tzoffset_vals = set() - tzinfo tz_out = None + tzinfo tz, tz_out = None cnp.flatiter it = cnp.PyArray_IterNew(values) NPY_DATETIMEUNIT item_reso bint infer_reso = creso == NPY_DATETIMEUNIT.NPY_FR_GENERIC @@ -523,15 +523,14 @@ cpdef array_to_datetime( elif is_integer_object(val) or is_float_object(val): # these must be ns unit by-definition - item_reso = NPY_FR_ns - state.update_creso(item_reso) - if infer_reso: - creso = state.creso if val != val or val == NPY_NAT: iresult[i] = NPY_NAT else: - # we now need to parse this as if unit='ns' + item_reso = NPY_FR_ns + state.update_creso(item_reso) + if infer_reso: + creso = state.creso iresult[i] = cast_from_unit(val, "ns", out_reso=creso) state.found_other = True @@ -553,6 +552,16 @@ cpdef array_to_datetime( _ts = convert_str_to_tsobject( val, None, unit="ns", dayfirst=dayfirst, yearfirst=yearfirst ) + + if _ts.value == NPY_NAT: + # e.g. "NaT" string or empty string, we do not consider + # this as either tzaware or tznaive. See + # test_to_datetime_with_empty_str_utc_false_format_mixed + # We also do not update resolution inference based on this, + # see test_infer_with_nat_int_float_str + iresult[i] = _ts.value + continue + item_reso = _ts.creso state.update_creso(item_reso) if infer_reso: @@ -563,12 +572,7 @@ cpdef array_to_datetime( iresult[i] = _ts.value tz = _ts.tzinfo - if _ts.value == NPY_NAT: - # e.g. "NaT" string or empty string, we do not consider - # this as either tzaware or tznaive. See - # test_to_datetime_with_empty_str_utc_false_format_mixed - pass - elif tz is not None: + if tz is not None: # dateutil timezone objects cannot be hashed, so # store the UTC offsets in seconds instead nsecs = tz.utcoffset(None).total_seconds() @@ -641,7 +645,7 @@ cpdef array_to_datetime( # Otherwise we can use the single reso that we encountered and avoid # a second pass. abbrev = npy_unit_to_abbrev(state.creso) - result = iresult.view(f"M8[{abbrev}]") + result = iresult.view(f"M8[{abbrev}]").reshape(result.shape) return result, tz_out diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 8966c9e81699b..4637b216ba6a6 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -240,7 +240,7 @@ cdef _get_format_regex(str fmt): cdef class DatetimeParseState: - def __cinit__(self, NPY_DATETIMEUNIT creso=NPY_DATETIMEUNIT.NPY_FR_ns): + def __cinit__(self, NPY_DATETIMEUNIT creso): # found_tz and found_naive are specifically about datetime/Timestamp # objects with and without tzinfos attached. self.found_tz = False diff --git a/pandas/tests/tslibs/test_array_to_datetime.py b/pandas/tests/tslibs/test_array_to_datetime.py index dbf81013662e7..15e34c68c4d2f 100644 --- a/pandas/tests/tslibs/test_array_to_datetime.py +++ b/pandas/tests/tslibs/test_array_to_datetime.py @@ -82,6 +82,24 @@ def test_infer_heterogeneous(self): assert tz is None tm.assert_numpy_array_equal(result, expected[::-1]) + @pytest.mark.parametrize( + "item", [float("nan"), NaT.value, float(NaT.value), "NaT", ""] + ) + def test_infer_with_nat_int_float_str(self, item): + # floats/ints get inferred to nanos *unless* they are NaN/iNaT, + # similar NaT string gets treated like NaT scalar (ignored for resolution) + dt = datetime(2023, 11, 15, 15, 5, 6) + + arr = np.array([dt, item], dtype=object) + result, tz = tslib.array_to_datetime(arr, creso=creso_infer) + assert tz is None + expected = np.array([dt, np.datetime64("NaT")], dtype="M8[us]") + tm.assert_numpy_array_equal(result, expected) + + result2, tz2 = tslib.array_to_datetime(arr[::-1], creso=creso_infer) + assert tz2 is None + tm.assert_numpy_array_equal(result2, expected[::-1]) + class TestArrayToDatetimeWithTZResolutionInference: def test_array_to_datetime_with_tz_resolution(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/55981
2023-11-16T01:19:31Z
2023-11-16T18:18:08Z
2023-11-16T18:18:08Z
2023-11-16T18:22:56Z
BUG: Index losing object dtype for pandas object and infer string
diff --git a/doc/source/whatsnew/v2.1.4.rst b/doc/source/whatsnew/v2.1.4.rst index 25afcbb3bb532..d0bc346ed2111 100644 --- a/doc/source/whatsnew/v2.1.4.rst +++ b/doc/source/whatsnew/v2.1.4.rst @@ -22,6 +22,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Bug in :class:`Series` constructor raising DeprecationWarning when ``index`` is a list of :class:`Series` (:issue:`55228`) +- Fixed bug in :class:`Index` constructor losing object dtype for :class:`Index` or :class:`Series` input when ``infer_string`` is set (:issue:`55980`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1b4e14f075f22..a51372b6f37db 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -23,6 +23,7 @@ from pandas._config import ( get_option, using_copy_on_write, + using_pyarrow_string_dtype, ) from pandas._libs import ( @@ -490,6 +491,11 @@ def __new__( if not copy and isinstance(data, (ABCSeries, Index)): refs = data._references + orig_dtype = None + if isinstance(data, (ABCSeries, Index)) and dtype is None: + # Avoid losing the dtype when infer string is set + orig_dtype = data.dtype + # range if isinstance(data, (range, RangeIndex)): result = RangeIndex(start=data, copy=copy, name=name) @@ -569,7 +575,14 @@ def __new__( klass = cls._dtype_to_subclass(arr.dtype) arr = klass._ensure_array(arr, arr.dtype, copy=False) - return klass._simple_new(arr, name, refs=refs) + result = klass._simple_new(arr, name, refs=refs) + if ( + using_pyarrow_string_dtype() + and orig_dtype == object + and result.dtype == "string" + ): + result = result.astype(orig_dtype) + return result @classmethod def _ensure_array(cls, data, dtype, copy: bool): diff --git a/pandas/tests/indexes/base_class/test_constructors.py b/pandas/tests/indexes/base_class/test_constructors.py index 60abbfc441e8e..47e9a17c01d3e 100644 --- a/pandas/tests/indexes/base_class/test_constructors.py +++ b/pandas/tests/indexes/base_class/test_constructors.py @@ -5,6 +5,7 @@ from pandas import ( Index, MultiIndex, + Series, ) import pandas._testing as tm @@ -50,10 +51,19 @@ def test_index_string_inference(self): dtype = "string[pyarrow_numpy]" expected = Index(["a", "b"], dtype=dtype) with pd.option_context("future.infer_string", True): - ser = Index(["a", "b"]) - tm.assert_index_equal(ser, expected) + idx = Index(["a", "b"]) + tm.assert_index_equal(idx, expected) expected = Index(["a", 1], dtype="object") with pd.option_context("future.infer_string", True): - ser = Index(["a", 1]) - tm.assert_index_equal(ser, expected) + idx = Index(["a", 1]) + tm.assert_index_equal(idx, expected) + + expected = Index(["a", "b"], dtype="object") + with pd.option_context("future.infer_string", True): + idx = Index(Index(["a", "b"], dtype=object)) + tm.assert_index_equal(idx, expected) + + with pd.option_context("future.infer_string", True): + idx = Index(Series(["a", "b"], dtype=object)) + tm.assert_index_equal(idx, 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/55980
2023-11-16T01:03:20Z
2023-12-08T21:44:59Z
null
2023-12-08T21:45:03Z
BUG: dt64 astype silent overflows
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 48aee18c90456..90534174a739d 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -347,6 +347,7 @@ Datetimelike - Bug in :meth:`Index.is_monotonic_increasing` and :meth:`Index.is_monotonic_decreasing` always caching :meth:`Index.is_unique` as ``True`` when first value in index is ``NaT`` (:issue:`55755`) - Bug in :meth:`Index.view` to a datetime64 dtype with non-supported resolution incorrectly raising (:issue:`55710`) - Bug in :meth:`Tick.delta` with very large ticks raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`) +- Bug in ``.astype`` converting from a higher-resolution ``datetime64`` dtype to a lower-resolution ``datetime64`` dtype (e.g. ``datetime64[us]->datetim64[ms]``) silently overflowing with values near the lower implementation bound (:issue:`55979`) - Bug in adding or subtracting a :class:`Week` offset to a ``datetime64`` :class:`Series`, :class:`Index`, or :class:`DataFrame` column with non-nanosecond resolution returning incorrect results (:issue:`55583`) - Bug in addition or subtraction of :class:`BusinessDay` offset with ``offset`` attribute to non-nanosecond :class:`Index`, :class:`Series`, or :class:`DataFrame` column giving incorrect results (:issue:`55608`) - Bug in addition or subtraction of :class:`DateOffset` objects with microsecond components to ``datetime64`` :class:`Index`, :class:`Series`, or :class:`DataFrame` columns with non-nanosecond resolution (:issue:`55595`) diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 4f14782d9efbb..89b420b18a980 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -716,7 +716,7 @@ cdef int64_t parse_pydatetime( result = _ts.value else: if isinstance(val, _Timestamp): - result = (<_Timestamp>val)._as_creso(creso, round_ok=False)._value + result = (<_Timestamp>val)._as_creso(creso, round_ok=True)._value else: result = pydatetime_to_dt64(val, dts, reso=creso) return result diff --git a/pandas/_libs/tslibs/np_datetime.pyx b/pandas/_libs/tslibs/np_datetime.pyx index 71a194177bf82..fa9b82fe46634 100644 --- a/pandas/_libs/tslibs/np_datetime.pyx +++ b/pandas/_libs/tslibs/np_datetime.pyx @@ -365,13 +365,10 @@ cpdef ndarray astype_overflowsafe( return values elif from_unit > to_unit: - if round_ok: - # e.g. ns -> us, so there is no risk of overflow, so we can use - # numpy's astype safely. Note there _is_ risk of truncation. - return values.astype(dtype) - else: - iresult2 = astype_round_check(values.view("i8"), from_unit, to_unit) - return iresult2.view(dtype) + iresult2 = _astype_overflowsafe_to_smaller_unit( + values.view("i8"), from_unit, to_unit, round_ok=round_ok + ) + return iresult2.view(dtype) if (<object>values).dtype.byteorder == ">": # GH#29684 we incorrectly get OutOfBoundsDatetime if we dont swap @@ -502,13 +499,20 @@ cdef int op_to_op_code(op): return Py_GT -cdef ndarray astype_round_check( +cdef ndarray _astype_overflowsafe_to_smaller_unit( ndarray i8values, NPY_DATETIMEUNIT from_unit, - NPY_DATETIMEUNIT to_unit + NPY_DATETIMEUNIT to_unit, + bint round_ok, ): - # cases with from_unit > to_unit, e.g. ns->us, raise if the conversion - # involves truncation, e.g. 1500ns->1us + """ + Overflow-safe conversion for cases with from_unit > to_unit, e.g. ns->us. + In addition for checking for overflows (which can occur near the lower + implementation bound, see numpy#22346), this checks for truncation, + e.g. 1500ns->1us. + """ + # e.g. test_astype_ns_to_ms_near_bounds is a case with round_ok=True where + # just using numpy's astype silently fails cdef: Py_ssize_t i, N = i8values.size @@ -531,7 +535,7 @@ cdef ndarray astype_round_check( new_value = NPY_DATETIME_NAT else: new_value, mod = divmod(value, mult) - if mod != 0: + if not round_ok and mod != 0: # TODO: avoid runtime import from pandas._libs.tslibs.dtypes import npy_unit_to_abbrev from_abbrev = npy_unit_to_abbrev(from_unit) diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 566117899cfc5..770f19d9f13ce 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -309,6 +309,22 @@ def test_cmp_dt64_arraylike_tznaive(self, comparison_op): class TestDatetimeArray: + def test_astype_ns_to_ms_near_bounds(self): + # GH#55979 + ts = pd.Timestamp("1677-09-21 00:12:43.145225") + target = ts.as_unit("ms") + + dta = DatetimeArray._from_sequence([ts], dtype="M8[ns]") + assert (dta.view("i8") == ts.as_unit("ns").value).all() + + result = dta.astype("M8[ms]") + assert result[0] == target + + expected = DatetimeArray._from_sequence([ts], dtype="M8[ms]") + assert (expected.view("i8") == target._value).all() + + tm.assert_datetime_array_equal(result, expected) + def test_astype_non_nano_tznaive(self): dti = pd.date_range("2016-01-01", periods=3)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] 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. Surfaced while implementing #55564
https://api.github.com/repos/pandas-dev/pandas/pulls/55979
2023-11-15T23:25:16Z
2023-11-16T02:13:24Z
2023-11-16T02:13:24Z
2023-11-16T02:15:34Z
DEPR: rename BQ to BQE for offsets
diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index 6731b70fc3860..22e3921bbf06b 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -886,7 +886,7 @@ into ``freq`` keyword arguments. The available date offsets and associated frequ :class:`~pandas.tseries.offsets.SemiMonthBegin`, ``'SMS'``, "15th (or other day_of_month) and calendar month begin" :class:`~pandas.tseries.offsets.QuarterEnd`, ``'QE'``, "calendar quarter end" :class:`~pandas.tseries.offsets.QuarterBegin`, ``'QS'``, "calendar quarter begin" - :class:`~pandas.tseries.offsets.BQuarterEnd`, ``'BQ``, "business quarter end" + :class:`~pandas.tseries.offsets.BQuarterEnd`, ``'BQE``, "business quarter end" :class:`~pandas.tseries.offsets.BQuarterBegin`, ``'BQS'``, "business quarter begin" :class:`~pandas.tseries.offsets.FY5253Quarter`, ``'REQ'``, "retail (aka 52-53 week) quarter" :class:`~pandas.tseries.offsets.YearEnd`, ``'YE'``, "calendar year end" @@ -1249,7 +1249,7 @@ frequencies. We will refer to these aliases as *offset aliases*. "BMS", "business month start frequency" "CBMS", "custom business month start frequency" "QE", "quarter end frequency" - "BQ", "business quarter end frequency" + "BQE", "business quarter end frequency" "QS", "quarter start frequency" "BQS", "business quarter start frequency" "YE", "year end frequency" @@ -1686,7 +1686,7 @@ the end of the interval. .. warning:: The default values for ``label`` and ``closed`` is '**left**' for all - frequency offsets except for 'ME', 'YE', 'QE', 'BME', 'BY', 'BQ', and 'W' + frequency offsets except for 'ME', 'YE', 'QE', 'BME', 'BY', 'BQE', and 'W' which all have a default of 'right'. This might unintendedly lead to looking ahead, where the value for a later diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 9040dba238c88..cea4e82cf9c5c 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -287,6 +287,7 @@ Other Deprecations - Deprecated string ``A`` denoting frequency in :class:`YearEnd` and strings ``A-DEC``, ``A-JAN``, etc. denoting annual frequencies with various fiscal year ends (:issue:`54275`) - Deprecated string ``BAS`` denoting frequency in :class:`BYearBegin` and strings ``BAS-DEC``, ``BAS-JAN``, etc. denoting annual frequencies with various fiscal year starts (:issue:`54275`) - Deprecated string ``BA`` denoting frequency in :class:`BYearEnd` and strings ``BA-DEC``, ``BA-JAN``, etc. denoting annual frequencies with various fiscal year ends (:issue:`54275`) +- Deprecated string ``BQ`` denoting frequency in :class:`BQuarterEnd` (:issue:`52064`) - Deprecated strings ``BM``, and ``CBM`` denoting frequencies in :class:`BusinessMonthEnd`, :class:`CustomBusinessMonthEnd` (:issue:`52064`) - Deprecated strings ``H``, ``BH``, and ``CBH`` denoting frequencies in :class:`Hour`, :class:`BusinessHour`, :class:`CustomBusinessHour` (:issue:`52536`) - Deprecated strings ``H``, ``S``, ``U``, and ``N`` denoting units in :func:`to_timedelta` (:issue:`52536`) diff --git a/pandas/_libs/tslibs/dtypes.pyx b/pandas/_libs/tslibs/dtypes.pyx index a8dc6b12a54b5..73ae704167537 100644 --- a/pandas/_libs/tslibs/dtypes.pyx +++ b/pandas/_libs/tslibs/dtypes.pyx @@ -191,7 +191,19 @@ OFFSET_TO_PERIOD_FREQSTR: dict = { "BME": "M", "BQS": "Q", "QS": "Q", - "BQ": "Q", + "BQE": "Q", + "BQE-DEC": "Q-DEC", + "BQE-JAN": "Q-JAN", + "BQE-FEB": "Q-FEB", + "BQE-MAR": "Q-MAR", + "BQE-APR": "Q-APR", + "BQE-MAY": "Q-MAY", + "BQE-JUN": "Q-JUN", + "BQE-JUL": "Q-JUL", + "BQE-AUG": "Q-AUG", + "BQE-SEP": "Q-SEP", + "BQE-OCT": "Q-OCT", + "BQE-NOV": "Q-NOV", "MS": "M", "D": "D", "B": "B", @@ -275,6 +287,21 @@ OFFSET_DEPR_FREQSTR: dict[str, str]= { "A-SEP": "YE-SEP", "A-OCT": "YE-OCT", "A-NOV": "YE-NOV", + "BM": "BME", + "CBM": "CBME", + "BQ": "BQE", + "BQ-DEC": "BQE-DEC", + "BQ-JAN": "BQE-JAN", + "BQ-FEB": "BQE-FEB", + "BQ-MAR": "BQE-MAR", + "BQ-APR": "BQE-APR", + "BQ-MAY": "BQE-MAY", + "BQ-JUN": "BQE-JUN", + "BQ-JUL": "BQE-JUL", + "BQ-AUG": "BQE-AUG", + "BQ-SEP": "BQE-SEP", + "BQ-OCT": "BQE-OCT", + "BQ-NOV": "BQE-NOV", } cdef dict c_OFFSET_TO_PERIOD_FREQSTR = OFFSET_TO_PERIOD_FREQSTR cdef dict c_OFFSET_DEPR_FREQSTR = OFFSET_DEPR_FREQSTR diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 7f3a72178a359..773e9e53b60da 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -2693,7 +2693,7 @@ cdef class BQuarterEnd(QuarterOffset): _output_name = "BusinessQuarterEnd" _default_starting_month = 3 _from_name_starting_month = 12 - _prefix = "BQ" + _prefix = "BQE" _day_opt = "business_end" @@ -4568,7 +4568,7 @@ prefix_mapping = { BusinessDay, # 'B' BusinessMonthBegin, # 'BMS' BusinessMonthEnd, # 'BME' - BQuarterEnd, # 'BQ' + BQuarterEnd, # 'BQE' BQuarterBegin, # 'BQS' BusinessHour, # 'bh' CustomBusinessDay, # 'C' @@ -4752,7 +4752,7 @@ cpdef to_offset(freq, bint is_period=False): for n, (sep, stride, name) in enumerate(tups): if is_period is False and name in c_OFFSET_DEPR_FREQSTR: warnings.warn( - f"\'{name}\' will be deprecated, please use " + f"\'{name}\' is deprecated, please use " f"\'{c_OFFSET_DEPR_FREQSTR.get(name)}\' instead.", FutureWarning, stacklevel=find_stack_level(), diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 7918e43b48719..1674960f21b19 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9200,11 +9200,11 @@ def resample( closed : {{'right', 'left'}}, default None Which side of bin interval is closed. The default is 'left' for all frequency offsets except for 'ME', 'YE', 'QE', 'BME', - 'BA', 'BQ', and 'W' which all have a default of 'right'. + 'BA', 'BQE', and 'W' which all have a default of 'right'. label : {{'right', 'left'}}, default None Which bin edge label to label bucket with. The default is 'left' for all frequency offsets except for 'ME', 'YE', 'QE', 'BME', - 'BA', 'BQ', and 'W' which all have a default of 'right'. + 'BA', 'BQE', and 'W' which all have a default of 'right'. convention : {{'start', 'end', 's', 'e'}}, default 'start' For `PeriodIndex` only, controls whether to use the start or end of `rule`. diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 14cd77ec8559b..6a95457526b5a 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -2130,7 +2130,7 @@ def __init__( else: freq = to_offset(freq) - end_types = {"ME", "YE", "QE", "BME", "BY", "BQ", "W"} + end_types = {"ME", "YE", "QE", "BME", "BY", "BQE", "W"} rule = freq.rule_code if rule in end_types or ("-" in rule and rule[: rule.find("-")] in end_types): if closed is None: @@ -2327,7 +2327,7 @@ def _adjust_bin_edges( # Some hacks for > daily data, see #1471, #1458, #1483 if self.freq.name in ("BME", "ME", "W") or self.freq.name.split("-")[0] in ( - "BQ", + "BQE", "BY", "QE", "YE", diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 566117899cfc5..3fe53db1b714c 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -756,9 +756,7 @@ def test_iter_zoneinfo_fold(self, tz): ) def test_date_range_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr): # GH#9586, GH#54275 - depr_msg = ( - f"'{freq_depr[1:]}' will be deprecated, please use '{freq[1:]}' instead." - ) + depr_msg = f"'{freq_depr[1:]}' is deprecated, please use '{freq[1:]}' instead." expected = pd.date_range("1/1/2000", periods=4, freq=freq) with tm.assert_produces_warning(FutureWarning, match=depr_msg): diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py index 616ad5133e778..13ba002f2cdc8 100644 --- a/pandas/tests/frame/methods/test_asfreq.py +++ b/pandas/tests/frame/methods/test_asfreq.py @@ -240,6 +240,8 @@ def test_asfreq_2ME(self, freq, freq_half): ("2ME", "2M"), ("2QE", "2Q"), ("2QE-SEP", "2Q-SEP"), + ("1BQE", "1BQ"), + ("2BQE-SEP", "2BQ-SEP"), ("1YE", "1Y"), ("2YE-MAR", "2Y-MAR"), ("1YE", "1A"), @@ -247,10 +249,8 @@ def test_asfreq_2ME(self, freq, freq_half): ], ) def test_asfreq_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr): - # GH#9586 - depr_msg = ( - f"'{freq_depr[1:]}' will be deprecated, please use '{freq[1:]}' instead." - ) + # GH#9586, #55978 + depr_msg = f"'{freq_depr[1:]}' is deprecated, please use '{freq[1:]}' instead." index = date_range("1/1/2000", periods=4, freq=f"{freq[1:]}") df = DataFrame({"s": Series([0.0, 1.0, 2.0, 3.0], index=index)}) diff --git a/pandas/tests/indexes/datetimes/methods/test_to_period.py b/pandas/tests/indexes/datetimes/methods/test_to_period.py index af04f827d4593..206524e77c2a5 100644 --- a/pandas/tests/indexes/datetimes/methods/test_to_period.py +++ b/pandas/tests/indexes/datetimes/methods/test_to_period.py @@ -50,7 +50,7 @@ def test_to_period_quarterly(self, month): result = stamps.to_period(freq) tm.assert_index_equal(rng, result) - @pytest.mark.parametrize("off", ["BQ", "QS", "BQS"]) + @pytest.mark.parametrize("off", ["BQE", "QS", "BQS"]) def test_to_period_quarterlyish(self, off): rng = date_range("01-Jan-2012", periods=8, freq=off) prng = rng.to_period() @@ -103,7 +103,7 @@ def test_dti_to_period_2monthish(self, freq_offset, freq_period): ) def test_to_period_frequency_M_Q_Y_A_deprecated(self, freq, freq_depr): # GH#9586 - msg = f"'{freq_depr[1:]}' will be deprecated, please use '{freq[1:]}' instead." + msg = f"'{freq_depr[1:]}' is deprecated, please use '{freq[1:]}' instead." rng = date_range("01-Jan-2012", periods=8, freq=freq) prng = rng.to_period() diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 3a6d1cacd0f81..cacf232c9b6d1 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -146,7 +146,7 @@ def test_date_range_float_periods(self): tm.assert_index_equal(rng, exp) def test_date_range_frequency_M_deprecated(self): - depr_msg = "'M' will be deprecated, please use 'ME' instead." + depr_msg = "'M' is deprecated, please use 'ME' instead." expected = date_range("1/1/2000", periods=4, freq="2ME") with tm.assert_produces_warning(FutureWarning, match=depr_msg): @@ -786,7 +786,7 @@ def test_frequencies_A_deprecated_Y_renamed(self, freq, freq_depr): # GH#9586, GH#54275 freq_msg = re.split("[0-9]*", freq, maxsplit=1)[1] freq_depr_msg = re.split("[0-9]*", freq_depr, maxsplit=1)[1] - msg = f"'{freq_depr_msg}' will be deprecated, please use '{freq_msg}' instead." + msg = f"'{freq_depr_msg}' is deprecated, please use '{freq_msg}' instead." expected = date_range("1/1/2000", periods=2, freq=freq) with tm.assert_produces_warning(FutureWarning, match=msg): @@ -1645,7 +1645,7 @@ def test_date_range_fy5253(self, unit): "freqstr,offset", [ ("QS", offsets.QuarterBegin(startingMonth=1)), - ("BQ", offsets.BQuarterEnd(startingMonth=12)), + ("BQE", offsets.BQuarterEnd(startingMonth=12)), ("W-SUN", offsets.Week(weekday=6)), ], ) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index a1074a1744c7a..3c37aee3c3309 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -201,16 +201,24 @@ def test_AS_BA_BAS_deprecated(self, freq_depr, expected_values, expected_freq): tm.assert_index_equal(result, expected) - def test_BM_deprecated(self): + @pytest.mark.parametrize( + "freq, expected_values, freq_depr", + [ + ("2BME", ["2016-02-29", "2016-04-29", "2016-06-30"], "2BM"), + ("2BQE", ["2016-03-31"], "2BQ"), + ("1BQE-MAR", ["2016-03-31", "2016-06-30"], "1BQ-MAR"), + ], + ) + def test_BM_BQ_deprecated(self, freq, expected_values, freq_depr): # GH#52064 - msg = "'BM' is deprecated and will be removed in a future version." + msg = f"'{freq_depr[1:]}' is deprecated, please use '{freq[1:]}' instead." with tm.assert_produces_warning(FutureWarning, match=msg): - expected = date_range(start="2016-02-21", end="2016-08-21", freq="2BM") + expected = date_range(start="2016-02-21", end="2016-08-21", freq=freq_depr) result = DatetimeIndex( - ["2016-02-29", "2016-04-29", "2016-06-30"], + data=expected_values, dtype="datetime64[ns]", - freq="2BME", + freq=freq, ) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 6fbfe27acc0e0..c361c15c79758 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -308,7 +308,7 @@ def test_dti_fields(self, tz): tm.assert_index_equal(res, exp) def test_dti_is_year_quarter_start(self): - dti = date_range(freq="BQ-FEB", start=datetime(1998, 1, 1), periods=4) + dti = date_range(freq="BQE-FEB", start=datetime(1998, 1, 1), periods=4) assert sum(dti.is_quarter_start) == 0 assert sum(dti.is_quarter_end) == 4 diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 6965aaf19f8fb..6411abe00a75a 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -299,7 +299,7 @@ def test_a_deprecated_from_time_series(self, freq_depr): series = Series(1, index=index) assert isinstance(series, Series) - @pytest.mark.parametrize("freq_depr", ["2ME", "2QE", "2YE"]) + @pytest.mark.parametrize("freq_depr", ["2ME", "2QE", "2BQE", "2YE"]) def test_period_index_frequency_error_message(self, freq_depr): # GH#9586 msg = f"for Period, please use '{freq_depr[1:-1]}' " diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 9cf4e68a9c5ec..54d2fa0f50346 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -2058,7 +2058,7 @@ def test_resample_empty_series_with_tz(): ) def test_resample_M_Q_Y_A_deprecated(freq, freq_depr): # GH#9586 - depr_msg = f"'{freq_depr[1:]}' will be deprecated, please use '{freq[1:]}' instead." + depr_msg = f"'{freq_depr[1:]}' is deprecated, please use '{freq[1:]}' instead." s = Series(range(10), index=date_range("20130101", freq="d", periods=10)) expected = s.resample(freq).mean() @@ -2067,14 +2067,22 @@ def test_resample_M_Q_Y_A_deprecated(freq, freq_depr): tm.assert_series_equal(result, expected) -def test_resample_BM_deprecated(): +@pytest.mark.parametrize( + "freq, freq_depr", + [ + ("2BME", "2BM"), + ("2BQE", "2BQ"), + ("2BQE-MAR", "2BQ-MAR"), + ], +) +def test_resample_BM_BQ_deprecated(freq, freq_depr): # GH#52064 - depr_msg = "'BM' is deprecated and will be removed in a future version." + depr_msg = f"'{freq_depr[1:]}' is deprecated, please use '{freq[1:]}' instead." s = Series(range(10), index=date_range("20130101", freq="d", periods=10)) - expected = s.resample("2BME").mean() + expected = s.resample(freq).mean() with tm.assert_produces_warning(FutureWarning, match=depr_msg): - result = s.resample("2BM").mean() + result = s.resample(freq_depr).mean() tm.assert_series_equal(result, expected) diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index f3a7c94fc9eaa..3c5253a36c04b 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -924,10 +924,13 @@ def test_resample_t_l_deprecated(self): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("freq_depr", ["2ME", "2QE", "2QE-FEB", "2YE", "2YE-MAR"]) +@pytest.mark.parametrize( + "freq_depr", ["2ME", "2QE", "2QE-FEB", "2BQE", "2BQE-FEB", "2YE", "2YE-MAR"] +) def test_resample_frequency_ME_QE_error_message(series_and_frame, freq_depr): # GH#9586 - msg = f"for Period, please use '{freq_depr[1:2]}{freq_depr[3:]}' " + pos_e = freq_depr.index("E") + msg = f"for Period, please use '{freq_depr[1:pos_e]}{freq_depr[pos_e+1:]}' " f"instead of '{freq_depr[1:]}'" obj = series_and_frame diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 6d5b762b4f15a..f360d2d239384 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -838,7 +838,7 @@ def test_rule_code(self): "NOV", "DEC", ] - base_lst = ["YE", "YS", "BY", "BYS", "QE", "QS", "BQ", "BQS"] + base_lst = ["YE", "YS", "BY", "BYS", "QE", "QS", "BQE", "BQS"] for base in base_lst: for v in suffix_lst: alias = "-".join([base, v]) @@ -857,7 +857,7 @@ def test_freq_offsets(): class TestReprNames: def test_str_for_named_is_name(self): # look at all the amazing combinations! - month_prefixes = ["YE", "YS", "BY", "BYS", "QE", "BQ", "BQS", "QS"] + month_prefixes = ["YE", "YS", "BY", "BYS", "QE", "BQE", "BQS", "QS"] names = [ prefix + "-" + month for prefix in month_prefixes @@ -1122,7 +1122,7 @@ def test_is_yqm_start_end(): bm = to_offset("BME") qfeb = to_offset("QE-FEB") qsfeb = to_offset("QS-FEB") - bq = to_offset("BQ") + bq = to_offset("BQE") bqs_apr = to_offset("BQS-APR") as_nov = to_offset("YS-NOV") diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 8460ef5826e34..d6ed3b1e90642 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -59,7 +59,7 @@ # -------------------------------------------------------------------- # Offset related functions -_need_suffix = ["QS", "BQ", "BQS", "YS", "BY", "BYS"] +_need_suffix = ["QS", "BQE", "BQS", "YS", "BY", "BYS"] for _prefix in _need_suffix: for _m in MONTHS: @@ -359,7 +359,7 @@ def _get_quarterly_rule(self) -> str | None: if pos_check is None: return None else: - return {"cs": "QS", "bs": "BQS", "ce": "QE", "be": "BQ"}.get(pos_check) + return {"cs": "QS", "bs": "BQS", "ce": "QE", "be": "BQE"}.get(pos_check) def _get_monthly_rule(self) -> str | None: if len(self.mdiffs) > 1:
xref #55553, #55496, #52064 Deprecated the alias denoting business quarter end frequency `'BQ'` for offsets in favour of `'BQE'`. Renamed strings 'BQ-DEC', 'BQ-JAN', etc. denoting business quarterly frequencies with various fiscal quarter ends to 'BQE-DEC', 'BQE-JAN', etc.
https://api.github.com/repos/pandas-dev/pandas/pulls/55978
2023-11-15T22:53:19Z
2023-11-17T09:44:55Z
2023-11-17T09:44:55Z
2023-11-17T10:51:21Z
Use NumPy macros for overflow detection
diff --git a/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c b/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c index 01e11e5138a8e..f6efae77c5c01 100644 --- a/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c +++ b/pandas/_libs/src/vendored/numpy/datetime/np_datetime.c @@ -40,15 +40,9 @@ This file is derived from NumPy 1.7. See NUMPY_LICENSE.txt #else #if defined __has_builtin #if __has_builtin(__builtin_add_overflow) -#if _LP64 || __LP64__ || _ILP64 || __ILP64__ -#define checked_int64_add(a, b, res) __builtin_saddl_overflow(a, b, res) -#define checked_int64_sub(a, b, res) __builtin_ssubl_overflow(a, b, res) -#define checked_int64_mul(a, b, res) __builtin_smull_overflow(a, b, res) -#else -#define checked_int64_add(a, b, res) __builtin_saddll_overflow(a, b, res) -#define checked_int64_sub(a, b, res) __builtin_ssubll_overflow(a, b, res) -#define checked_int64_mul(a, b, res) __builtin_smulll_overflow(a, b, res) -#endif +#define checked_int64_add(a, b, res) __builtin_add_overflow(a, b, res) +#define checked_int64_sub(a, b, res) __builtin_sub_overflow(a, b, res) +#define checked_int64_mul(a, b, res) __builtin_mul_overflow(a, b, res) #else _Static_assert(0, "Overflow checking not detected; please try a newer compiler"); @@ -56,15 +50,9 @@ _Static_assert(0, // __has_builtin was added in gcc 10, but our muslinux_1_1 build environment // only has gcc-9.3, so fall back to __GNUC__ macro as long as we have that #elif __GNUC__ > 7 -#if _LP64 || __LP64__ || _ILP64 || __ILP64__ -#define checked_int64_add(a, b, res) __builtin_saddl_overflow(a, b, res) -#define checked_int64_sub(a, b, res) __builtin_ssubl_overflow(a, b, res) -#define checked_int64_mul(a, b, res) __builtin_smull_overflow(a, b, res) -#else -#define checked_int64_add(a, b, res) __builtin_saddll_overflow(a, b, res) -#define checked_int64_sub(a, b, res) __builtin_ssubll_overflow(a, b, res) -#define checked_int64_mul(a, b, res) __builtin_smulll_overflow(a, b, res) -#endif +#define checked_int64_add(a, b, res) __builtin_add_overflow(a, b, res) +#define checked_int64_sub(a, b, res) __builtin_sub_overflow(a, b, res) +#define checked_int64_mul(a, b, res) __builtin_mul_overflow(a, b, res) #else _Static_assert(0, "__has_builtin not detected; please try a newer compiler"); #endif
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55977
2023-11-15T22:03:15Z
2023-11-17T17:39:32Z
2023-11-17T17:39:32Z
2023-11-17T17:39:40Z
REF: lreshape, wide_to_long
diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index e333d263a6b7a..bb1cd0d738dac 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -12,7 +12,6 @@ from pandas.core.dtypes.missing import notna import pandas.core.algorithms as algos -from pandas.core.arrays import Categorical from pandas.core.indexes.api import MultiIndex from pandas.core.reshape.concat import concat from pandas.core.reshape.util import tile_compat @@ -139,7 +138,7 @@ def melt( return result -def lreshape(data: DataFrame, groups, dropna: bool = True) -> DataFrame: +def lreshape(data: DataFrame, groups: dict, dropna: bool = True) -> DataFrame: """ Reshape wide-format data to long. Generalized inverse of DataFrame.pivot. @@ -192,30 +191,20 @@ def lreshape(data: DataFrame, groups, dropna: bool = True) -> DataFrame: 2 Red Sox 2008 545 3 Yankees 2008 526 """ - if isinstance(groups, dict): - keys = list(groups.keys()) - values = list(groups.values()) - else: - keys, values = zip(*groups) - - all_cols = list(set.union(*(set(x) for x in values))) - id_cols = list(data.columns.difference(all_cols)) - - K = len(values[0]) - - for seq in values: - if len(seq) != K: - raise ValueError("All column lists must be same length") - mdata = {} pivot_cols = [] - - for target, names in zip(keys, values): + all_cols: set[Hashable] = set() + K = len(next(iter(groups.values()))) + for target, names in groups.items(): + if len(names) != K: + raise ValueError("All column lists must be same length") to_concat = [data[col]._values for col in names] mdata[target] = concat_compat(to_concat) pivot_cols.append(target) + all_cols = all_cols.union(names) + id_cols = list(data.columns.difference(all_cols)) for col in id_cols: mdata[col] = np.tile(data[col]._values, K) @@ -467,10 +456,10 @@ def wide_to_long( two 2.9 """ - def get_var_names(df, stub: str, sep: str, suffix: str) -> list[str]: + def get_var_names(df, stub: str, sep: str, suffix: str): regex = rf"^{re.escape(stub)}{re.escape(sep)}{suffix}$" pattern = re.compile(regex) - return [col for col in df.columns if pattern.match(col)] + return df.columns[df.columns.str.match(pattern)] def melt_stub(df, stub: str, i, j, value_vars, sep: str): newdf = melt( @@ -480,7 +469,6 @@ def melt_stub(df, stub: str, i, j, value_vars, sep: str): value_name=stub.rstrip(sep), var_name=j, ) - newdf[j] = Categorical(newdf[j]) newdf[j] = newdf[j].str.replace(re.escape(stub + sep), "", regex=True) # GH17627 Cast numerics suffixes to int/float @@ -497,7 +485,7 @@ def melt_stub(df, stub: str, i, j, value_vars, sep: str): else: stubnames = list(stubnames) - if any(col in stubnames for col in df.columns): + if df.columns.isin(stubnames).any(): raise ValueError("stubname can't be identical to a column name") if not is_list_like(i): @@ -508,18 +496,18 @@ def melt_stub(df, stub: str, i, j, value_vars, sep: str): if df[i].duplicated().any(): raise ValueError("the id variables need to uniquely identify each row") - value_vars = [get_var_names(df, stub, sep, suffix) for stub in stubnames] - - value_vars_flattened = [e for sublist in value_vars for e in sublist] - id_vars = list(set(df.columns.tolist()).difference(value_vars_flattened)) + _melted = [] + value_vars_flattened = [] + for stub in stubnames: + value_var = get_var_names(df, stub, sep, suffix) + value_vars_flattened.extend(value_var) + _melted.append(melt_stub(df, stub, i, j, value_var, sep)) - _melted = [melt_stub(df, s, i, j, v, sep) for s, v in zip(stubnames, value_vars)] - melted = _melted[0].join(_melted[1:], how="outer") + melted = concat(_melted, axis=1) + id_vars = df.columns.difference(value_vars_flattened) + new = df[id_vars] if len(i) == 1: - new = df[id_vars].set_index(i).join(melted) - return new - - new = df[id_vars].merge(melted.reset_index(), on=i).set_index(i + [j]) - - return new + return new.set_index(i).join(melted) + else: + return new.merge(melted.reset_index(), on=i).set_index(i + [j])
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55976
2023-11-15T19:07:17Z
2023-11-20T17:54:01Z
2023-11-20T17:54:01Z
2023-12-08T12:55:01Z
TST: parametrize over dt64 unit
diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 5a5abcc4aa85d..5996d8797d143 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -853,10 +853,14 @@ def test_concat_same_type_invalid(self, arr1d): with pytest.raises(ValueError, match="to_concat must have the same"): arr._concat_same_type([arr, other]) - def test_concat_same_type_different_freq(self): + def test_concat_same_type_different_freq(self, unit): # we *can* concatenate DTI with different freqs. - a = DatetimeArray(pd.date_range("2000", periods=2, freq="D", tz="US/Central")) - b = DatetimeArray(pd.date_range("2000", periods=2, freq="h", tz="US/Central")) + a = DatetimeArray( + pd.date_range("2000", periods=2, freq="D", tz="US/Central", unit=unit) + ) + b = DatetimeArray( + pd.date_range("2000", periods=2, freq="h", tz="US/Central", unit=unit) + ) result = DatetimeArray._concat_same_type([a, b]) expected = DatetimeArray( pd.to_datetime( @@ -866,7 +870,9 @@ def test_concat_same_type_different_freq(self): "2000-01-01 00:00:00", "2000-01-01 01:00:00", ] - ).tz_localize("US/Central") + ) + .tz_localize("US/Central") + .as_unit(unit) ) tm.assert_datetime_array_equal(result, expected) diff --git a/pandas/tests/groupby/methods/test_nth.py b/pandas/tests/groupby/methods/test_nth.py index b21060e7f1247..e3005c9b971ec 100644 --- a/pandas/tests/groupby/methods/test_nth.py +++ b/pandas/tests/groupby/methods/test_nth.py @@ -286,8 +286,10 @@ def test_nth5(): tm.assert_frame_equal(gb.nth([3, 4]), df.loc[[]]) -def test_nth_bdays(): - business_dates = pd.date_range(start="4/1/2014", end="6/30/2014", freq="B") +def test_nth_bdays(unit): + business_dates = pd.date_range( + start="4/1/2014", end="6/30/2014", freq="B", unit=unit + ) df = DataFrame(1, index=business_dates, columns=["a", "b"]) # get the first, fourth and last two business days for each month key = [df.index.year, df.index.month] @@ -307,7 +309,7 @@ def test_nth_bdays(): "2014/6/27", "2014/6/30", ] - ) + ).as_unit(unit) expected = DataFrame(1, columns=["a", "b"], index=expected_dates) tm.assert_frame_equal(result, expected) @@ -401,14 +403,15 @@ def test_first_last_tz(data, expected_first, expected_last): ["last", Timestamp("2013-01-02", tz="US/Eastern"), "b"], ], ) -def test_first_last_tz_multi_column(method, ts, alpha): +def test_first_last_tz_multi_column(method, ts, alpha, unit): # GH 21603 category_string = Series(list("abc")).astype("category") + dti = pd.date_range("20130101", periods=3, tz="US/Eastern", unit=unit) df = DataFrame( { "group": [1, 1, 2], "category_string": category_string, - "datetimetz": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "datetimetz": dti, } ) result = getattr(df.groupby("group"), method)() @@ -421,6 +424,7 @@ def test_first_last_tz_multi_column(method, ts, alpha): }, index=Index([1, 2], name="group"), ) + expected["datetimetz"] = expected["datetimetz"].dt.as_unit(unit) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/methods/test_quantile.py b/pandas/tests/groupby/methods/test_quantile.py index fcb9701e9881b..d949e5e36fa81 100644 --- a/pandas/tests/groupby/methods/test_quantile.py +++ b/pandas/tests/groupby/methods/test_quantile.py @@ -415,13 +415,14 @@ def test_columns_groupby_quantile(): tm.assert_frame_equal(result, expected) -def test_timestamp_groupby_quantile(): +def test_timestamp_groupby_quantile(unit): # GH 33168 + dti = pd.date_range( + start="2020-04-19 00:00:00", freq="1min", periods=100, tz="UTC", unit=unit + ).floor("1h") df = DataFrame( { - "timestamp": pd.date_range( - start="2020-04-19 00:00:00", freq="1min", periods=100, tz="UTC" - ).floor("1h"), + "timestamp": dti, "category": list(range(1, 101)), "value": list(range(101, 201)), } @@ -429,6 +430,7 @@ def test_timestamp_groupby_quantile(): result = df.groupby("timestamp").quantile([0.2, 0.8]) + mi = pd.MultiIndex.from_product([dti[::99], [0.2, 0.8]], names=("timestamp", None)) expected = DataFrame( [ {"category": 12.8, "value": 112.8}, @@ -436,15 +438,7 @@ def test_timestamp_groupby_quantile(): {"category": 68.8, "value": 168.8}, {"category": 92.2, "value": 192.2}, ], - index=pd.MultiIndex.from_tuples( - [ - (pd.Timestamp("2020-04-19 00:00:00+00:00"), 0.2), - (pd.Timestamp("2020-04-19 00:00:00+00:00"), 0.8), - (pd.Timestamp("2020-04-19 01:00:00+00:00"), 0.2), - (pd.Timestamp("2020-04-19 01:00:00+00:00"), 0.8), - ], - names=("timestamp", None), - ), + index=mi, ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/methods/test_value_counts.py b/pandas/tests/groupby/methods/test_value_counts.py index b82908ef2aa21..200fa5fd4367d 100644 --- a/pandas/tests/groupby/methods/test_value_counts.py +++ b/pandas/tests/groupby/methods/test_value_counts.py @@ -1135,7 +1135,7 @@ def test_subset_duplicate_columns(): @pytest.mark.parametrize("utc", [True, False]) -def test_value_counts_time_grouper(utc): +def test_value_counts_time_grouper(utc, unit): # GH#50486 df = DataFrame( { @@ -1152,12 +1152,12 @@ def test_value_counts_time_grouper(utc): } ).drop([3]) - df["Datetime"] = to_datetime(df["Timestamp"], utc=utc, unit="s") + df["Datetime"] = to_datetime(df["Timestamp"], utc=utc, unit="s").dt.as_unit(unit) gb = df.groupby(Grouper(freq="1D", key="Datetime")) result = gb.value_counts() dates = to_datetime( ["2019-08-06", "2019-08-07", "2019-08-09", "2019-08-10"], utc=utc - ) + ).as_unit(unit) timestamps = df["Timestamp"].unique() index = MultiIndex( levels=[dates, timestamps, ["apple", "banana", "orange", "pear"]], diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index de8ceb30b565b..5eb894f4eabdf 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -3172,28 +3172,32 @@ def test_groupby_selection_other_methods(df): ) -def test_groupby_with_Time_Grouper(): - idx2 = [ - to_datetime("2016-08-31 22:08:12.000"), - to_datetime("2016-08-31 22:09:12.200"), - to_datetime("2016-08-31 22:20:12.400"), - ] +def test_groupby_with_Time_Grouper(unit): + idx2 = to_datetime( + [ + "2016-08-31 22:08:12.000", + "2016-08-31 22:09:12.200", + "2016-08-31 22:20:12.400", + ] + ).as_unit(unit) test_data = DataFrame( {"quant": [1.0, 1.0, 3.0], "quant2": [1.0, 1.0, 3.0], "time2": idx2} ) + time2 = date_range("2016-08-31 22:08:00", periods=13, freq="1min", unit=unit) expected_output = DataFrame( { - "time2": date_range("2016-08-31 22:08:00", periods=13, freq="1min"), + "time2": time2, "quant": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], "quant2": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], } ) - df = test_data.groupby(Grouper(key="time2", freq="1min")).count().reset_index() + gb = test_data.groupby(Grouper(key="time2", freq="1min")) + result = gb.count().reset_index() - tm.assert_frame_equal(df, expected_output) + tm.assert_frame_equal(result, expected_output) def test_groupby_series_with_datetimeindex_month_name(): diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 01768582299eb..3e52476be9dbd 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -276,19 +276,24 @@ def test_grouper_creation_bug2(self): result = g.sum() tm.assert_frame_equal(result, expected) - def test_grouper_creation_bug3(self): + def test_grouper_creation_bug3(self, unit): # GH8866 + dti = date_range("20130101", periods=2, unit=unit) + mi = MultiIndex.from_product( + [list("ab"), range(2), dti], + names=["one", "two", "three"], + ) ser = Series( np.arange(8, dtype="int64"), - index=MultiIndex.from_product( - [list("ab"), range(2), date_range("20130101", periods=2)], - names=["one", "two", "three"], - ), + index=mi, ) result = ser.groupby(Grouper(level="three", freq="ME")).sum() + exp_dti = pd.DatetimeIndex( + [Timestamp("2013-01-31")], freq="ME", name="three" + ).as_unit(unit) expected = Series( [28], - index=pd.DatetimeIndex([Timestamp("2013-01-31")], freq="ME", name="three"), + index=exp_dti, ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/methods/test_delete.py b/pandas/tests/indexes/datetimes/methods/test_delete.py index 0fdd60c14474e..2341499977f22 100644 --- a/pandas/tests/indexes/datetimes/methods/test_delete.py +++ b/pandas/tests/indexes/datetimes/methods/test_delete.py @@ -116,18 +116,17 @@ def test_delete_slice(self, unit): # TODO: belongs in Series.drop tests? @pytest.mark.parametrize("tz", [None, "Asia/Tokyo", "US/Pacific"]) - def test_delete_slice2(self, tz): + def test_delete_slice2(self, tz, unit): + dti = date_range( + "2000-01-01 09:00", periods=10, freq="h", name="idx", tz=tz, unit=unit + ) ts = Series( 1, - index=date_range( - "2000-01-01 09:00", periods=10, freq="h", name="idx", tz=tz - ), + index=dti, ) # preserve freq result = ts.drop(ts.index[:5]).index - expected = date_range( - "2000-01-01 14:00", periods=5, freq="h", name="idx", tz=tz - ) + expected = dti[5:] tm.assert_index_equal(result, expected) assert result.name == expected.name assert result.freq == expected.freq @@ -135,18 +134,7 @@ def test_delete_slice2(self, tz): # reset freq to None result = ts.drop(ts.index[[1, 3, 5, 7, 9]]).index - expected = DatetimeIndex( - [ - "2000-01-01 09:00", - "2000-01-01 11:00", - "2000-01-01 13:00", - "2000-01-01 15:00", - "2000-01-01 17:00", - ], - freq=None, - name="idx", - tz=tz, - ) + expected = dti[::2]._with_freq(None) tm.assert_index_equal(result, expected) assert result.name == expected.name assert result.freq == expected.freq diff --git a/pandas/tests/indexes/datetimes/methods/test_repeat.py b/pandas/tests/indexes/datetimes/methods/test_repeat.py index cf4749aedd5a7..92501755f8c5b 100644 --- a/pandas/tests/indexes/datetimes/methods/test_repeat.py +++ b/pandas/tests/indexes/datetimes/methods/test_repeat.py @@ -17,29 +17,29 @@ def test_repeat_range(self, tz_naive_fixture): assert result.freq is None assert len(result) == 5 * len(rng) - def test_repeat_range2(self, tz_naive_fixture): + def test_repeat_range2(self, tz_naive_fixture, unit): tz = tz_naive_fixture - index = date_range("2001-01-01", periods=2, freq="D", tz=tz) + index = date_range("2001-01-01", periods=2, freq="D", tz=tz, unit=unit) exp = DatetimeIndex( ["2001-01-01", "2001-01-01", "2001-01-02", "2001-01-02"], tz=tz - ) + ).as_unit(unit) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) assert res.freq is None - def test_repeat_range3(self, tz_naive_fixture): + def test_repeat_range3(self, tz_naive_fixture, unit): tz = tz_naive_fixture - index = date_range("2001-01-01", periods=2, freq="2D", tz=tz) + index = date_range("2001-01-01", periods=2, freq="2D", tz=tz, unit=unit) exp = DatetimeIndex( ["2001-01-01", "2001-01-01", "2001-01-03", "2001-01-03"], tz=tz - ) + ).as_unit(unit) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) assert res.freq is None - def test_repeat_range4(self, tz_naive_fixture): + def test_repeat_range4(self, tz_naive_fixture, unit): tz = tz_naive_fixture - index = DatetimeIndex(["2001-01-01", "NaT", "2003-01-01"], tz=tz) + index = DatetimeIndex(["2001-01-01", "NaT", "2003-01-01"], tz=tz).as_unit(unit) exp = DatetimeIndex( [ "2001-01-01", @@ -53,17 +53,17 @@ def test_repeat_range4(self, tz_naive_fixture): "2003-01-01", ], tz=tz, - ) + ).as_unit(unit) for res in [index.repeat(3), np.repeat(index, 3)]: tm.assert_index_equal(res, exp) assert res.freq is None - def test_repeat(self, tz_naive_fixture): + def test_repeat(self, tz_naive_fixture, unit): tz = tz_naive_fixture reps = 2 msg = "the 'axis' parameter is not supported" - rng = date_range(start="2016-01-01", periods=2, freq="30Min", tz=tz) + rng = date_range(start="2016-01-01", periods=2, freq="30Min", tz=tz, unit=unit) expected_rng = DatetimeIndex( [ @@ -72,7 +72,7 @@ def test_repeat(self, tz_naive_fixture): Timestamp("2016-01-01 00:30:00", tz=tz), Timestamp("2016-01-01 00:30:00", tz=tz), ] - ) + ).as_unit(unit) res = rng.repeat(reps) tm.assert_index_equal(res, expected_rng) diff --git a/pandas/tests/indexes/datetimes/methods/test_tz_localize.py b/pandas/tests/indexes/datetimes/methods/test_tz_localize.py index 9cd0d2df48ac8..6e5349870144a 100644 --- a/pandas/tests/indexes/datetimes/methods/test_tz_localize.py +++ b/pandas/tests/indexes/datetimes/methods/test_tz_localize.py @@ -97,9 +97,11 @@ def test_dti_tz_localize_ambiguous_infer(self, tz): dr.tz_localize(tz) @pytest.mark.parametrize("tz", easts) - def test_dti_tz_localize_ambiguous_infer2(self, tz): + def test_dti_tz_localize_ambiguous_infer2(self, tz, unit): # With repeated hours, we can infer the transition - dr = date_range(datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour(), tz=tz) + dr = date_range( + datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour(), tz=tz, unit=unit + ) times = [ "11/06/2011 00:00", "11/06/2011 01:00", @@ -107,11 +109,11 @@ def test_dti_tz_localize_ambiguous_infer2(self, tz): "11/06/2011 02:00", "11/06/2011 03:00", ] - di = DatetimeIndex(times) + di = DatetimeIndex(times).as_unit(unit) result = di.tz_localize(tz, ambiguous="infer") expected = dr._with_freq(None) tm.assert_index_equal(result, expected) - result2 = DatetimeIndex(times, tz=tz, ambiguous="infer") + result2 = DatetimeIndex(times, tz=tz, ambiguous="infer").as_unit(unit) tm.assert_index_equal(result2, expected) @pytest.mark.parametrize("tz", easts) @@ -269,11 +271,13 @@ def test_dti_tz_localize_ambiguous_nat(self, tz): tm.assert_numpy_array_equal(di_test.values, localized.values) @pytest.mark.parametrize("tz", easts) - def test_dti_tz_localize_ambiguous_flags(self, tz): + def test_dti_tz_localize_ambiguous_flags(self, tz, unit): # November 6, 2011, fall back, repeat 2 AM hour # Pass in flags to determine right dst transition - dr = date_range(datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour(), tz=tz) + dr = date_range( + datetime(2011, 11, 6, 0), periods=5, freq=offsets.Hour(), tz=tz, unit=unit + ) times = [ "11/06/2011 00:00", "11/06/2011 01:00", @@ -283,12 +287,17 @@ def test_dti_tz_localize_ambiguous_flags(self, tz): ] # Test tz_localize - di = DatetimeIndex(times) + di = DatetimeIndex(times).as_unit(unit) is_dst = [1, 1, 0, 0, 0] localized = di.tz_localize(tz, ambiguous=is_dst) expected = dr._with_freq(None) tm.assert_index_equal(expected, localized) - tm.assert_index_equal(expected, DatetimeIndex(times, tz=tz, ambiguous=is_dst)) + + result = DatetimeIndex(times, tz=tz, ambiguous=is_dst).as_unit(unit) + tm.assert_index_equal( + result, + expected, + ) localized = di.tz_localize(tz, ambiguous=np.array(is_dst)) tm.assert_index_equal(dr, localized) @@ -297,12 +306,12 @@ def test_dti_tz_localize_ambiguous_flags(self, tz): tm.assert_index_equal(dr, localized) # Test constructor - localized = DatetimeIndex(times, tz=tz, ambiguous=is_dst) + localized = DatetimeIndex(times, tz=tz, ambiguous=is_dst).as_unit(unit) tm.assert_index_equal(dr, localized) # Test duplicate times where inferring the dst fails times += times - di = DatetimeIndex(times) + di = DatetimeIndex(times).as_unit(unit) # When the sizes are incompatible, make sure error is raised msg = "Length of ambiguous bool-array must be the same size as vals" @@ -315,6 +324,8 @@ def test_dti_tz_localize_ambiguous_flags(self, tz): dr = dr.append(dr) tm.assert_index_equal(dr, localized) + @pytest.mark.parametrize("tz", easts) + def test_dti_tz_localize_ambiguous_flags2(self, tz, unit): # When there is no dst transition, nothing special happens dr = date_range(datetime(2011, 6, 1, 0), periods=10, freq=offsets.Hour()) is_dst = np.array([1] * 10) @@ -373,15 +384,15 @@ def test_dti_tz_localize_bdate_range(self): ) @pytest.mark.parametrize("tz_type", ["", "dateutil/"]) def test_dti_tz_localize_nonexistent_shift( - self, start_ts, tz, end_ts, shift, tz_type + self, start_ts, tz, end_ts, shift, tz_type, unit ): # GH#8917 tz = tz_type + tz if isinstance(shift, str): shift = "shift_" + shift - dti = DatetimeIndex([Timestamp(start_ts)]) + dti = DatetimeIndex([Timestamp(start_ts)]).as_unit(unit) result = dti.tz_localize(tz, nonexistent=shift) - expected = DatetimeIndex([Timestamp(end_ts)]).tz_localize(tz) + expected = DatetimeIndex([Timestamp(end_ts)]).tz_localize(tz).as_unit(unit) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("offset", [-1, 1]) diff --git a/pandas/tests/indexes/datetimes/methods/test_unique.py b/pandas/tests/indexes/datetimes/methods/test_unique.py index 5319bf59f8a64..0d2c1e3f03c02 100644 --- a/pandas/tests/indexes/datetimes/methods/test_unique.py +++ b/pandas/tests/indexes/datetimes/methods/test_unique.py @@ -33,7 +33,8 @@ def test_index_unique(rand_series_with_duplicate_datetimeindex): datetime(2000, 1, 3), datetime(2000, 1, 4), datetime(2000, 1, 5), - ] + ], + dtype="M8[ns]", ) assert uniques.dtype == "M8[ns]" # sanity tm.assert_index_equal(uniques, expected) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 2a1fa20dce777..7110a428544d5 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -955,8 +955,10 @@ def test_dti_tz_constructors(self, tzstr): for other in [idx2, idx3, idx4]: tm.assert_index_equal(idx1, other) - def test_dti_construction_univalent(self): - rng = date_range("03/12/2012 00:00", periods=10, freq="W-FRI", tz="US/Eastern") + def test_dti_construction_univalent(self, unit): + rng = date_range( + "03/12/2012 00:00", periods=10, freq="W-FRI", tz="US/Eastern", unit=unit + ) rng2 = DatetimeIndex(data=rng, tz="US/Eastern") tm.assert_index_equal(rng, rng2) diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 3a6d1cacd0f81..6e8214dc775ae 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -285,9 +285,11 @@ def test_date_range_normalize(self): rng = date_range(snap, periods=n, normalize=False, freq="2D") offset = timedelta(2) - values = DatetimeIndex([snap + i * offset for i in range(n)], freq=offset) + expected = DatetimeIndex( + [snap + i * offset for i in range(n)], dtype="M8[ns]", freq=offset + ) - tm.assert_index_equal(rng, values) + tm.assert_index_equal(rng, expected) rng = date_range("1/1/2000 08:15", periods=n, normalize=False, freq="B") the_time = time(8, 15) @@ -306,11 +308,12 @@ def test_date_range_ambiguous_arguments(self): with pytest.raises(ValueError, match=msg): date_range(start, end, periods=10, freq="s") - def test_date_range_convenience_periods(self): + def test_date_range_convenience_periods(self, unit): # GH 20808 - result = date_range("2018-04-24", "2018-04-27", periods=3) + result = date_range("2018-04-24", "2018-04-27", periods=3, unit=unit) expected = DatetimeIndex( ["2018-04-24 00:00:00", "2018-04-25 12:00:00", "2018-04-27 00:00:00"], + dtype=f"M8[{unit}]", freq=None, ) @@ -322,6 +325,7 @@ def test_date_range_convenience_periods(self): "2018-04-01 04:00:00", tz="Australia/Sydney", periods=3, + unit=unit, ) expected = DatetimeIndex( [ @@ -329,7 +333,7 @@ def test_date_range_convenience_periods(self): Timestamp("2018-04-01 02:00:00+1000", tz="Australia/Sydney"), Timestamp("2018-04-01 04:00:00+1000", tz="Australia/Sydney"), ] - ) + ).as_unit(unit) tm.assert_index_equal(result, expected) def test_date_range_index_comparison(self): @@ -432,7 +436,7 @@ def test_catch_infinite_loop(self): with pytest.raises(ValueError, match=msg): date_range(datetime(2011, 11, 11), datetime(2011, 11, 12), freq=offset) - def test_construct_over_dst(self): + def test_construct_over_dst(self, unit): # GH 20854 pre_dst = Timestamp("2010-11-07 01:00:00").tz_localize( "US/Pacific", ambiguous=True @@ -445,14 +449,19 @@ def test_construct_over_dst(self): pre_dst, pst_dst, ] - expected = DatetimeIndex(expect_data, freq="h") - result = date_range(start="2010-11-7", periods=3, freq="h", tz="US/Pacific") + expected = DatetimeIndex(expect_data, freq="h").as_unit(unit) + result = date_range( + start="2010-11-7", periods=3, freq="h", tz="US/Pacific", unit=unit + ) tm.assert_index_equal(result, expected) - def test_construct_with_different_start_end_string_format(self): + def test_construct_with_different_start_end_string_format(self, unit): # GH 12064 result = date_range( - "2013-01-01 00:00:00+09:00", "2013/01/01 02:00:00+09:00", freq="h" + "2013-01-01 00:00:00+09:00", + "2013/01/01 02:00:00+09:00", + freq="h", + unit=unit, ) expected = DatetimeIndex( [ @@ -461,7 +470,7 @@ def test_construct_with_different_start_end_string_format(self): Timestamp("2013-01-01 02:00:00+09:00"), ], freq="h", - ) + ).as_unit(unit) tm.assert_index_equal(result, expected) def test_error_with_zero_monthends(self): @@ -469,13 +478,15 @@ def test_error_with_zero_monthends(self): with pytest.raises(ValueError, match=msg): date_range("1/1/2000", "1/1/2001", freq=MonthEnd(0)) - def test_range_bug(self): + def test_range_bug(self, unit): # GH #770 offset = DateOffset(months=3) - result = date_range("2011-1-1", "2012-1-31", freq=offset) + result = date_range("2011-1-1", "2012-1-31", freq=offset, unit=unit) start = datetime(2011, 1, 1) - expected = DatetimeIndex([start + i * offset for i in range(5)], freq=offset) + expected = DatetimeIndex( + [start + i * offset for i in range(5)], dtype=f"M8[{unit}]", freq=offset + ) tm.assert_index_equal(result, expected) def test_range_tz_pytz(self): @@ -1081,7 +1092,7 @@ def test_bday_near_overflow(self): # GH#24252 avoid doing unnecessary addition that _would_ overflow start = Timestamp.max.floor("D").to_pydatetime() rng = date_range(start, end=None, periods=1, freq="B") - expected = DatetimeIndex([start], freq="B") + expected = DatetimeIndex([start], freq="B").as_unit("ns") tm.assert_index_equal(rng, expected) def test_bday_overflow_error(self): @@ -1123,18 +1134,22 @@ def test_daterange_bug_456(self): result = rng1.union(rng2) assert isinstance(result, DatetimeIndex) - def test_cdaterange(self): - result = bdate_range("2013-05-01", periods=3, freq="C") - expected = DatetimeIndex(["2013-05-01", "2013-05-02", "2013-05-03"], freq="C") + def test_cdaterange(self, unit): + result = bdate_range("2013-05-01", periods=3, freq="C", unit=unit) + expected = DatetimeIndex( + ["2013-05-01", "2013-05-02", "2013-05-03"], dtype=f"M8[{unit}]", freq="C" + ) tm.assert_index_equal(result, expected) assert result.freq == expected.freq - def test_cdaterange_weekmask(self): + def test_cdaterange_weekmask(self, unit): result = bdate_range( - "2013-05-01", periods=3, freq="C", weekmask="Sun Mon Tue Wed Thu" + "2013-05-01", periods=3, freq="C", weekmask="Sun Mon Tue Wed Thu", unit=unit ) expected = DatetimeIndex( - ["2013-05-01", "2013-05-02", "2013-05-05"], freq=result.freq + ["2013-05-01", "2013-05-02", "2013-05-05"], + dtype=f"M8[{unit}]", + freq=result.freq, ) tm.assert_index_equal(result, expected) assert result.freq == expected.freq @@ -1147,10 +1162,14 @@ def test_cdaterange_weekmask(self): with pytest.raises(ValueError, match=msg): bdate_range("2013-05-01", periods=3, weekmask="Sun Mon Tue Wed Thu") - def test_cdaterange_holidays(self): - result = bdate_range("2013-05-01", periods=3, freq="C", holidays=["2013-05-01"]) + def test_cdaterange_holidays(self, unit): + result = bdate_range( + "2013-05-01", periods=3, freq="C", holidays=["2013-05-01"], unit=unit + ) expected = DatetimeIndex( - ["2013-05-02", "2013-05-03", "2013-05-06"], freq=result.freq + ["2013-05-02", "2013-05-03", "2013-05-06"], + dtype=f"M8[{unit}]", + freq=result.freq, ) tm.assert_index_equal(result, expected) assert result.freq == expected.freq @@ -1163,20 +1182,24 @@ def test_cdaterange_holidays(self): with pytest.raises(ValueError, match=msg): bdate_range("2013-05-01", periods=3, holidays=["2013-05-01"]) - def test_cdaterange_weekmask_and_holidays(self): + def test_cdaterange_weekmask_and_holidays(self, unit): result = bdate_range( "2013-05-01", periods=3, freq="C", weekmask="Sun Mon Tue Wed Thu", holidays=["2013-05-01"], + unit=unit, ) expected = DatetimeIndex( - ["2013-05-02", "2013-05-05", "2013-05-06"], freq=result.freq + ["2013-05-02", "2013-05-05", "2013-05-06"], + dtype=f"M8[{unit}]", + freq=result.freq, ) tm.assert_index_equal(result, expected) assert result.freq == expected.freq + def test_cdaterange_holidays_weekmask_requires_freqstr(self): # raise with non-custom freq msg = ( "a custom frequency string is required when holidays or " @@ -1216,7 +1239,7 @@ def test_range_with_millisecond_resolution(self, start_end): # https://github.com/pandas-dev/pandas/issues/24110 start, end = start_end result = date_range(start=start, end=end, periods=2, inclusive="left") - expected = DatetimeIndex([start]) + expected = DatetimeIndex([start], dtype="M8[ns, UTC]") tm.assert_index_equal(result, expected) @pytest.mark.parametrize( @@ -1234,7 +1257,7 @@ def test_range_with_millisecond_resolution(self, start_end): def test_range_with_timezone_and_custombusinessday(self, start, period, expected): # GH49441 result = date_range(start=start, periods=period, freq="C") - expected = DatetimeIndex(expected) + expected = DatetimeIndex(expected).as_unit("ns") tm.assert_index_equal(result, expected) @@ -1618,6 +1641,16 @@ def test_date_range_week_of_month(self, unit): ) tm.assert_index_equal(result2, expected2) + def test_date_range_week_of_month2(self, unit): + # GH#5115, GH#5348 + result = date_range("2013-1-1", periods=4, freq="WOM-1SAT", unit=unit) + expected = DatetimeIndex( + ["2013-01-05", "2013-02-02", "2013-03-02", "2013-04-06"], + dtype=f"M8[{unit}]", + freq="WOM-1SAT", + ) + tm.assert_index_equal(result, expected) + def test_date_range_negative_freq_month_end(self, unit): # GH#11018 rng = date_range("2011-01-31", freq="-2ME", periods=3, unit=unit) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index a1074a1744c7a..e17afd8c2d8a9 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -58,12 +58,6 @@ def test_week_of_month_frequency(self): expected = DatetimeIndex([d1, d3, d2]) tm.assert_index_equal(result_union, expected) - # GH 5115 - result = date_range("2013-1-1", periods=4, freq="WOM-1SAT") - dates = ["2013-01-05", "2013-02-02", "2013-03-02", "2013-04-06"] - expected = DatetimeIndex(dates, freq="WOM-1SAT") - tm.assert_index_equal(result, expected) - def test_append_nondatetimeindex(self): rng = date_range("1/1/2000", periods=10) idx = Index(["a", "b", "c", "d"]) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 9cf4e68a9c5ec..9bc1b5e2502ae 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1385,7 +1385,9 @@ def test_resample_timegrouper(dates, unit): @pytest.mark.parametrize("dates", [dates1, dates2, dates3]) -def test_resample_timegrouper2(dates): +def test_resample_timegrouper2(dates, unit): + dates = DatetimeIndex(dates).as_unit(unit) + df = DataFrame({"A": dates, "B": np.arange(len(dates)), "C": np.arange(len(dates))}) result = df.set_index("A").resample("ME").count() @@ -1393,7 +1395,7 @@ def test_resample_timegrouper2(dates): ["2014-07-31", "2014-08-31", "2014-09-30", "2014-10-31", "2014-11-30"], freq="ME", name="A", - ) + ).as_unit(unit) expected = DataFrame( {"B": [1, 0, 2, 2, 1], "C": [1, 0, 2, 2, 1]}, index=exp_idx, diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index f3a7c94fc9eaa..e9871fa4bdc12 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -303,13 +303,17 @@ def test_with_local_timezone(self, tz): dateutil.tz.gettz("America/Los_Angeles"), ], ) - def test_resample_with_tz(self, tz): + def test_resample_with_tz(self, tz, unit): # GH 13238 - ser = Series(2, index=date_range("2017-01-01", periods=48, freq="h", tz=tz)) + dti = date_range("2017-01-01", periods=48, freq="h", tz=tz, unit=unit) + ser = Series(2, index=dti) result = ser.resample("D").mean() + exp_dti = pd.DatetimeIndex( + ["2017-01-01", "2017-01-02"], tz=tz, freq="D" + ).as_unit(unit) expected = Series( 2.0, - index=pd.DatetimeIndex(["2017-01-01", "2017-01-02"], tz=tz, freq="D"), + index=exp_dti, ) tm.assert_series_equal(result, expected) # Especially assert that the timezone is LMT for pytz diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py index 2779100f5355c..227cf6a495c91 100644 --- a/pandas/tests/tseries/offsets/test_business_hour.py +++ b/pandas/tests/tseries/offsets/test_business_hour.py @@ -946,6 +946,38 @@ def test_apply_nanoseconds(self): for base, expected in cases.items(): assert_offset_equal(offset, base, expected) + def test_datetimeindex(self): + idx1 = date_range(start="2014-07-04 15:00", end="2014-07-08 10:00", freq="bh") + idx2 = date_range(start="2014-07-04 15:00", periods=12, freq="bh") + idx3 = date_range(end="2014-07-08 10:00", periods=12, freq="bh") + expected = DatetimeIndex( + [ + "2014-07-04 15:00", + "2014-07-04 16:00", + "2014-07-07 09:00", + "2014-07-07 10:00", + "2014-07-07 11:00", + "2014-07-07 12:00", + "2014-07-07 13:00", + "2014-07-07 14:00", + "2014-07-07 15:00", + "2014-07-07 16:00", + "2014-07-08 09:00", + "2014-07-08 10:00", + ], + freq="bh", + ) + for idx in [idx1, idx2, idx3]: + tm.assert_index_equal(idx, expected) + + idx1 = date_range(start="2014-07-04 15:45", end="2014-07-08 10:45", freq="bh") + idx2 = date_range(start="2014-07-04 15:45", periods=12, freq="bh") + idx3 = date_range(end="2014-07-08 10:45", periods=12, freq="bh") + + expected = idx1 + for idx in [idx1, idx2, idx3]: + tm.assert_index_equal(idx, expected) + @pytest.mark.parametrize("td_unit", ["s", "ms", "us", "ns"]) @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) def test_bday_ignores_timedeltas(self, unit, td_unit): diff --git a/pandas/tests/tseries/offsets/test_month.py b/pandas/tests/tseries/offsets/test_month.py index 2b643999c3ad3..fc12510369245 100644 --- a/pandas/tests/tseries/offsets/test_month.py +++ b/pandas/tests/tseries/offsets/test_month.py @@ -23,6 +23,7 @@ DatetimeIndex, Series, _testing as tm, + date_range, ) from pandas.tests.tseries.offsets.common import ( assert_is_on_offset, @@ -73,6 +74,11 @@ def test_offset_whole_year(self): exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) + # ensure generating a range with DatetimeIndex gives same result + result = date_range(start=dates[0], end=dates[-1], freq="SM") + exp = DatetimeIndex(dates, freq="SM") + tm.assert_index_equal(result, exp) + offset_cases = [] offset_cases.append( ( @@ -324,6 +330,11 @@ def test_offset_whole_year(self): exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) + # ensure generating a range with DatetimeIndex gives same result + result = date_range(start=dates[0], end=dates[-1], freq="SMS") + exp = DatetimeIndex(dates, freq="SMS") + tm.assert_index_equal(result, exp) + offset_cases = [ ( SemiMonthBegin(), diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index c5c395414b450..427780db79783 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -102,12 +102,38 @@ def test_ewma_with_times_equal_spacing(halflife_with_times, times, min_periods): tm.assert_frame_equal(result, expected) -def test_ewma_with_times_variable_spacing(tz_aware_fixture): +@pytest.mark.parametrize( + "unit", + [ + pytest.param( + "s", + marks=pytest.mark.xfail( + reason="ExponentialMovingWindow constructor raises on non-nano" + ), + ), + pytest.param( + "ms", + marks=pytest.mark.xfail( + reason="ExponentialMovingWindow constructor raises on non-nano" + ), + ), + pytest.param( + "us", + marks=pytest.mark.xfail( + reason="ExponentialMovingWindow constructor raises on non-nano" + ), + ), + "ns", + ], +) +def test_ewma_with_times_variable_spacing(tz_aware_fixture, unit): tz = tz_aware_fixture halflife = "23 days" - times = DatetimeIndex( - ["2020-01-01", "2020-01-10T00:04:05", "2020-02-23T05:00:23"] - ).tz_localize(tz) + times = ( + DatetimeIndex(["2020-01-01", "2020-01-10T00:04:05", "2020-02-23T05:00:23"]) + .tz_localize(tz) + .as_unit(unit) + ) data = np.arange(3) df = DataFrame(data) result = df.ewm(halflife=halflife, times=times).mean()
- [ ] 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. Aimed at trimming the diff in #55901
https://api.github.com/repos/pandas-dev/pandas/pulls/55974
2023-11-15T17:10:07Z
2023-11-16T02:15:19Z
2023-11-16T02:15:19Z
2023-11-16T02:30:45Z
PERF: assert_frame_equal / assert_series_equal
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index be5383602383e..accf076513aa1 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -309,7 +309,7 @@ Other Deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- Performance improvement in :func:`.testing.assert_frame_equal` and :func:`.testing.assert_series_equal` for objects indexed by a :class:`MultiIndex` (:issue:`55949`) +- Performance improvement in :func:`.testing.assert_frame_equal` and :func:`.testing.assert_series_equal` (:issue:`55949`, :issue:`55971`) - Performance improvement in :func:`concat` with ``axis=1`` and objects with unaligned indexes (:issue:`55084`) - Performance improvement in :func:`merge_asof` when ``by`` is not ``None`` (:issue:`55580`, :issue:`55678`) - Performance improvement in :func:`read_stata` for files with many variables (:issue:`55515`) diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 8e49fcfb355fa..0d8fb7bfce33a 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -43,7 +43,6 @@ Series, TimedeltaIndex, ) -from pandas.core.algorithms import take_nd from pandas.core.arrays import ( DatetimeArray, ExtensionArray, @@ -246,13 +245,6 @@ def _check_types(left, right, obj: str = "Index") -> None: assert_attr_equal("dtype", left, right, obj=obj) - def _get_ilevel_values(index, level): - # accept level number only - unique = index.levels[level] - level_codes = index.codes[level] - filled = take_nd(unique._values, level_codes, fill_value=unique._na_value) - return unique._shallow_copy(filled, name=index.names[level]) - # instance validation _check_isinstance(left, right, Index) @@ -299,9 +291,8 @@ def _get_ilevel_values(index, level): ) assert_numpy_array_equal(left.codes[level], right.codes[level]) except AssertionError: - # cannot use get_level_values here because it can change dtype - llevel = _get_ilevel_values(left, level) - rlevel = _get_ilevel_values(right, level) + llevel = left.get_level_values(level) + rlevel = right.get_level_values(level) assert_index_equal( llevel, @@ -592,7 +583,7 @@ def raise_assert_detail( {message}""" if isinstance(index_values, Index): - index_values = np.array(index_values) + index_values = np.asarray(index_values) if isinstance(index_values, np.ndarray): msg += f"\n[index]: {pprint_thing(index_values)}" diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 8760c8eeca454..a635ac77566e1 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -562,12 +562,29 @@ def _array_equivalent_datetimelike(left: np.ndarray, right: np.ndarray): def _array_equivalent_object(left: np.ndarray, right: np.ndarray, strict_nan: bool): - if not strict_nan: - # isna considers NaN and None to be equivalent. - - return lib.array_equivalent_object(ensure_object(left), ensure_object(right)) - - for left_value, right_value in zip(left, right): + left = ensure_object(left) + right = ensure_object(right) + + mask: npt.NDArray[np.bool_] | None = None + if strict_nan: + mask = isna(left) & isna(right) + if not mask.any(): + mask = None + + try: + if mask is None: + return lib.array_equivalent_object(left, right) + if not lib.array_equivalent_object(left[~mask], right[~mask]): + return False + left_remaining = left[mask] + right_remaining = right[mask] + except ValueError: + # can raise a ValueError if left and right cannot be + # compared (e.g. nested arrays) + left_remaining = left + right_remaining = right + + for left_value, right_value in zip(left_remaining, right_remaining): if left_value is NaT and right_value is not NaT: return False diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index b995dc591c749..1cc1e2725b9c7 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -560,9 +560,7 @@ def test_array_equivalent_str(dtype): ) -@pytest.mark.parametrize( - "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False] -) +@pytest.mark.parametrize("strict_nan", [True, False]) def test_array_equivalent_nested(strict_nan): # reached in groupby aggregations, make sure we use np.any when checking # if the comparison is truthy @@ -585,9 +583,7 @@ def test_array_equivalent_nested(strict_nan): @pytest.mark.filterwarnings("ignore:elementwise comparison failed:DeprecationWarning") -@pytest.mark.parametrize( - "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False] -) +@pytest.mark.parametrize("strict_nan", [True, False]) def test_array_equivalent_nested2(strict_nan): # more than one level of nesting left = np.array( @@ -612,9 +608,7 @@ def test_array_equivalent_nested2(strict_nan): assert not array_equivalent(left, right, strict_nan=strict_nan) -@pytest.mark.parametrize( - "strict_nan", [pytest.param(True, marks=pytest.mark.xfail), False] -) +@pytest.mark.parametrize("strict_nan", [True, False]) def test_array_equivalent_nested_list(strict_nan): left = np.array([[50, 70, 90], [20, 30]], dtype=object) right = np.array([[50, 70, 90], [20, 30]], dtype=object)
- [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.2.0.rst` file if fixing a bug or adding a new feature. Follow-up to #55949 addressing some of @jbrockmendel's comments and also expanding to non-multiindex cases: ``` import pandas as pd N = 1_000_000 idx = pd._testing.makeStringIndex(N) ser1 = pd.Series(1, index=idx.copy(deep=True)) ser2 = pd.Series(1, index=idx.copy(deep=True)) %timeit pd.testing.assert_series_equal(ser1, ser2) # 17.8 s ± 129 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # 48.1 ms ± 3.28 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/55971
2023-11-15T12:51:02Z
2023-11-17T23:00:50Z
2023-11-17T23:00:50Z
2023-12-20T18:00:01Z
DEPR: resample with PeriodIndex
diff --git a/doc/source/whatsnew/v0.21.0.rst b/doc/source/whatsnew/v0.21.0.rst index 08a132264ddba..dad69b99ee6a4 100644 --- a/doc/source/whatsnew/v0.21.0.rst +++ b/doc/source/whatsnew/v0.21.0.rst @@ -635,17 +635,22 @@ Previous behavior: New behavior: -.. ipython:: python +.. code-block:: ipython - pi = pd.period_range('2017-01', periods=12, freq='M') + In [1]: pi = pd.period_range('2017-01', periods=12, freq='M') - s = pd.Series(np.arange(12), index=pi) + In [2]: s = pd.Series(np.arange(12), index=pi) - resampled = s.resample('2Q').mean() + In [3]: resampled = s.resample('2Q').mean() - resampled + In [4]: resampled + Out[4]: + 2017Q1 2.5 + 2017Q3 8.5 + Freq: 2Q-DEC, dtype: float64 - resampled.index + In [5]: resampled.index + Out[5]: PeriodIndex(['2017Q1', '2017Q3'], dtype='period[2Q-DEC]') Upsampling and calling ``.ohlc()`` previously returned a ``Series``, basically identical to calling ``.asfreq()``. OHLC upsampling now returns a DataFrame with columns ``open``, ``high``, ``low`` and ``close`` (:issue:`13083`). This is consistent with downsampling and ``DatetimeIndex`` behavior. diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 8209525721b98..98411634f1808 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -437,6 +437,7 @@ Other Deprecations - Deprecated :meth:`.DataFrameGroupBy.fillna` and :meth:`.SeriesGroupBy.fillna`; use :meth:`.DataFrameGroupBy.ffill`, :meth:`.DataFrameGroupBy.bfill` for forward and backward filling or :meth:`.DataFrame.fillna` to fill with a single value (or the Series equivalents) (:issue:`55718`) - Deprecated :meth:`Index.format`, use ``index.astype(str)`` or ``index.map(formatter)`` instead (:issue:`55413`) - Deprecated :meth:`Series.ravel`, the underlying array is already 1D, so ravel is not necessary (:issue:`52511`) +- Deprecated :meth:`Series.resample` and :meth:`DataFrame.resample` with a :class:`PeriodIndex` (and the 'convention' keyword), convert to :class:`DatetimeIndex` (with ``.to_timestamp()``) before resampling instead (:issue:`53481`) - Deprecated :meth:`Series.view`, use :meth:`Series.astype` instead to change the dtype (:issue:`20251`) - Deprecated ``core.internals`` members ``Block``, ``ExtensionBlock``, and ``DatetimeTZBlock``, use public APIs instead (:issue:`55139`) - Deprecated ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index e46a0aa044b6d..e809e507d8c5e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9370,7 +9370,7 @@ def resample( axis: Axis | lib.NoDefault = lib.no_default, closed: Literal["right", "left"] | None = None, label: Literal["right", "left"] | None = None, - convention: Literal["start", "end", "s", "e"] = "start", + convention: Literal["start", "end", "s", "e"] | lib.NoDefault = lib.no_default, kind: Literal["timestamp", "period"] | None | lib.NoDefault = lib.no_default, on: Level | None = None, level: Level | None = None, @@ -9408,6 +9408,9 @@ def resample( convention : {{'start', 'end', 's', 'e'}}, default 'start' For `PeriodIndex` only, controls whether to use the start or end of `rule`. + + .. deprecated:: 2.2.0 + Convert PeriodIndex to DatetimeIndex before resampling instead. kind : {{'timestamp', 'period'}}, optional, default None Pass 'timestamp' to convert the resulting index to a `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`. @@ -9572,55 +9575,6 @@ def resample( 2000-01-01 00:06:00 26 Freq: 3min, dtype: int64 - For a Series with a PeriodIndex, the keyword `convention` can be - used to control whether to use the start or end of `rule`. - - Resample a year by quarter using 'start' `convention`. Values are - assigned to the first quarter of the period. - - >>> s = pd.Series([1, 2], index=pd.period_range('2012-01-01', - ... freq='Y', - ... periods=2)) - >>> s - 2012 1 - 2013 2 - Freq: Y-DEC, dtype: int64 - >>> s.resample('Q', convention='start').asfreq() - 2012Q1 1.0 - 2012Q2 NaN - 2012Q3 NaN - 2012Q4 NaN - 2013Q1 2.0 - 2013Q2 NaN - 2013Q3 NaN - 2013Q4 NaN - Freq: Q-DEC, dtype: float64 - - Resample quarters by month using 'end' `convention`. Values are - assigned to the last month of the period. - - >>> q = pd.Series([1, 2, 3, 4], index=pd.period_range('2018-01-01', - ... freq='Q', - ... periods=4)) - >>> q - 2018Q1 1 - 2018Q2 2 - 2018Q3 3 - 2018Q4 4 - Freq: Q-DEC, dtype: int64 - >>> q.resample('M', convention='end').asfreq() - 2018-03 1.0 - 2018-04 NaN - 2018-05 NaN - 2018-06 2.0 - 2018-07 NaN - 2018-08 NaN - 2018-09 3.0 - 2018-10 NaN - 2018-11 NaN - 2018-12 4.0 - Freq: M, dtype: float64 - For DataFrame objects, the keyword `on` can be used to specify the column instead of the index for resampling. @@ -9785,6 +9739,18 @@ def resample( else: kind = None + if convention is not lib.no_default: + warnings.warn( + f"The 'convention' keyword in {type(self).__name__}.resample is " + "deprecated and will be removed in a future version. " + "Explicitly cast PeriodIndex to DatetimeIndex before resampling " + "instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + convention = "start" + return get_resampler( cast("Series | DataFrame", self), freq=rule, diff --git a/pandas/core/resample.py b/pandas/core/resample.py index b3e86b4360d74..785c7f7c583d6 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1876,6 +1876,12 @@ class PeriodIndexResampler(DatetimeIndexResampler): @property def _resampler_for_grouping(self): + warnings.warn( + "Resampling a groupby with a PeriodIndex is deprecated. " + "Cast to DatetimeIndex before resampling instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) return PeriodIndexResamplerGroupby def _get_binner_for_time(self): @@ -2225,6 +2231,21 @@ def _get_resampler(self, obj: NDFrame, kind=None) -> Resampler: gpr_index=ax, ) elif isinstance(ax, PeriodIndex) or kind == "period": + if isinstance(ax, PeriodIndex): + # GH#53481 + warnings.warn( + "Resampling with a PeriodIndex is deprecated. " + "Cast index to DatetimeIndex before resampling instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + warnings.warn( + "Resampling with kind='period' is deprecated. " + "Use datetime paths instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) return PeriodIndexResampler( obj, timegrouper=self, diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 6d3579c7f7adb..bf1c0f6346f02 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -86,9 +86,12 @@ def maybe_resample(series: Series, ax: Axes, kwargs: dict[str, Any]): ) freq = ax_freq elif _is_sup(freq, ax_freq): # one is weekly - how = "last" - series = getattr(series.resample("D"), how)().dropna() - series = getattr(series.resample(ax_freq), how)().dropna() + # Resampling with PeriodDtype is deprecated, so we convert to + # DatetimeIndex, resample, then convert back. + ser_ts = series.to_timestamp() + ser_d = ser_ts.resample("D").last().dropna() + ser_freq = ser_d.resample(ax_freq).last().dropna() + series = ser_freq.to_period(ax_freq) freq = ax_freq elif is_subperiod(freq, ax_freq) or _is_sub(freq, ax_freq): _upsample_others(ax, freq, kwargs) diff --git a/pandas/tests/resample/test_base.py b/pandas/tests/resample/test_base.py index 7176cdf6ff9e4..50644e33e45e1 100644 --- a/pandas/tests/resample/test_base.py +++ b/pandas/tests/resample/test_base.py @@ -85,8 +85,13 @@ def test_asfreq_fill_value(series, create_index): def test_resample_interpolate(frame): # GH#12925 df = frame - result = df.resample("1min").asfreq().interpolate() - expected = df.resample("1min").interpolate() + warn = None + if isinstance(df.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + result = df.resample("1min").asfreq().interpolate() + expected = df.resample("1min").interpolate() tm.assert_frame_equal(result, expected) @@ -118,7 +123,13 @@ def test_resample_empty_series(freq, empty_series_dti, resample_method): elif freq == "ME" and isinstance(ser.index, PeriodIndex): # index is PeriodIndex, so convert to corresponding Period freq freq = "M" - rs = ser.resample(freq) + + warn = None + if isinstance(ser.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = ser.resample(freq) result = getattr(rs, resample_method)() if resample_method == "ohlc": @@ -150,7 +161,10 @@ def test_resample_nat_index_series(freq, series, resample_method): ser = series.copy() ser.index = PeriodIndex([NaT] * len(ser), freq=freq) - rs = ser.resample(freq) + + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = ser.resample(freq) result = getattr(rs, resample_method)() if resample_method == "ohlc": @@ -182,7 +196,13 @@ def test_resample_count_empty_series(freq, empty_series_dti, resample_method): elif freq == "ME" and isinstance(ser.index, PeriodIndex): # index is PeriodIndex, so convert to corresponding Period freq freq = "M" - rs = ser.resample(freq) + + warn = None + if isinstance(ser.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = ser.resample(freq) result = getattr(rs, resample_method)() @@ -210,7 +230,13 @@ def test_resample_empty_dataframe(empty_frame_dti, freq, resample_method): elif freq == "ME" and isinstance(df.index, PeriodIndex): # index is PeriodIndex, so convert to corresponding Period freq freq = "M" - rs = df.resample(freq, group_keys=False) + + warn = None + if isinstance(df.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = df.resample(freq, group_keys=False) result = getattr(rs, resample_method)() if resample_method == "ohlc": # TODO: no tests with len(df.columns) > 0 @@ -253,7 +279,14 @@ def test_resample_count_empty_dataframe(freq, empty_frame_dti): elif freq == "ME" and isinstance(empty_frame_dti.index, PeriodIndex): # index is PeriodIndex, so convert to corresponding Period freq freq = "M" - result = empty_frame_dti.resample(freq).count() + + warn = None + if isinstance(empty_frame_dti.index, PeriodIndex): + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(warn, match=msg): + rs = empty_frame_dti.resample(freq) + result = rs.count() index = _asfreq_compat(empty_frame_dti.index, freq) @@ -280,7 +313,14 @@ def test_resample_size_empty_dataframe(freq, empty_frame_dti): elif freq == "ME" and isinstance(empty_frame_dti.index, PeriodIndex): # index is PeriodIndex, so convert to corresponding Period freq freq = "M" - result = empty_frame_dti.resample(freq).size() + + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(empty_frame_dti.index, PeriodIndex): + warn = FutureWarning + with tm.assert_produces_warning(warn, match=msg): + rs = empty_frame_dti.resample(freq) + result = rs.size() index = _asfreq_compat(empty_frame_dti.index, freq) @@ -298,12 +338,21 @@ def test_resample_size_empty_dataframe(freq, empty_frame_dti): ], ) @pytest.mark.parametrize("dtype", [float, int, object, "datetime64[ns]"]) +@pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_resample_empty_dtypes(index, dtype, resample_method): # Empty series were sometimes causing a segfault (for the functions # with Cython bounds-checking disabled) or an IndexError. We just run # them to ensure they no longer do. (GH #10228) + warn = None + if isinstance(index, PeriodIndex): + # GH#53511 + index = PeriodIndex([], freq="B", name=index.name) + warn = FutureWarning + msg = "Resampling with a PeriodIndex is deprecated" + empty_series_dti = Series([], index, dtype) - rs = empty_series_dti.resample("d", group_keys=False) + with tm.assert_produces_warning(warn, match=msg): + rs = empty_series_dti.resample("d", group_keys=False) try: getattr(rs, resample_method)() except DataError: @@ -329,8 +378,18 @@ def test_apply_to_empty_series(empty_series_dti, freq): elif freq == "ME" and isinstance(empty_series_dti.index, PeriodIndex): # index is PeriodIndex, so convert to corresponding Period freq freq = "M" - result = ser.resample(freq, group_keys=False).apply(lambda x: 1) - expected = ser.resample(freq).apply("sum") + + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(empty_series_dti.index, PeriodIndex): + warn = FutureWarning + + with tm.assert_produces_warning(warn, match=msg): + rs = ser.resample(freq, group_keys=False) + + result = rs.apply(lambda x: 1) + with tm.assert_produces_warning(warn, match=msg): + expected = ser.resample(freq).apply("sum") tm.assert_series_equal(result, expected, check_dtype=False) @@ -340,8 +399,16 @@ def test_resampler_is_iterable(series): # GH 15314 freq = "h" tg = Grouper(freq=freq, convention="start") - grouped = series.groupby(tg) - resampled = series.resample(freq) + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(series.index, PeriodIndex): + warn = FutureWarning + + with tm.assert_produces_warning(warn, match=msg): + grouped = series.groupby(tg) + + with tm.assert_produces_warning(warn, match=msg): + resampled = series.resample(freq) for (rk, rv), (gk, gv) in zip(resampled, grouped): assert rk == gk tm.assert_series_equal(rv, gv) @@ -353,6 +420,12 @@ def test_resample_quantile(series): ser = series q = 0.75 freq = "h" - result = ser.resample(freq).quantile(q) - expected = ser.resample(freq).agg(lambda x: x.quantile(q)).rename(ser.name) + + msg = "Resampling with a PeriodIndex" + warn = None + if isinstance(series.index, PeriodIndex): + warn = FutureWarning + with tm.assert_produces_warning(warn, match=msg): + result = ser.resample(freq).quantile(q) + expected = ser.resample(freq).agg(lambda x: x.quantile(q)).rename(ser.name) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index a9701b7ecd607..80583f5d3c5f2 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -184,6 +184,9 @@ def test_resample_basic_grouper(series, unit): tm.assert_series_equal(result, expected) +@pytest.mark.filterwarnings( + "ignore:The 'convention' keyword in Series.resample:FutureWarning" +) @pytest.mark.parametrize( "_index_start,_index_end,_index_name", [("1/1/2000 00:00:00", "1/1/2000 00:13:00", "index")], @@ -1055,7 +1058,10 @@ def test_period_with_agg(): ) expected = s2.to_timestamp().resample("D").mean().to_period() - result = s2.resample("D").agg(lambda x: x.mean()) + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = s2.resample("D") + result = rs.agg(lambda x: x.mean()) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 60b222179ba12..a796a06b83dd2 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -30,6 +30,10 @@ from pandas.tseries import offsets +pytestmark = pytest.mark.filterwarnings( + "ignore:Resampling with a PeriodIndex is deprecated:FutureWarning" +) + @pytest.fixture() def _index_factory(): @@ -142,6 +146,9 @@ def test_annual_upsample_cases( ts = simple_period_range_series("1/1/1990", "12/31/1991", freq=f"Y-{month}") warn = FutureWarning if period == "B" else None msg = r"PeriodDtype\[B\] is deprecated" + if warn is None: + msg = "Resampling with a PeriodIndex is deprecated" + warn = FutureWarning with tm.assert_produces_warning(warn, match=msg): result = getattr(ts.resample(period, convention=conv), meth)() expected = result.to_timestamp(period, how=conv) @@ -184,7 +191,9 @@ def test_basic_upsample(self, freq, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "6/30/1995", freq="M") result = ts.resample("Y-DEC").mean() - resampled = result.resample(freq, convention="end").ffill() + msg = "The 'convention' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + resampled = result.resample(freq, convention="end").ffill() expected = result.to_timestamp(freq, how="end") expected = expected.asfreq(freq, "ffill").to_period(freq) tm.assert_series_equal(resampled, expected) @@ -193,7 +202,9 @@ def test_upsample_with_limit(self): rng = period_range("1/1/2000", periods=5, freq="Y") ts = Series(np.random.default_rng(2).standard_normal(len(rng)), rng) - result = ts.resample("M", convention="end").ffill(limit=2) + msg = "The 'convention' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample("M", convention="end").ffill(limit=2) expected = ts.asfreq("M").reindex(result.index, method="ffill", limit=2) tm.assert_series_equal(result, expected) @@ -226,6 +237,9 @@ def test_quarterly_upsample( ts = simple_period_range_series("1/1/1990", "12/31/1995", freq=freq) warn = FutureWarning if period == "B" else None msg = r"PeriodDtype\[B\] is deprecated" + if warn is None: + msg = "Resampling with a PeriodIndex is deprecated" + warn = FutureWarning with tm.assert_produces_warning(warn, match=msg): result = ts.resample(period, convention=convention).ffill() expected = result.to_timestamp(period, how=convention) @@ -239,6 +253,9 @@ def test_monthly_upsample(self, target, convention, simple_period_range_series): warn = None if target == "D" else FutureWarning msg = r"PeriodDtype\[B\] is deprecated" + if warn is None: + msg = "Resampling with a PeriodIndex is deprecated" + warn = FutureWarning with tm.assert_produces_warning(warn, match=msg): result = ts.resample(target, convention=convention).ffill() expected = result.to_timestamp(target, how=convention) @@ -410,6 +427,9 @@ def test_weekly_upsample(self, day, target, convention, simple_period_range_seri warn = None if target == "D" else FutureWarning msg = r"PeriodDtype\[B\] is deprecated" + if warn is None: + msg = "Resampling with a PeriodIndex is deprecated" + warn = FutureWarning with tm.assert_produces_warning(warn, match=msg): result = ts.resample(target, convention=convention).ffill() expected = result.to_timestamp(target, how=convention) @@ -446,7 +466,9 @@ def test_resample_to_quarterly(self, simple_period_range_series, month): def test_resample_to_quarterly_start_end(self, simple_period_range_series, how): # conforms, but different month ts = simple_period_range_series("1990", "1992", freq="Y-JUN") - result = ts.resample("Q-MAR", convention=how).ffill() + msg = "The 'convention' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample("Q-MAR", convention=how).ffill() expected = ts.asfreq("Q-MAR", how=how) expected = expected.reindex(result.index, method="ffill") @@ -494,7 +516,9 @@ def test_upsample_daily_business_daily(self, simple_period_range_series): tm.assert_series_equal(result, expected) ts = simple_period_range_series("1/1/2000", "2/1/2000") - result = ts.resample("h", convention="s").asfreq() + msg = "The 'convention' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample("h", convention="s").asfreq() exp_rng = period_range("1/1/2000", "2/1/2000 23:00", freq="h") expected = ts.asfreq("h", how="s").reindex(exp_rng) tm.assert_series_equal(result, expected) @@ -854,7 +878,10 @@ def test_resample_with_nat(self, periods, values, freq, expected_values): "1970-01-01 00:00:00", periods=len(expected_values), freq=freq ) expected = DataFrame(expected_values, index=expected_index) - result = frame.resample(freq).mean() + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = frame.resample(freq) + result = rs.mean() tm.assert_frame_equal(result, expected) def test_resample_with_only_nat(self): @@ -890,7 +917,10 @@ def test_resample_with_offset(self, start, end, start_freq, end_freq, offset): # GH 23882 & 31809 pi = period_range(start, end, freq=start_freq) ser = Series(np.arange(len(pi)), index=pi) - result = ser.resample(end_freq, offset=offset).mean() + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = ser.resample(end_freq, offset=offset) + result = rs.mean() result = result.to_timestamp(end_freq) expected = ser.to_timestamp().resample(end_freq, offset=offset).mean() @@ -900,7 +930,10 @@ def test_resample_with_offset_month(self): # GH 23882 & 31809 pi = period_range("19910905 12:00", "19910909 1:00", freq="h") ser = Series(np.arange(len(pi)), index=pi) - result = ser.resample("M", offset="3h").mean() + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = ser.resample("M", offset="3h") + result = rs.mean() result = result.to_timestamp("M") expected = ser.to_timestamp().resample("ME", offset="3h").mean() # TODO: is non-tick the relevant characteristic? (GH 33815) @@ -945,7 +978,10 @@ def test_sum_min_count(self): data = np.ones(6) data[3:6] = np.nan s = Series(data, index).to_period() - result = s.resample("Q").sum(min_count=1) + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + rs = s.resample("Q") + result = rs.sum(min_count=1) expected = Series( [3.0, np.nan], index=PeriodIndex(["2018Q1", "2018Q2"], freq="Q-DEC") ) @@ -994,7 +1030,9 @@ def test_corner_cases_period(simple_period_range_series): # miscellaneous test coverage len0pts = simple_period_range_series("2007-01", "2010-05", freq="M")[:0] # it works - result = len0pts.resample("Y-DEC").mean() + msg = "Resampling with a PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = len0pts.resample("Y-DEC").mean() assert len(result) == 0
- [x] closes #53481 (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/55968
2023-11-15T04:24:09Z
2023-12-18T19:32:19Z
2023-12-18T19:32:19Z
2023-12-18T21:00:46Z
TST: Move groupby tests out of test_function
diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 882f42ff18bdd..78b99a00d43ce 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -356,6 +356,12 @@ def test_agg_multiple_functions_maintain_order(df): tm.assert_index_equal(result.columns, exp_cols) +def test_series_index_name(df): + grouped = df.loc[:, ["C"]].groupby(df["A"]) + result = grouped.agg(lambda x: x.mean()) + assert result.index.name == "A" + + def test_agg_multiple_functions_same_name(): # GH 30880 df = DataFrame( diff --git a/pandas/tests/groupby/methods/test_describe.py b/pandas/tests/groupby/methods/test_describe.py index f38de8faddb59..c2ffcb04caa60 100644 --- a/pandas/tests/groupby/methods/test_describe.py +++ b/pandas/tests/groupby/methods/test_describe.py @@ -219,3 +219,73 @@ def test_describe_duplicate_columns(): ) expected.index.names = [1] tm.assert_frame_equal(result, expected) + + +class TestGroupByNonCythonPaths: + # GH#5610 non-cython calls should not include the grouper + # Tests for code not expected to go through cython paths. + + @pytest.fixture + def df(self): + df = DataFrame( + [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], + columns=["A", "B", "C"], + ) + return df + + @pytest.fixture + def gb(self, df): + gb = df.groupby("A") + return gb + + @pytest.fixture + def gni(self, df): + gni = df.groupby("A", as_index=False) + return gni + + def test_describe(self, df, gb, gni): + # describe + expected_index = Index([1, 3], name="A") + expected_col = MultiIndex( + levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], + codes=[[0] * 8, list(range(8))], + ) + expected = DataFrame( + [ + [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], + [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], + ], + index=expected_index, + columns=expected_col, + ) + result = gb.describe() + tm.assert_frame_equal(result, expected) + + expected = expected.reset_index() + result = gni.describe() + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("dtype", [int, float, object]) +@pytest.mark.parametrize( + "kwargs", + [ + {"percentiles": [0.10, 0.20, 0.30], "include": "all", "exclude": None}, + {"percentiles": [0.10, 0.20, 0.30], "include": None, "exclude": ["int"]}, + {"percentiles": [0.10, 0.20, 0.30], "include": ["int"], "exclude": None}, + ], +) +def test_groupby_empty_dataset(dtype, kwargs): + # GH#41575 + df = DataFrame([[1, 2, 3]], columns=["A", "B", "C"], dtype=dtype) + df["B"] = df["B"].astype(int) + df["C"] = df["C"].astype(float) + + result = df.iloc[:0].groupby("A").describe(**kwargs) + expected = df.groupby("A").describe(**kwargs).reset_index(drop=True).iloc[:0] + tm.assert_frame_equal(result, expected) + + result = df.iloc[:0].groupby("A").B.describe(**kwargs) + expected = df.groupby("A").B.describe(**kwargs).reset_index(drop=True).iloc[:0] + expected.index = Index([]) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index 2f2648b9293c5..60b386adb664a 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -1559,3 +1559,45 @@ def test_include_groups(include_groups): if not include_groups: expected = expected[["b"]] tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("f", [max, min, sum]) +@pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key +def test_builtins_apply(keys, f): + # see gh-8155 + rs = np.random.default_rng(2) + df = DataFrame(rs.integers(1, 7, (10, 2)), columns=["jim", "joe"]) + df["jolie"] = rs.standard_normal(10) + + gb = df.groupby(keys) + + fname = f.__name__ + + warn = None if f is not sum else FutureWarning + msg = "The behavior of DataFrame.sum with axis=None is deprecated" + with tm.assert_produces_warning( + warn, match=msg, check_stacklevel=False, raise_on_extra_warnings=False + ): + # Also warns on deprecation GH#53425 + result = gb.apply(f) + ngroups = len(df.drop_duplicates(subset=keys)) + + assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))" + assert result.shape == (ngroups, 3), assert_msg + + npfunc = lambda x: getattr(np, fname)(x, axis=0) # numpy's equivalent function + msg = "DataFrameGroupBy.apply operated on the grouping columns" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = gb.apply(npfunc) + tm.assert_frame_equal(result, expected) + + with tm.assert_produces_warning(FutureWarning, match=msg): + expected2 = gb.apply(lambda x: npfunc(x)) + tm.assert_frame_equal(result, expected2) + + if f != sum: + expected = gb.agg(fname).reset_index() + expected.set_index(keys, inplace=True, drop=False) + tm.assert_frame_equal(result, expected, check_dtype=False) + + tm.assert_series_equal(getattr(result, fname)(axis=0), getattr(df, fname)(axis=0)) diff --git a/pandas/tests/groupby/test_cumulative.py b/pandas/tests/groupby/test_cumulative.py index eecb82cd5050b..25534865b3486 100644 --- a/pandas/tests/groupby/test_cumulative.py +++ b/pandas/tests/groupby/test_cumulative.py @@ -289,3 +289,30 @@ def test_nullable_int_not_cast_as_float(method, dtype, val): expected = DataFrame({"b": data}, dtype=dtype) tm.assert_frame_equal(result, expected) + + +def test_cython_api2(): + # this takes the fast apply path + + # cumsum (GH5614) + df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"]) + expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) + result = df.groupby("A").cumsum() + tm.assert_frame_equal(result, expected) + + # GH 5755 - cumsum is a transformer and should ignore as_index + result = df.groupby("A", as_index=False).cumsum() + tm.assert_frame_equal(result, expected) + + # GH 13994 + msg = "DataFrameGroupBy.cumsum with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").cumsum(axis=1) + expected = df.cumsum(axis=1) + tm.assert_frame_equal(result, expected) + + msg = "DataFrameGroupBy.cumprod with axis=1 is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.groupby("A").cumprod(axis=1) + expected = df.cumprod(axis=1) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index b840443aab347..399ea534ae373 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1,4 +1,3 @@ -import builtins import re import numpy as np @@ -10,73 +9,12 @@ from pandas import ( DataFrame, Index, - MultiIndex, Series, Timestamp, date_range, ) import pandas._testing as tm from pandas.tests.groupby import get_groupby_method_args -from pandas.util import _test_decorators as td - - -def test_intercept_builtin_sum(): - s = Series([1.0, 2.0, np.nan, 3.0]) - grouped = s.groupby([0, 1, 2, 2]) - - msg = "using SeriesGroupBy.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result = grouped.agg(builtins.sum) - msg = "using np.sum" - with tm.assert_produces_warning(FutureWarning, match=msg): - # GH#53425 - result2 = grouped.apply(builtins.sum) - expected = grouped.sum() - tm.assert_series_equal(result, expected) - tm.assert_series_equal(result2, expected) - - -@pytest.mark.parametrize("f", [max, min, sum]) -@pytest.mark.parametrize("keys", ["jim", ["jim", "joe"]]) # Single key # Multi-key -def test_builtins_apply(keys, f): - # see gh-8155 - rs = np.random.default_rng(2) - df = DataFrame(rs.integers(1, 7, (10, 2)), columns=["jim", "joe"]) - df["jolie"] = rs.standard_normal(10) - - gb = df.groupby(keys) - - fname = f.__name__ - - warn = None if f is not sum else FutureWarning - msg = "The behavior of DataFrame.sum with axis=None is deprecated" - with tm.assert_produces_warning( - warn, match=msg, check_stacklevel=False, raise_on_extra_warnings=False - ): - # Also warns on deprecation GH#53425 - result = gb.apply(f) - ngroups = len(df.drop_duplicates(subset=keys)) - - assert_msg = f"invalid frame shape: {result.shape} (expected ({ngroups}, 3))" - assert result.shape == (ngroups, 3), assert_msg - - npfunc = lambda x: getattr(np, fname)(x, axis=0) # numpy's equivalent function - msg = "DataFrameGroupBy.apply operated on the grouping columns" - with tm.assert_produces_warning(FutureWarning, match=msg): - expected = gb.apply(npfunc) - tm.assert_frame_equal(result, expected) - - with tm.assert_produces_warning(FutureWarning, match=msg): - expected2 = gb.apply(lambda x: npfunc(x)) - tm.assert_frame_equal(result, expected2) - - if f != sum: - expected = gb.agg(fname).reset_index() - expected.set_index(keys, inplace=True, drop=False) - tm.assert_frame_equal(result, expected, check_dtype=False) - - tm.assert_series_equal(getattr(result, fname)(axis=0), getattr(df, fname)(axis=0)) class TestNumericOnly: @@ -267,118 +205,6 @@ def _check(self, df, method, expected_columns, expected_columns_numeric): tm.assert_index_equal(result.columns, expected_columns) -class TestGroupByNonCythonPaths: - # GH#5610 non-cython calls should not include the grouper - # Tests for code not expected to go through cython paths. - - @pytest.fixture - def df(self): - df = DataFrame( - [[1, 2, "foo"], [1, np.nan, "bar"], [3, np.nan, "baz"]], - columns=["A", "B", "C"], - ) - return df - - @pytest.fixture - def gb(self, df): - gb = df.groupby("A") - return gb - - @pytest.fixture - def gni(self, df): - gni = df.groupby("A", as_index=False) - return gni - - def test_describe(self, df, gb, gni): - # describe - expected_index = Index([1, 3], name="A") - expected_col = MultiIndex( - levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], - codes=[[0] * 8, list(range(8))], - ) - expected = DataFrame( - [ - [1.0, 2.0, np.nan, 2.0, 2.0, 2.0, 2.0, 2.0], - [0.0, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan], - ], - index=expected_index, - columns=expected_col, - ) - result = gb.describe() - tm.assert_frame_equal(result, expected) - - expected = expected.reset_index() - result = gni.describe() - tm.assert_frame_equal(result, expected) - - -def test_cython_api2(): - # this takes the fast apply path - - # cumsum (GH5614) - df = DataFrame([[1, 2, np.nan], [1, np.nan, 9], [3, 4, 9]], columns=["A", "B", "C"]) - expected = DataFrame([[2, np.nan], [np.nan, 9], [4, 9]], columns=["B", "C"]) - result = df.groupby("A").cumsum() - tm.assert_frame_equal(result, expected) - - # GH 5755 - cumsum is a transformer and should ignore as_index - result = df.groupby("A", as_index=False).cumsum() - tm.assert_frame_equal(result, expected) - - # GH 13994 - msg = "DataFrameGroupBy.cumsum with axis=1 is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby("A").cumsum(axis=1) - expected = df.cumsum(axis=1) - tm.assert_frame_equal(result, expected) - - msg = "DataFrameGroupBy.cumprod with axis=1 is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - result = df.groupby("A").cumprod(axis=1) - expected = df.cumprod(axis=1) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize( - "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"] -) -@pytest.mark.parametrize( - "method,data", - [ - ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), - ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), - ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), - ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), - ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}), - ], -) -def test_groupby_non_arithmetic_agg_types(dtype, method, data): - # GH9311, GH6620 - df = DataFrame( - [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}] - ) - - df["b"] = df.b.astype(dtype) - - if "args" not in data: - data["args"] = [] - - if "out_type" in data: - out_type = data["out_type"] - else: - out_type = dtype - - exp = data["df"] - df_out = DataFrame(exp) - - df_out["b"] = df_out.b.astype(out_type) - df_out.set_index("a", inplace=True) - - grpd = df.groupby("a") - t = getattr(grpd, method)(*data["args"]) - tm.assert_frame_equal(t, df_out) - - @pytest.mark.parametrize( "i", [ @@ -493,78 +319,6 @@ def test_axis1_numeric_only(request, groupby_func, numeric_only): tm.assert_equal(result, expected) -def scipy_sem(*args, **kwargs): - from scipy.stats import sem - - return sem(*args, ddof=1, **kwargs) - - -@pytest.mark.parametrize( - "op,targop", - [ - ("mean", np.mean), - ("median", np.median), - ("std", np.std), - ("var", np.var), - ("sum", np.sum), - ("prod", np.prod), - ("min", np.min), - ("max", np.max), - ("first", lambda x: x.iloc[0]), - ("last", lambda x: x.iloc[-1]), - ("count", np.size), - pytest.param("sem", scipy_sem, marks=td.skip_if_no_scipy), - ], -) -def test_ops_general(op, targop): - df = DataFrame(np.random.default_rng(2).standard_normal(1000)) - labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) - - result = getattr(df.groupby(labels), op)() - warn = None if op in ("first", "last", "count", "sem") else FutureWarning - msg = f"using DataFrameGroupBy.{op}" - with tm.assert_produces_warning(warn, match=msg): - expected = df.groupby(labels).agg(targop) - tm.assert_frame_equal(result, expected) - - -def test_series_index_name(df): - grouped = df.loc[:, ["C"]].groupby(df["A"]) - result = grouped.agg(lambda x: x.mean()) - assert result.index.name == "A" - - -@pytest.mark.parametrize( - "values", - [ - { - "a": [1, 1, 1, 2, 2, 2, 3, 3, 3], - "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2], - }, - {"a": [1, 1, 2, 2, 3, 3], "b": [1, 2, 1, 2, 1, 2]}, - ], -) -@pytest.mark.parametrize("function", ["mean", "median", "var"]) -def test_apply_to_nullable_integer_returns_float(values, function): - # https://github.com/pandas-dev/pandas/issues/32219 - output = 0.5 if function == "var" else 1.5 - arr = np.array([output] * 3, dtype=float) - idx = Index([1, 2, 3], name="a", dtype="Int64") - expected = DataFrame({"b": arr}, index=idx).astype("Float64") - - groups = DataFrame(values, dtype="Int64").groupby("a") - - result = getattr(groups, function)() - tm.assert_frame_equal(result, expected) - - result = groups.agg(function) - tm.assert_frame_equal(result, expected) - - result = groups.agg([function]) - expected.columns = MultiIndex.from_tuples([("b", function)]) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( "kernel, has_arg", [ @@ -781,31 +535,6 @@ def test_deprecate_numeric_only_series(dtype, groupby_func, request): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("dtype", [int, float, object]) -@pytest.mark.parametrize( - "kwargs", - [ - {"percentiles": [0.10, 0.20, 0.30], "include": "all", "exclude": None}, - {"percentiles": [0.10, 0.20, 0.30], "include": None, "exclude": ["int"]}, - {"percentiles": [0.10, 0.20, 0.30], "include": ["int"], "exclude": None}, - ], -) -def test_groupby_empty_dataset(dtype, kwargs): - # GH#41575 - df = DataFrame([[1, 2, 3]], columns=["A", "B", "C"], dtype=dtype) - df["B"] = df["B"].astype(int) - df["C"] = df["C"].astype(float) - - result = df.iloc[:0].groupby("A").describe(**kwargs) - expected = df.groupby("A").describe(**kwargs).reset_index(drop=True).iloc[:0] - tm.assert_frame_equal(result, expected) - - result = df.iloc[:0].groupby("A").B.describe(**kwargs) - expected = df.groupby("A").B.describe(**kwargs).reset_index(drop=True).iloc[:0] - expected.index = Index([]) - tm.assert_frame_equal(result, expected) - - def test_multiindex_group_all_columns_when_empty(groupby_func): # GH 32464 df = DataFrame({"a": [], "b": [], "c": []}).set_index(["a", "b", "c"]) @@ -835,53 +564,3 @@ def test_duplicate_columns(request, groupby_func, as_index): if groupby_func not in ("size", "ngroup", "cumcount"): expected = expected.rename(columns={"c": "b"}) tm.assert_equal(result, expected) - - -@pytest.mark.parametrize( - "op", - [ - "sum", - "prod", - "min", - "max", - "median", - "mean", - "skew", - "std", - "var", - "sem", - ], -) -@pytest.mark.parametrize("axis", [0, 1]) -@pytest.mark.parametrize("skipna", [True, False]) -@pytest.mark.parametrize("sort", [True, False]) -def test_regression_allowlist_methods(op, axis, skipna, sort): - # GH6944 - # GH 17537 - # explicitly test the allowlist methods - raw_frame = DataFrame([0]) - 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" - - with tm.assert_produces_warning(FutureWarning, match=msg): - grouped = frame.groupby(level=0, axis=axis, sort=sort) - - if op == "skew": - # skew has skipna - result = getattr(grouped, op)(skipna=skipna) - expected = frame.groupby(level=0).apply( - lambda h: getattr(h, op)(axis=axis, skipna=skipna) - ) - if sort: - expected = expected.sort_index(axis=axis) - tm.assert_frame_equal(result, expected) - else: - result = getattr(grouped, op)() - expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(axis=axis)) - if sort: - expected = expected.sort_index(axis=axis) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_reductions.py b/pandas/tests/groupby/test_reductions.py index f48926e4d0c77..e5836ce1e61c9 100644 --- a/pandas/tests/groupby/test_reductions.py +++ b/pandas/tests/groupby/test_reductions.py @@ -17,6 +17,7 @@ isna, ) import pandas._testing as tm +from pandas.util import _test_decorators as td @pytest.mark.parametrize("agg_func", ["any", "all"]) @@ -793,6 +794,23 @@ def test_empty_categorical(observed): tm.assert_series_equal(result, expected) +def test_intercept_builtin_sum(): + s = Series([1.0, 2.0, np.nan, 3.0]) + grouped = s.groupby([0, 1, 2, 2]) + + msg = "using SeriesGroupBy.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result = grouped.agg(builtins.sum) + msg = "using np.sum" + with tm.assert_produces_warning(FutureWarning, match=msg): + # GH#53425 + result2 = grouped.apply(builtins.sum) + expected = grouped.sum() + tm.assert_series_equal(result, expected) + tm.assert_series_equal(result2, expected) + + @pytest.mark.parametrize("min_count", [0, 10]) def test_groupby_sum_mincount_boolean(min_count): b = True @@ -853,3 +871,159 @@ def test_groupby_sum_timedelta_with_nat(): res = gb["b"].sum(min_count=2) expected = Series([td3, pd.NaT], dtype="m8[ns]", name="b", index=expected.index) tm.assert_series_equal(res, expected) + + +@pytest.mark.parametrize( + "dtype", ["int8", "int16", "int32", "int64", "float32", "float64", "uint64"] +) +@pytest.mark.parametrize( + "method,data", + [ + ("first", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), + ("last", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), + ("min", {"df": [{"a": 1, "b": 1}, {"a": 2, "b": 3}]}), + ("max", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 4}]}), + ("count", {"df": [{"a": 1, "b": 2}, {"a": 2, "b": 2}], "out_type": "int64"}), + ], +) +def test_groupby_non_arithmetic_agg_types(dtype, method, data): + # GH9311, GH6620 + df = DataFrame( + [{"a": 1, "b": 1}, {"a": 1, "b": 2}, {"a": 2, "b": 3}, {"a": 2, "b": 4}] + ) + + df["b"] = df.b.astype(dtype) + + if "args" not in data: + data["args"] = [] + + if "out_type" in data: + out_type = data["out_type"] + else: + out_type = dtype + + exp = data["df"] + df_out = DataFrame(exp) + + df_out["b"] = df_out.b.astype(out_type) + df_out.set_index("a", inplace=True) + + grpd = df.groupby("a") + t = getattr(grpd, method)(*data["args"]) + tm.assert_frame_equal(t, df_out) + + +def scipy_sem(*args, **kwargs): + from scipy.stats import sem + + return sem(*args, ddof=1, **kwargs) + + +@pytest.mark.parametrize( + "op,targop", + [ + ("mean", np.mean), + ("median", np.median), + ("std", np.std), + ("var", np.var), + ("sum", np.sum), + ("prod", np.prod), + ("min", np.min), + ("max", np.max), + ("first", lambda x: x.iloc[0]), + ("last", lambda x: x.iloc[-1]), + ("count", np.size), + pytest.param("sem", scipy_sem, marks=td.skip_if_no_scipy), + ], +) +def test_ops_general(op, targop): + df = DataFrame(np.random.default_rng(2).standard_normal(1000)) + labels = np.random.default_rng(2).integers(0, 50, size=1000).astype(float) + + result = getattr(df.groupby(labels), op)() + warn = None if op in ("first", "last", "count", "sem") else FutureWarning + msg = f"using DataFrameGroupBy.{op}" + with tm.assert_produces_warning(warn, match=msg): + expected = df.groupby(labels).agg(targop) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "values", + [ + { + "a": [1, 1, 1, 2, 2, 2, 3, 3, 3], + "b": [1, pd.NA, 2, 1, pd.NA, 2, 1, pd.NA, 2], + }, + {"a": [1, 1, 2, 2, 3, 3], "b": [1, 2, 1, 2, 1, 2]}, + ], +) +@pytest.mark.parametrize("function", ["mean", "median", "var"]) +def test_apply_to_nullable_integer_returns_float(values, function): + # https://github.com/pandas-dev/pandas/issues/32219 + output = 0.5 if function == "var" else 1.5 + arr = np.array([output] * 3, dtype=float) + idx = pd.Index([1, 2, 3], name="a", dtype="Int64") + expected = DataFrame({"b": arr}, index=idx).astype("Float64") + + groups = DataFrame(values, dtype="Int64").groupby("a") + + result = getattr(groups, function)() + tm.assert_frame_equal(result, expected) + + result = groups.agg(function) + tm.assert_frame_equal(result, expected) + + result = groups.agg([function]) + expected.columns = MultiIndex.from_tuples([("b", function)]) + tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize( + "op", + [ + "sum", + "prod", + "min", + "max", + "median", + "mean", + "skew", + "std", + "var", + "sem", + ], +) +@pytest.mark.parametrize("axis", [0, 1]) +@pytest.mark.parametrize("skipna", [True, False]) +@pytest.mark.parametrize("sort", [True, False]) +def test_regression_allowlist_methods(op, axis, skipna, sort): + # GH6944 + # GH 17537 + # explicitly test the allowlist methods + raw_frame = DataFrame([0]) + 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" + + with tm.assert_produces_warning(FutureWarning, match=msg): + grouped = frame.groupby(level=0, axis=axis, sort=sort) + + if op == "skew": + # skew has skipna + result = getattr(grouped, op)(skipna=skipna) + expected = frame.groupby(level=0).apply( + lambda h: getattr(h, op)(axis=axis, skipna=skipna) + ) + if sort: + expected = expected.sort_index(axis=axis) + tm.assert_frame_equal(result, expected) + else: + result = getattr(grouped, op)() + expected = frame.groupby(level=0).apply(lambda h: getattr(h, op)(axis=axis)) + if sort: + expected = expected.sort_index(axis=axis) + 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 tests that remain are tests that go across reductions, transformations, and filters. The bulk of these are tests for `numeric_only`
https://api.github.com/repos/pandas-dev/pandas/pulls/55967
2023-11-15T03:41:14Z
2023-11-16T02:20:59Z
2023-11-16T02:20:59Z
2023-11-16T13:20:22Z
TST: collect date_range tests, parametrize over unit
diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index d743442c87fd5..2a1fa20dce777 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -598,17 +598,10 @@ def test_integer_values_and_tz_interpreted_as_utc(self): # but UTC is *not* deprecated. with tm.assert_produces_warning(None): result = DatetimeIndex(values, tz="UTC") - expected = DatetimeIndex(["2000-01-01T00:00:00"], tz="US/Central") + expected = DatetimeIndex(["2000-01-01T00:00:00"], tz="UTC") + tm.assert_index_equal(result, expected) def test_constructor_coverage(self): - rng = date_range("1/1/2000", periods=10.5) - exp = date_range("1/1/2000", periods=10) - tm.assert_index_equal(rng, exp) - - msg = "periods must be a number, got foo" - with pytest.raises(TypeError, match=msg): - date_range(start="1/1/2000", periods="foo", freq="D") - msg = r"DatetimeIndex\(\.\.\.\) must be called with a collection" with pytest.raises(TypeError, match=msg): DatetimeIndex("1/1/2000") @@ -647,17 +640,6 @@ def test_constructor_coverage(self): with pytest.raises(ValueError, match=msg): DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-04"], freq="D") - msg = ( - "Of the four parameters: start, end, periods, and freq, exactly " - "three must be specified" - ) - with pytest.raises(ValueError, match=msg): - date_range(start="2011-01-01", freq="b") - with pytest.raises(ValueError, match=msg): - date_range(end="2011-01-01", freq="B") - with pytest.raises(ValueError, match=msg): - date_range(periods=10, freq="D") - @pytest.mark.parametrize("freq", ["YS", "W-SUN"]) def test_constructor_datetime64_tzformat(self, freq): # see GH#6572: ISO 8601 format results in stdlib timezone object @@ -762,10 +744,6 @@ def test_constructor_invalid_dtype_raises(self, dtype): with pytest.raises(ValueError, match=msg): DatetimeIndex([1, 2], dtype=dtype) - def test_constructor_name(self): - idx = date_range(start="2000-01-01", periods=1, freq="YE", name="TEST") - assert idx.name == "TEST" - def test_000constructor_resolution(self): # 2252 t1 = Timestamp((1352934390 * 1000000000) + 1000000 + 1000 + 1) @@ -921,9 +899,7 @@ def test_constructor_with_nonexistent_keyword_arg(self, warsaw): tm.assert_index_equal(result, expected) # nonexistent keyword in end - end = Timestamp("2015-03-29 02:30:00").tz_localize( - timezone, nonexistent="shift_forward" - ) + end = start result = date_range(end=end, periods=2, freq="h") expected = DatetimeIndex( [ diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index b1b4e738a6365..3a6d1cacd0f81 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -43,6 +43,8 @@ fixed_off_no_name, ) +from pandas.tseries.holiday import USFederalHolidayCalendar + START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) @@ -128,6 +130,21 @@ def test_date_range_timestamp_equiv_preserve_frequency(self): class TestDateRanges: + def test_date_range_name(self): + idx = date_range(start="2000-01-01", periods=1, freq="YE", name="TEST") + assert idx.name == "TEST" + + def test_date_range_invalid_periods(self): + msg = "periods must be a number, got foo" + with pytest.raises(TypeError, match=msg): + date_range(start="1/1/2000", periods="foo", freq="D") + + def test_date_range_float_periods(self): + # TODO: reconsider allowing this? + rng = date_range("1/1/2000", periods=10.5) + exp = date_range("1/1/2000", periods=10) + tm.assert_index_equal(rng, exp) + def test_date_range_frequency_M_deprecated(self): depr_msg = "'M' will be deprecated, please use 'ME' instead." @@ -261,50 +278,6 @@ def test_date_range_gen_error(self): rng = date_range("1/1/2000 00:00", "1/1/2000 00:18", freq="5min") assert len(rng) == 4 - def test_begin_year_alias(self): - # see gh-9313 - rng = date_range("1/1/2013", "7/1/2017", freq="YS") - exp = DatetimeIndex( - ["2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01", "2017-01-01"], - freq="YS", - ) - tm.assert_index_equal(rng, exp) - - def test_end_year_alias(self): - # see gh-9313 - rng = date_range("1/1/2013", "7/1/2017", freq="YE") - exp = DatetimeIndex( - ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-31"], freq="YE" - ) - tm.assert_index_equal(rng, exp) - - def test_business_end_year_alias(self): - # see gh-9313 - rng = date_range("1/1/2013", "7/1/2017", freq="BY") - exp = DatetimeIndex( - ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-30"], freq="BY" - ) - tm.assert_index_equal(rng, exp) - - def test_date_range_negative_freq(self): - # GH 11018 - rng = date_range("2011-12-31", freq="-2YE", periods=3) - exp = DatetimeIndex(["2011-12-31", "2009-12-31", "2007-12-31"], freq="-2YE") - tm.assert_index_equal(rng, exp) - assert rng.freq == "-2YE" - - rng = date_range("2011-01-31", freq="-2ME", periods=3) - exp = DatetimeIndex(["2011-01-31", "2010-11-30", "2010-09-30"], freq="-2ME") - tm.assert_index_equal(rng, exp) - assert rng.freq == "-2ME" - - def test_date_range_bms_bug(self): - # #1645 - rng = date_range("1/1/2000", periods=10, freq="BMS") - - ex_first = Timestamp("2000-01-03") - assert rng[0] == ex_first - def test_date_range_normalize(self): snap = datetime.today() n = 50 @@ -321,15 +294,6 @@ def test_date_range_normalize(self): for val in rng: assert val.time() == the_time - def test_date_range_fy5252(self): - dr = date_range( - start="2013-01-01", - periods=2, - freq=offsets.FY5253(startingMonth=1, weekday=3, variation="nearest"), - ) - assert dr[0] == Timestamp("2013-01-31") - assert dr[1] == Timestamp("2014-01-30") - def test_date_range_ambiguous_arguments(self): # #2538 start = datetime(2011, 1, 1, 5, 3, 40) @@ -420,65 +384,6 @@ def test_date_range_linspacing_tz(self, start, end, result_tz): expected = date_range("20180101", periods=3, freq="D", tz="US/Eastern") tm.assert_index_equal(result, expected) - def test_date_range_businesshour(self): - idx = DatetimeIndex( - [ - "2014-07-04 09:00", - "2014-07-04 10:00", - "2014-07-04 11:00", - "2014-07-04 12:00", - "2014-07-04 13:00", - "2014-07-04 14:00", - "2014-07-04 15:00", - "2014-07-04 16:00", - ], - freq="bh", - ) - rng = date_range("2014-07-04 09:00", "2014-07-04 16:00", freq="bh") - tm.assert_index_equal(idx, rng) - - idx = DatetimeIndex(["2014-07-04 16:00", "2014-07-07 09:00"], freq="bh") - rng = date_range("2014-07-04 16:00", "2014-07-07 09:00", freq="bh") - tm.assert_index_equal(idx, rng) - - idx = DatetimeIndex( - [ - "2014-07-04 09:00", - "2014-07-04 10:00", - "2014-07-04 11:00", - "2014-07-04 12:00", - "2014-07-04 13:00", - "2014-07-04 14:00", - "2014-07-04 15:00", - "2014-07-04 16:00", - "2014-07-07 09:00", - "2014-07-07 10:00", - "2014-07-07 11:00", - "2014-07-07 12:00", - "2014-07-07 13:00", - "2014-07-07 14:00", - "2014-07-07 15:00", - "2014-07-07 16:00", - "2014-07-08 09:00", - "2014-07-08 10:00", - "2014-07-08 11:00", - "2014-07-08 12:00", - "2014-07-08 13:00", - "2014-07-08 14:00", - "2014-07-08 15:00", - "2014-07-08 16:00", - ], - freq="bh", - ) - rng = date_range("2014-07-04 09:00", "2014-07-08 16:00", freq="bh") - tm.assert_index_equal(idx, rng) - - def test_date_range_business_hour_short(self, unit): - # GH#49835 - idx4 = date_range(start="2014-07-01 10:00", freq="bh", periods=1, unit=unit) - expected4 = DatetimeIndex(["2014-07-01 10:00"], freq="bh").as_unit(unit) - tm.assert_index_equal(idx4, expected4) - def test_date_range_timedelta(self): start = "2020-01-01" end = "2020-01-11" @@ -527,12 +432,6 @@ def test_catch_infinite_loop(self): with pytest.raises(ValueError, match=msg): date_range(datetime(2011, 11, 11), datetime(2011, 11, 12), freq=offset) - @pytest.mark.parametrize("periods", (1, 2)) - def test_wom_len(self, periods): - # https://github.com/pandas-dev/pandas/issues/20517 - res = date_range(start="20110101", periods=periods, freq="WOM-1MON") - assert len(res) == periods - def test_construct_over_dst(self): # GH 20854 pre_dst = Timestamp("2010-11-07 01:00:00").tz_localize( @@ -661,37 +560,19 @@ def test_range_tz_dateutil(self): assert dr[2] == end @pytest.mark.parametrize("freq", ["1D", "3D", "2ME", "7W", "3h", "YE"]) - def test_range_closed(self, freq, inclusive_endpoints_fixture): - begin = datetime(2011, 1, 1) - end = datetime(2014, 1, 1) - - result_range = date_range( - begin, end, inclusive=inclusive_endpoints_fixture, freq=freq - ) - both_range = date_range(begin, end, inclusive="both", freq=freq) - expected_range = _get_expected_range( - begin, end, both_range, inclusive_endpoints_fixture - ) + @pytest.mark.parametrize("tz", [None, "US/Eastern"]) + def test_range_closed(self, freq, tz, inclusive_endpoints_fixture): + # GH#12409, GH#12684 - tm.assert_index_equal(expected_range, result_range) - - @pytest.mark.parametrize("freq", ["1D", "3D", "2ME", "7W", "3h", "YE"]) - def test_range_closed_with_tz_aware_start_end( - self, freq, inclusive_endpoints_fixture - ): - # GH12409, GH12684 - begin = Timestamp("2011/1/1", tz="US/Eastern") - end = Timestamp("2014/1/1", tz="US/Eastern") + begin = Timestamp("2011/1/1", tz=tz) + end = Timestamp("2014/1/1", tz=tz) result_range = date_range( begin, end, inclusive=inclusive_endpoints_fixture, freq=freq ) both_range = date_range(begin, end, inclusive="both", freq=freq) expected_range = _get_expected_range( - begin, - end, - both_range, - inclusive_endpoints_fixture, + begin, end, both_range, inclusive_endpoints_fixture ) tm.assert_index_equal(expected_range, result_range) @@ -912,33 +793,13 @@ def test_frequencies_A_deprecated_Y_renamed(self, freq, freq_depr): result = date_range("1/1/2000", periods=2, freq=freq_depr) tm.assert_index_equal(result, expected) - def test_date_range_misc(self): + def test_date_range_bday(self): sdate = datetime(1999, 12, 25) - edate = datetime(2000, 1, 1) idx = date_range(start=sdate, freq="1B", periods=20) assert len(idx) == 20 assert idx[0] == sdate + 0 * offsets.BDay() assert idx.freq == "B" - idx1 = date_range(start=sdate, end=edate, freq="W-SUN") - idx2 = date_range(start=sdate, end=edate, freq=offsets.Week(weekday=6)) - assert len(idx1) == len(idx2) - assert idx1.freq == idx2.freq - - idx1 = date_range(start=sdate, end=edate, freq="QS") - idx2 = date_range( - start=sdate, end=edate, freq=offsets.QuarterBegin(startingMonth=1) - ) - assert len(idx1) == len(idx2) - assert idx1.freq == idx2.freq - - idx1 = date_range(start=sdate, end=edate, freq="BQ") - idx2 = date_range( - start=sdate, end=edate, freq=offsets.BQuarterEnd(startingMonth=12) - ) - assert len(idx1) == len(idx2) - assert idx1.freq == idx2.freq - class TestDateRangeTZ: """Tests for date_range with timezones""" @@ -1045,14 +906,16 @@ def test_date_range_nonexistent_endpoint(self, tz, option, expected): class TestGenRangeGeneration: - def test_generate(self): - rng1 = list(generate_range(START, END, periods=None, offset=BDay(), unit="ns")) - rng2 = list(generate_range(START, END, periods=None, offset="B", unit="ns")) - assert rng1 == rng2 - - def test_generate_cday(self): - rng1 = list(generate_range(START, END, periods=None, offset=CDay(), unit="ns")) - rng2 = list(generate_range(START, END, periods=None, offset="C", unit="ns")) + @pytest.mark.parametrize( + "freqstr,offset", + [ + ("B", BDay()), + ("C", CDay()), + ], + ) + def test_generate(self, freqstr, offset): + rng1 = list(generate_range(START, END, periods=None, offset=offset, unit="ns")) + rng2 = list(generate_range(START, END, periods=None, offset=freqstr, unit="ns")) assert rng1 == rng2 def test_1(self): @@ -1375,22 +1238,6 @@ def test_range_with_timezone_and_custombusinessday(self, start, period, expected tm.assert_index_equal(result, expected) -def test_date_range_with_custom_holidays(): - # GH 30593 - freq = offsets.CustomBusinessHour(start="15:00", holidays=["2020-11-26"]) - result = date_range(start="2020-11-25 15:00", periods=4, freq=freq) - expected = DatetimeIndex( - [ - "2020-11-25 15:00:00", - "2020-11-25 16:00:00", - "2020-11-27 15:00:00", - "2020-11-27 16:00:00", - ], - freq=freq, - ) - tm.assert_index_equal(result, expected) - - class TestDateRangeNonNano: def test_date_range_reso_validation(self): msg = "'unit' must be one of 's', 'ms', 'us', 'ns'" @@ -1455,3 +1302,358 @@ def test_date_range_non_nano(self): ).view("M8[s]") tm.assert_numpy_array_equal(dti.to_numpy(), exp) + + +class TestDateRangeNonTickFreq: + # Tests revolving around less-common (non-Tick) `freq` keywords. + + def test_date_range_custom_business_month_begin(self, unit): + hcal = USFederalHolidayCalendar() + freq = offsets.CBMonthBegin(calendar=hcal) + dti = date_range(start="20120101", end="20130101", freq=freq, unit=unit) + assert all(freq.is_on_offset(x) for x in dti) + + expected = DatetimeIndex( + [ + "2012-01-03", + "2012-02-01", + "2012-03-01", + "2012-04-02", + "2012-05-01", + "2012-06-01", + "2012-07-02", + "2012-08-01", + "2012-09-04", + "2012-10-01", + "2012-11-01", + "2012-12-03", + ], + dtype=f"M8[{unit}]", + freq=freq, + ) + tm.assert_index_equal(dti, expected) + + def test_date_range_custom_business_month_end(self, unit): + hcal = USFederalHolidayCalendar() + freq = offsets.CBMonthEnd(calendar=hcal) + dti = date_range(start="20120101", end="20130101", freq=freq, unit=unit) + assert all(freq.is_on_offset(x) for x in dti) + + expected = DatetimeIndex( + [ + "2012-01-31", + "2012-02-29", + "2012-03-30", + "2012-04-30", + "2012-05-31", + "2012-06-29", + "2012-07-31", + "2012-08-31", + "2012-09-28", + "2012-10-31", + "2012-11-30", + "2012-12-31", + ], + dtype=f"M8[{unit}]", + freq=freq, + ) + tm.assert_index_equal(dti, expected) + + def test_date_range_with_custom_holidays(self, unit): + # GH#30593 + freq = offsets.CustomBusinessHour(start="15:00", holidays=["2020-11-26"]) + result = date_range(start="2020-11-25 15:00", periods=4, freq=freq, unit=unit) + expected = DatetimeIndex( + [ + "2020-11-25 15:00:00", + "2020-11-25 16:00:00", + "2020-11-27 15:00:00", + "2020-11-27 16:00:00", + ], + dtype=f"M8[{unit}]", + freq=freq, + ) + tm.assert_index_equal(result, expected) + + def test_date_range_businesshour(self, unit): + idx = DatetimeIndex( + [ + "2014-07-04 09:00", + "2014-07-04 10:00", + "2014-07-04 11:00", + "2014-07-04 12:00", + "2014-07-04 13:00", + "2014-07-04 14:00", + "2014-07-04 15:00", + "2014-07-04 16:00", + ], + dtype=f"M8[{unit}]", + freq="bh", + ) + rng = date_range("2014-07-04 09:00", "2014-07-04 16:00", freq="bh", unit=unit) + tm.assert_index_equal(idx, rng) + + idx = DatetimeIndex( + ["2014-07-04 16:00", "2014-07-07 09:00"], dtype=f"M8[{unit}]", freq="bh" + ) + rng = date_range("2014-07-04 16:00", "2014-07-07 09:00", freq="bh", unit=unit) + tm.assert_index_equal(idx, rng) + + idx = DatetimeIndex( + [ + "2014-07-04 09:00", + "2014-07-04 10:00", + "2014-07-04 11:00", + "2014-07-04 12:00", + "2014-07-04 13:00", + "2014-07-04 14:00", + "2014-07-04 15:00", + "2014-07-04 16:00", + "2014-07-07 09:00", + "2014-07-07 10:00", + "2014-07-07 11:00", + "2014-07-07 12:00", + "2014-07-07 13:00", + "2014-07-07 14:00", + "2014-07-07 15:00", + "2014-07-07 16:00", + "2014-07-08 09:00", + "2014-07-08 10:00", + "2014-07-08 11:00", + "2014-07-08 12:00", + "2014-07-08 13:00", + "2014-07-08 14:00", + "2014-07-08 15:00", + "2014-07-08 16:00", + ], + dtype=f"M8[{unit}]", + freq="bh", + ) + rng = date_range("2014-07-04 09:00", "2014-07-08 16:00", freq="bh", unit=unit) + tm.assert_index_equal(idx, rng) + + def test_date_range_business_hour2(self, unit): + idx1 = date_range( + start="2014-07-04 15:00", end="2014-07-08 10:00", freq="bh", unit=unit + ) + idx2 = date_range(start="2014-07-04 15:00", periods=12, freq="bh", unit=unit) + idx3 = date_range(end="2014-07-08 10:00", periods=12, freq="bh", unit=unit) + expected = DatetimeIndex( + [ + "2014-07-04 15:00", + "2014-07-04 16:00", + "2014-07-07 09:00", + "2014-07-07 10:00", + "2014-07-07 11:00", + "2014-07-07 12:00", + "2014-07-07 13:00", + "2014-07-07 14:00", + "2014-07-07 15:00", + "2014-07-07 16:00", + "2014-07-08 09:00", + "2014-07-08 10:00", + ], + dtype=f"M8[{unit}]", + freq="bh", + ) + tm.assert_index_equal(idx1, expected) + tm.assert_index_equal(idx2, expected) + tm.assert_index_equal(idx3, expected) + + idx4 = date_range( + start="2014-07-04 15:45", end="2014-07-08 10:45", freq="bh", unit=unit + ) + idx5 = date_range(start="2014-07-04 15:45", periods=12, freq="bh", unit=unit) + idx6 = date_range(end="2014-07-08 10:45", periods=12, freq="bh", unit=unit) + + expected2 = expected + Timedelta(minutes=45).as_unit(unit) + expected2.freq = "bh" + tm.assert_index_equal(idx4, expected2) + tm.assert_index_equal(idx5, expected2) + tm.assert_index_equal(idx6, expected2) + + def test_date_range_business_hour_short(self, unit): + # GH#49835 + idx4 = date_range(start="2014-07-01 10:00", freq="bh", periods=1, unit=unit) + expected4 = DatetimeIndex(["2014-07-01 10:00"], dtype=f"M8[{unit}]", freq="bh") + tm.assert_index_equal(idx4, expected4) + + def test_date_range_year_start(self, unit): + # see GH#9313 + rng = date_range("1/1/2013", "7/1/2017", freq="YS", unit=unit) + exp = DatetimeIndex( + ["2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01", "2017-01-01"], + dtype=f"M8[{unit}]", + freq="YS", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_year_end(self, unit): + # see GH#9313 + rng = date_range("1/1/2013", "7/1/2017", freq="YE", unit=unit) + exp = DatetimeIndex( + ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-31"], + dtype=f"M8[{unit}]", + freq="YE", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_negative_freq_year_end(self, unit): + # GH#11018 + rng = date_range("2011-12-31", freq="-2YE", periods=3, unit=unit) + exp = DatetimeIndex( + ["2011-12-31", "2009-12-31", "2007-12-31"], dtype=f"M8[{unit}]", freq="-2YE" + ) + tm.assert_index_equal(rng, exp) + assert rng.freq == "-2YE" + + def test_date_range_business_year_end_year(self, unit): + # see GH#9313 + rng = date_range("1/1/2013", "7/1/2017", freq="BY", unit=unit) + exp = DatetimeIndex( + ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-30"], + dtype=f"M8[{unit}]", + freq="BY", + ) + tm.assert_index_equal(rng, exp) + + def test_date_range_bms(self, unit): + # GH#1645 + result = date_range("1/1/2000", periods=10, freq="BMS", unit=unit) + + expected = DatetimeIndex( + [ + "2000-01-03", + "2000-02-01", + "2000-03-01", + "2000-04-03", + "2000-05-01", + "2000-06-01", + "2000-07-03", + "2000-08-01", + "2000-09-01", + "2000-10-02", + ], + dtype=f"M8[{unit}]", + freq="BMS", + ) + tm.assert_index_equal(result, expected) + + def test_date_range_semi_month_begin(self, unit): + dates = [ + datetime(2007, 12, 15), + datetime(2008, 1, 1), + datetime(2008, 1, 15), + datetime(2008, 2, 1), + datetime(2008, 2, 15), + datetime(2008, 3, 1), + datetime(2008, 3, 15), + datetime(2008, 4, 1), + datetime(2008, 4, 15), + datetime(2008, 5, 1), + datetime(2008, 5, 15), + datetime(2008, 6, 1), + datetime(2008, 6, 15), + datetime(2008, 7, 1), + datetime(2008, 7, 15), + datetime(2008, 8, 1), + datetime(2008, 8, 15), + datetime(2008, 9, 1), + datetime(2008, 9, 15), + datetime(2008, 10, 1), + datetime(2008, 10, 15), + datetime(2008, 11, 1), + datetime(2008, 11, 15), + datetime(2008, 12, 1), + datetime(2008, 12, 15), + ] + # ensure generating a range with DatetimeIndex gives same result + result = date_range(start=dates[0], end=dates[-1], freq="SMS", unit=unit) + exp = DatetimeIndex(dates, dtype=f"M8[{unit}]", freq="SMS") + tm.assert_index_equal(result, exp) + + def test_date_range_semi_month_end(self, unit): + dates = [ + datetime(2007, 12, 31), + datetime(2008, 1, 15), + datetime(2008, 1, 31), + datetime(2008, 2, 15), + datetime(2008, 2, 29), + datetime(2008, 3, 15), + datetime(2008, 3, 31), + datetime(2008, 4, 15), + datetime(2008, 4, 30), + datetime(2008, 5, 15), + datetime(2008, 5, 31), + datetime(2008, 6, 15), + datetime(2008, 6, 30), + datetime(2008, 7, 15), + datetime(2008, 7, 31), + datetime(2008, 8, 15), + datetime(2008, 8, 31), + datetime(2008, 9, 15), + datetime(2008, 9, 30), + datetime(2008, 10, 15), + datetime(2008, 10, 31), + datetime(2008, 11, 15), + datetime(2008, 11, 30), + datetime(2008, 12, 15), + datetime(2008, 12, 31), + ] + # ensure generating a range with DatetimeIndex gives same result + result = date_range(start=dates[0], end=dates[-1], freq="SM", unit=unit) + exp = DatetimeIndex(dates, dtype=f"M8[{unit}]", freq="SM") + tm.assert_index_equal(result, exp) + + def test_date_range_week_of_month(self, unit): + # GH#20517 + # Note the start here is not on_offset for this freq + result = date_range(start="20110101", periods=1, freq="WOM-1MON", unit=unit) + expected = DatetimeIndex(["2011-01-03"], dtype=f"M8[{unit}]", freq="WOM-1MON") + tm.assert_index_equal(result, expected) + + result2 = date_range(start="20110101", periods=2, freq="WOM-1MON", unit=unit) + expected2 = DatetimeIndex( + ["2011-01-03", "2011-02-07"], dtype=f"M8[{unit}]", freq="WOM-1MON" + ) + tm.assert_index_equal(result2, expected2) + + def test_date_range_negative_freq_month_end(self, unit): + # GH#11018 + rng = date_range("2011-01-31", freq="-2ME", periods=3, unit=unit) + exp = DatetimeIndex( + ["2011-01-31", "2010-11-30", "2010-09-30"], dtype=f"M8[{unit}]", freq="-2ME" + ) + tm.assert_index_equal(rng, exp) + assert rng.freq == "-2ME" + + def test_date_range_fy5253(self, unit): + freq = offsets.FY5253(startingMonth=1, weekday=3, variation="nearest") + dti = date_range( + start="2013-01-01", + periods=2, + freq=freq, + unit=unit, + ) + expected = DatetimeIndex( + ["2013-01-31", "2014-01-30"], dtype=f"M8[{unit}]", freq=freq + ) + + tm.assert_index_equal(dti, expected) + + @pytest.mark.parametrize( + "freqstr,offset", + [ + ("QS", offsets.QuarterBegin(startingMonth=1)), + ("BQ", offsets.BQuarterEnd(startingMonth=12)), + ("W-SUN", offsets.Week(weekday=6)), + ], + ) + def test_date_range_freqstr_matches_offset(self, freqstr, offset): + sdate = datetime(1999, 12, 25) + edate = datetime(2000, 1, 1) + + idx1 = date_range(start=sdate, end=edate, freq=freqstr) + idx2 = date_range(start=sdate, end=edate, freq=offset) + assert len(idx1) == len(idx2) + assert idx1.freq == idx2.freq diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py index 227cf6a495c91..2779100f5355c 100644 --- a/pandas/tests/tseries/offsets/test_business_hour.py +++ b/pandas/tests/tseries/offsets/test_business_hour.py @@ -946,38 +946,6 @@ def test_apply_nanoseconds(self): for base, expected in cases.items(): assert_offset_equal(offset, base, expected) - def test_datetimeindex(self): - idx1 = date_range(start="2014-07-04 15:00", end="2014-07-08 10:00", freq="bh") - idx2 = date_range(start="2014-07-04 15:00", periods=12, freq="bh") - idx3 = date_range(end="2014-07-08 10:00", periods=12, freq="bh") - expected = DatetimeIndex( - [ - "2014-07-04 15:00", - "2014-07-04 16:00", - "2014-07-07 09:00", - "2014-07-07 10:00", - "2014-07-07 11:00", - "2014-07-07 12:00", - "2014-07-07 13:00", - "2014-07-07 14:00", - "2014-07-07 15:00", - "2014-07-07 16:00", - "2014-07-08 09:00", - "2014-07-08 10:00", - ], - freq="bh", - ) - for idx in [idx1, idx2, idx3]: - tm.assert_index_equal(idx, expected) - - idx1 = date_range(start="2014-07-04 15:45", end="2014-07-08 10:45", freq="bh") - idx2 = date_range(start="2014-07-04 15:45", periods=12, freq="bh") - idx3 = date_range(end="2014-07-08 10:45", periods=12, freq="bh") - - expected = idx1 - for idx in [idx1, idx2, idx3]: - tm.assert_index_equal(idx, expected) - @pytest.mark.parametrize("td_unit", ["s", "ms", "us", "ns"]) @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) def test_bday_ignores_timedeltas(self, unit, td_unit): diff --git a/pandas/tests/tseries/offsets/test_custom_business_month.py b/pandas/tests/tseries/offsets/test_custom_business_month.py index 0fff99ff8c025..d226302e042d3 100644 --- a/pandas/tests/tseries/offsets/test_custom_business_month.py +++ b/pandas/tests/tseries/offsets/test_custom_business_month.py @@ -21,17 +21,13 @@ CDay, ) -from pandas import ( - _testing as tm, - date_range, -) +import pandas._testing as tm from pandas.tests.tseries.offsets.common import ( assert_is_on_offset, assert_offset_equal, ) from pandas.tseries import offsets -from pandas.tseries.holiday import USFederalHolidayCalendar @pytest.fixture @@ -201,14 +197,6 @@ def test_holidays(self): assert dt + bm_offset == datetime(2012, 1, 2) assert dt + 2 * bm_offset == datetime(2012, 2, 3) - @pytest.mark.filterwarnings("ignore:Non:pandas.errors.PerformanceWarning") - def test_datetimeindex(self): - hcal = USFederalHolidayCalendar() - cbmb = CBMonthBegin(calendar=hcal) - assert date_range(start="20120101", end="20130101", freq=cbmb).tolist()[ - 0 - ] == datetime(2012, 1, 3) - @pytest.mark.parametrize( "case", [ @@ -397,15 +385,6 @@ def test_holidays(self): assert dt + bm_offset == datetime(2012, 1, 30) assert dt + 2 * bm_offset == datetime(2012, 2, 27) - @pytest.mark.filterwarnings("ignore:Non:pandas.errors.PerformanceWarning") - def test_datetimeindex(self): - hcal = USFederalHolidayCalendar() - freq = CBMonthEnd(calendar=hcal) - - assert date_range(start="20120101", end="20130101", freq=freq).tolist()[ - 0 - ] == datetime(2012, 1, 31) - @pytest.mark.parametrize( "case", [ diff --git a/pandas/tests/tseries/offsets/test_month.py b/pandas/tests/tseries/offsets/test_month.py index fc12510369245..2b643999c3ad3 100644 --- a/pandas/tests/tseries/offsets/test_month.py +++ b/pandas/tests/tseries/offsets/test_month.py @@ -23,7 +23,6 @@ DatetimeIndex, Series, _testing as tm, - date_range, ) from pandas.tests.tseries.offsets.common import ( assert_is_on_offset, @@ -74,11 +73,6 @@ def test_offset_whole_year(self): exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) - # ensure generating a range with DatetimeIndex gives same result - result = date_range(start=dates[0], end=dates[-1], freq="SM") - exp = DatetimeIndex(dates, freq="SM") - tm.assert_index_equal(result, exp) - offset_cases = [] offset_cases.append( ( @@ -330,11 +324,6 @@ def test_offset_whole_year(self): exp = DatetimeIndex(dates[1:]) tm.assert_index_equal(result, exp) - # ensure generating a range with DatetimeIndex gives same result - result = date_range(start=dates[0], end=dates[-1], freq="SMS") - exp = DatetimeIndex(dates, freq="SMS") - tm.assert_index_equal(result, exp) - offset_cases = [ ( SemiMonthBegin(),
- [ ] 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/55966
2023-11-15T02:33:16Z
2023-11-15T03:57:46Z
2023-11-15T03:57:45Z
2023-11-15T04:13:55Z
Updates to check the dtypes instead
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 2a1503b84a634..a322e83f5f501 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -924,7 +924,9 @@ def plt(self): @final def _get_xticks(self): index = self.data.index - is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time") + is_datetype = self.data.dtypes.isin( + ["datetime64[ns]", "datetime", "date", "time"] + ).any() # TODO: be stricter about x? x: list[int] | np.ndarray @@ -1247,9 +1249,14 @@ def __init__(self, data, x, y, **kwargs) -> None: MPLPlot.__init__(self, data, **kwargs) if x is None or y is None: raise ValueError(self._kind + " requires an x and y column") - if is_integer(x) and not self.data.columns._holds_integer(): + if self.data.columns._holds_integer(): + raise Warning( + """_holds_integer is deprecated and may be removed in a future version. + Please cast to a int dtype before plotting.""" + ) + if is_integer(x) and not is_integer_dtype(self.data.columns): x = self.data.columns[x] - if is_integer(y) and not self.data.columns._holds_integer(): + if is_integer(y) and not is_integer_dtype(self.data.columns): y = self.data.columns[y] self.x = x @@ -1319,7 +1326,12 @@ def __init__( self.norm = norm super().__init__(data, x, y, **kwargs) - if is_integer(c) and not self.data.columns._holds_integer(): + if self.data.columns._holds_integer(): + raise Warning( + """_holds_integer is deprecated and may be removed in a future version. + Please cast to a int dtype before plotting.""" + ) + if is_integer(c) and not is_integer_dtype(self.data.columns): c = self.data.columns[c] self.c = c @@ -1435,7 +1447,12 @@ def _kind(self) -> Literal["hexbin"]: def __init__(self, data, x, y, C=None, *, colorbar: bool = True, **kwargs) -> None: super().__init__(data, x, y, **kwargs) - if is_integer(C) and not self.data.columns._holds_integer(): + if self.data.columns._holds_integer(): + raise Warning( + """_holds_integer is deprecated and may be removed in a future version. + Please cast to a int dtype before plotting.""" + ) + if is_integer(C) and not is_integer_dtype(self.data.columns): C = self.data.columns[C] self.C = C
- [x] closes #55897 - [ ] [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/55965
2023-11-15T01:34:36Z
2023-12-27T19:12:29Z
null
2023-12-27T19:12:30Z
DEPR: PeriodIndex ordinal, fields keywords
diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index 25e5b3b46b4f3..fa6105761df0a 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -489,3 +489,5 @@ Methods PeriodIndex.asfreq PeriodIndex.strftime PeriodIndex.to_timestamp + PeriodIndex.from_fields + PeriodIndex.from_ordinals diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 9040dba238c88..48aee18c90456 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -264,6 +264,7 @@ Other Deprecations - Changed :meth:`Timedelta.resolution_string` to return ``h``, ``min``, ``s``, ``ms``, ``us``, and ``ns`` instead of ``H``, ``T``, ``S``, ``L``, ``U``, and ``N``, for compatibility with respective deprecations in frequency aliases (:issue:`52536`) - Deprecated :func:`read_gbq` and :meth:`DataFrame.to_gbq`. Use ``pandas_gbq.read_gbq`` and ``pandas_gbq.to_gbq`` instead https://pandas-gbq.readthedocs.io/en/latest/api.html (:issue:`55525`) - Deprecated :meth:`Index.format`, use ``index.astype(str)`` or ``index.map(formatter)`` instead (:issue:`55413`) +- Deprecated ``year``, ``month``, ``quarter``, ``day``, ``hour``, ``minute``, and ``second`` keywords in the :class:`PeriodIndex` constructor, use :meth:`PeriodIndex.from_fields` instead (:issue:`55960`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_clipboard`. (:issue:`54229`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_csv` except ``path_or_buf``. (:issue:`54229`) - Deprecated allowing non-keyword arguments in :meth:`DataFrame.to_dict`. (:issue:`54229`) @@ -294,6 +295,7 @@ Other Deprecations - Deprecated strings ``T``, ``S``, ``L``, ``U``, and ``N`` denoting frequencies in :class:`Minute`, :class:`Second`, :class:`Milli`, :class:`Micro`, :class:`Nano` (:issue:`52536`) - Deprecated the ``errors="ignore"`` option in :func:`to_datetime`, :func:`to_timedelta`, and :func:`to_numeric`; explicitly catch exceptions instead (:issue:`54467`) - Deprecated the ``fastpath`` keyword in the :class:`Series` constructor (:issue:`20110`) +- Deprecated the ``ordinal`` keyword in :class:`PeriodIndex`, use :meth:`PeriodIndex.from_ordinals` instead (:issue:`55960`) - Deprecated the extension test classes ``BaseNoReduceTests``, ``BaseBooleanReduceTests``, and ``BaseNumericReduceTests``, use ``BaseReduceTests`` instead (:issue:`54663`) - Deprecated the option ``mode.data_manager`` and the ``ArrayManager``; only the ``BlockManager`` will be available in future versions (:issue:`55043`) - Deprecated the previous implementation of :class:`DataFrame.stack`; specify ``future_stack=True`` to adopt the future version (:issue:`53515`) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 25659d8738057..57b244e8d02e9 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -329,26 +329,25 @@ def _from_datetime64(cls, data, freq, tz=None) -> Self: return cls(data, dtype=dtype) @classmethod - def _generate_range(cls, start, end, periods, freq, fields): + def _generate_range(cls, start, end, periods, freq): periods = dtl.validate_periods(periods) if freq is not None: freq = Period._maybe_convert_freq(freq) - field_count = len(fields) if start is not None or end is not None: - if field_count > 0: - raise ValueError( - "Can either instantiate from fields or endpoints, but not both" - ) subarr, freq = _get_ordinal_range(start, end, periods, freq) - elif field_count > 0: - subarr, freq = _range_from_fields(freq=freq, **fields) else: raise ValueError("Not enough parameters to construct Period range") return subarr, freq + @classmethod + def _from_fields(cls, *, fields: dict, freq) -> Self: + subarr, freq = _range_from_fields(freq=freq, **fields) + dtype = PeriodDtype(freq) + return cls._simple_new(subarr, dtype=dtype) + # ----------------------------------------------------------------- # DatetimeLike Interface diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index faf058eff4bf4..b2f1933800fd3 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -5,6 +5,7 @@ timedelta, ) from typing import TYPE_CHECKING +import warnings import numpy as np @@ -21,6 +22,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_integer from pandas.core.dtypes.dtypes import PeriodDtype @@ -97,12 +99,33 @@ class PeriodIndex(DatetimeIndexOpsMixin): freq : str or period object, optional One of pandas period strings or corresponding objects. year : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. month : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. quarter : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. day : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. hour : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. minute : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. second : int, array, or Series, default None + + .. deprecated:: 2.2.0 + Use PeriodIndex.from_fields instead. dtype : str or PeriodDtype, default None Attributes @@ -135,6 +158,8 @@ class PeriodIndex(DatetimeIndexOpsMixin): asfreq strftime to_timestamp + from_fields + from_ordinals See Also -------- @@ -146,7 +171,7 @@ class PeriodIndex(DatetimeIndexOpsMixin): Examples -------- - >>> idx = pd.PeriodIndex(year=[2000, 2002], quarter=[1, 3]) + >>> idx = pd.PeriodIndex.from_fields(year=[2000, 2002], quarter=[1, 3]) >>> idx PeriodIndex(['2000Q1', '2002Q3'], dtype='period[Q-DEC]') """ @@ -233,6 +258,24 @@ def __new__( if not set(fields).issubset(valid_field_set): argument = next(iter(set(fields) - valid_field_set)) raise TypeError(f"__new__() got an unexpected keyword argument {argument}") + elif len(fields): + # GH#55960 + warnings.warn( + "Constructing PeriodIndex from fields is deprecated. Use " + "PeriodIndex.from_fields instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) + + if ordinal is not None: + # GH#55960 + warnings.warn( + "The 'ordinal' keyword in PeriodIndex is deprecated and will " + "be removed in a future version. Use PeriodIndex.from_ordinals " + "instead.", + FutureWarning, + stacklevel=find_stack_level(), + ) name = maybe_extract_name(name, data, cls) @@ -241,14 +284,9 @@ def __new__( if not fields: # test_pickle_compat_construction cls._raise_scalar_data_error(None) + data = cls.from_fields(**fields, freq=freq)._data + copy = False - data, freq2 = PeriodArray._generate_range(None, None, None, freq, fields) - # PeriodArray._generate range does validation that fields is - # empty when really using the range-based constructor. - freq = freq2 - - dtype = PeriodDtype(freq) - data = PeriodArray(data, dtype=dtype) elif fields: if data is not None: raise ValueError("Cannot pass both data and fields") @@ -280,6 +318,39 @@ def __new__( return cls._simple_new(data, name=name, refs=refs) + @classmethod + def from_fields( + cls, + *, + year=None, + quarter=None, + month=None, + day=None, + hour=None, + minute=None, + second=None, + freq=None, + ) -> Self: + fields = { + "year": year, + "quarter": quarter, + "month": month, + "day": day, + "hour": hour, + "minute": minute, + "second": second, + } + fields = {key: value for key, value in fields.items() if value is not None} + arr = PeriodArray._from_fields(fields=fields, freq=freq) + return cls._simple_new(arr) + + @classmethod + def from_ordinals(cls, ordinals, *, freq, name=None) -> Self: + ordinals = np.asarray(ordinals, dtype=np.int64) + dtype = PeriodDtype(freq) + data = PeriodArray._simple_new(ordinals, dtype=dtype) + return cls._simple_new(data, name=name) + # ------------------------------------------------------------------------ # Data @@ -537,7 +608,7 @@ def period_range( if freq is None and (not isinstance(start, Period) and not isinstance(end, Period)): freq = "D" - data, freq = PeriodArray._generate_range(start, end, periods, freq, fields={}) + data, freq = PeriodArray._generate_range(start, end, periods, freq) dtype = PeriodDtype(freq) data = PeriodArray(data, dtype=dtype) return PeriodIndex(data, name=name) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 3659e7247495d..9e0e3686e4aa2 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2169,8 +2169,10 @@ def convert( # error: Incompatible types in assignment (expression has type # "Callable[[Any, KwArg(Any)], PeriodIndex]", variable has type # "Union[Type[Index], Type[DatetimeIndex]]") - factory = lambda x, **kwds: PeriodIndex( # type: ignore[assignment] - ordinal=x, **kwds + factory = lambda x, **kwds: PeriodIndex.from_ordinals( # type: ignore[assignment] + x, freq=kwds.get("freq", None) + )._rename( + kwds["name"] ) # making an Index instance could throw a number of different errors diff --git a/pandas/tests/indexes/period/methods/test_to_timestamp.py b/pandas/tests/indexes/period/methods/test_to_timestamp.py index 977ad8b26a369..7be2602135578 100644 --- a/pandas/tests/indexes/period/methods/test_to_timestamp.py +++ b/pandas/tests/indexes/period/methods/test_to_timestamp.py @@ -87,7 +87,7 @@ def test_to_timestamp_quarterly_bug(self): years = np.arange(1960, 2000).repeat(4) quarters = np.tile(list(range(1, 5)), 40) - pindex = PeriodIndex(year=years, quarter=quarters) + pindex = PeriodIndex.from_fields(year=years, quarter=quarters) stamps = pindex.to_timestamp("D", "end") expected = DatetimeIndex([x.to_timestamp("D", "end") for x in pindex]) diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index 79837af79c189..a1923d29d3d0e 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -23,18 +23,23 @@ class TestPeriodIndex: def test_keyword_mismatch(self): # GH#55961 we should get exactly one of data/ordinals/**fields per = Period("2016-01-01", "D") + depr_msg1 = "The 'ordinal' keyword in PeriodIndex is deprecated" + depr_msg2 = "Constructing PeriodIndex from fields is deprecated" err_msg1 = "Cannot pass both data and ordinal" with pytest.raises(ValueError, match=err_msg1): - PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq) + with tm.assert_produces_warning(FutureWarning, match=depr_msg1): + PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq) err_msg2 = "Cannot pass both data and fields" with pytest.raises(ValueError, match=err_msg2): - PeriodIndex(data=[per], year=[per.year], freq=per.freq) + with tm.assert_produces_warning(FutureWarning, match=depr_msg2): + PeriodIndex(data=[per], year=[per.year], freq=per.freq) err_msg3 = "Cannot pass both ordinal and fields" with pytest.raises(ValueError, match=err_msg3): - PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq) + with tm.assert_produces_warning(FutureWarning, match=depr_msg2): + PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq) def test_construction_base_constructor(self): # GH 13664 @@ -94,14 +99,18 @@ def test_constructor_field_arrays(self): years = np.arange(1990, 2010).repeat(4)[2:-2] quarters = np.tile(np.arange(1, 5), 20)[2:-2] - index = PeriodIndex(year=years, quarter=quarters, freq="Q-DEC") + depr_msg = "Constructing PeriodIndex from fields is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + index = PeriodIndex(year=years, quarter=quarters, freq="Q-DEC") expected = period_range("1990Q3", "2009Q2", freq="Q-DEC") tm.assert_index_equal(index, expected) - index2 = PeriodIndex(year=years, quarter=quarters, freq="2Q-DEC") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + index2 = PeriodIndex(year=years, quarter=quarters, freq="2Q-DEC") tm.assert_numpy_array_equal(index.asi8, index2.asi8) - index = PeriodIndex(year=years, quarter=quarters) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + index = PeriodIndex(year=years, quarter=quarters) tm.assert_index_equal(index, expected) years = [2007, 2007, 2007] @@ -109,13 +118,16 @@ def test_constructor_field_arrays(self): msg = "Mismatched Period array lengths" with pytest.raises(ValueError, match=msg): - PeriodIndex(year=years, month=months, freq="M") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + PeriodIndex(year=years, month=months, freq="M") with pytest.raises(ValueError, match=msg): - PeriodIndex(year=years, month=months, freq="2M") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + PeriodIndex(year=years, month=months, freq="2M") years = [2007, 2007, 2007] months = [1, 2, 3] - idx = PeriodIndex(year=years, month=months, freq="M") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + idx = PeriodIndex(year=years, month=months, freq="M") exp = period_range("2007-01", periods=3, freq="M") tm.assert_index_equal(idx, exp) @@ -145,15 +157,24 @@ def test_constructor_arrays_negative_year(self): years = np.arange(1960, 2000, dtype=np.int64).repeat(4) quarters = np.tile(np.array([1, 2, 3, 4], dtype=np.int64), 40) - pindex = PeriodIndex(year=years, quarter=quarters) + msg = "Constructing PeriodIndex from fields is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pindex = PeriodIndex(year=years, quarter=quarters) tm.assert_index_equal(pindex.year, Index(years)) tm.assert_index_equal(pindex.quarter, Index(quarters)) + alt = PeriodIndex.from_fields(year=years, quarter=quarters) + tm.assert_index_equal(alt, pindex) + def test_constructor_invalid_quarters(self): + depr_msg = "Constructing PeriodIndex from fields is deprecated" msg = "Quarter must be 1 <= q <= 4" with pytest.raises(ValueError, match=msg): - PeriodIndex(year=range(2000, 2004), quarter=list(range(4)), freq="Q-DEC") + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + PeriodIndex( + year=range(2000, 2004), quarter=list(range(4)), freq="Q-DEC" + ) def test_constructor_corner(self): result = period_range("2007-01", periods=10.5, freq="M") @@ -394,7 +415,9 @@ def test_constructor_nat(self): def test_constructor_year_and_quarter(self): year = Series([2001, 2002, 2003]) quarter = year - 2000 - idx = PeriodIndex(year=year, quarter=quarter) + msg = "Constructing PeriodIndex from fields is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx = PeriodIndex(year=year, quarter=quarter) strs = [f"{t[0]:d}Q{t[1]:d}" for t in zip(quarter, year)] lops = list(map(Period, strs)) p = PeriodIndex(lops) diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 6965aaf19f8fb..c30535a012012 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -214,10 +214,19 @@ def test_negative_ordinals(self): Period(ordinal=-1000, freq="Y") Period(ordinal=0, freq="Y") - idx1 = PeriodIndex(ordinal=[-1, 0, 1], freq="Y") - idx2 = PeriodIndex(ordinal=np.array([-1, 0, 1]), freq="Y") + msg = "The 'ordinal' keyword in PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + idx1 = PeriodIndex(ordinal=[-1, 0, 1], freq="Y") + with tm.assert_produces_warning(FutureWarning, match=msg): + idx2 = PeriodIndex(ordinal=np.array([-1, 0, 1]), freq="Y") tm.assert_index_equal(idx1, idx2) + alt1 = PeriodIndex.from_ordinals([-1, 0, 1], freq="Y") + tm.assert_index_equal(alt1, idx1) + + alt2 = PeriodIndex.from_ordinals(np.array([-1, 0, 1]), freq="Y") + tm.assert_index_equal(alt2, idx2) + def test_pindex_fieldaccessor_nat(self): idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2012-03", "2012-04"], freq="D", name="name" diff --git a/pandas/tests/indexes/test_old_base.py b/pandas/tests/indexes/test_old_base.py index 30e3f5cee05b4..f08de8e65451c 100644 --- a/pandas/tests/indexes/test_old_base.py +++ b/pandas/tests/indexes/test_old_base.py @@ -272,7 +272,9 @@ def test_ensure_copied_data(self, index): if isinstance(index, PeriodIndex): # .values an object array of Period, thus copied - result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) + depr_msg = "The 'ordinal' keyword in PeriodIndex is deprecated" + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + result = index_type(ordinal=index.asi8, copy=False, **init_kwargs) tm.assert_numpy_array_equal(index.asi8, result.asi8, check_same="same") elif isinstance(index, IntervalIndex): # checked in test_interval.py
- [x] closes #55960 (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/55963
2023-11-14T21:46:14Z
2023-11-15T23:20:00Z
2023-11-15T23:20:00Z
2023-11-15T23:21:17Z
TST: parametrize and improve test performance
diff --git a/pandas/tests/frame/test_iteration.py b/pandas/tests/frame/test_iteration.py index 216fd5c2f70c5..7374a8ea6aa77 100644 --- a/pandas/tests/frame/test_iteration.py +++ b/pandas/tests/frame/test_iteration.py @@ -1,6 +1,7 @@ import datetime import numpy as np +import pytest from pandas.compat import ( IS64, @@ -91,6 +92,7 @@ def test_itertuples(self, float_frame): expected = float_frame.iloc[i, :].reset_index(drop=True) tm.assert_series_equal(ser, expected) + def test_itertuples_index_false(self): df = DataFrame( {"floats": np.random.default_rng(2).standard_normal(5), "ints": range(5)}, columns=["floats", "ints"], @@ -99,6 +101,7 @@ def test_itertuples(self, float_frame): for tup in df.itertuples(index=False): assert isinstance(tup[1], int) + def test_itertuples_duplicate_cols(self): df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) dfaa = df[["a", "a"]] @@ -111,32 +114,27 @@ def test_itertuples(self, float_frame): == "[(0, 1, 4), (1, 2, 5), (2, 3, 6)]" ) + def test_itertuples_tuple_name(self): + df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) tup = next(df.itertuples(name="TestName")) assert tup._fields == ("Index", "a", "b") assert (tup.Index, tup.a, tup.b) == tup assert type(tup).__name__ == "TestName" - df.columns = ["def", "return"] + def test_itertuples_disallowed_col_labels(self): + df = DataFrame(data={"def": [1, 2, 3], "return": [4, 5, 6]}) tup2 = next(df.itertuples(name="TestName")) assert tup2 == (0, 1, 4) assert tup2._fields == ("Index", "_1", "_2") - df3 = DataFrame({"f" + str(i): [i] for i in range(1024)}) - # will raise SyntaxError if trying to create namedtuple - tup3 = next(df3.itertuples()) - assert isinstance(tup3, tuple) - assert hasattr(tup3, "_fields") - + @pytest.mark.parametrize("limit", [254, 255, 1024]) + @pytest.mark.parametrize("index", [True, False]) + def test_itertuples_py2_3_field_limit_namedtuple(self, limit, index): # GH#28282 - df_254_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(254)}]) - result_254_columns = next(df_254_columns.itertuples(index=False)) - assert isinstance(result_254_columns, tuple) - assert hasattr(result_254_columns, "_fields") - - df_255_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(255)}]) - result_255_columns = next(df_255_columns.itertuples(index=False)) - assert isinstance(result_255_columns, tuple) - assert hasattr(result_255_columns, "_fields") + df = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(limit)}]) + result = next(df.itertuples(index=index)) + assert isinstance(result, tuple) + assert hasattr(result, "_fields") def test_sequence_like_with_categorical(self): # GH#7839 diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index da11920ac1cba..73de33607ca0b 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -8,6 +8,7 @@ import numpy as np import pytest +from pandas._libs import index as libindex from pandas.compat.numpy import np_long import pandas as pd @@ -425,17 +426,17 @@ def test_get_loc_time_obj(self): expected = np.array([]) tm.assert_numpy_array_equal(result, expected, check_dtype=False) - def test_get_loc_time_obj2(self): + @pytest.mark.parametrize("offset", [-10, 10]) + def test_get_loc_time_obj2(self, monkeypatch, offset): # GH#8667 - - from pandas._libs.index import _SIZE_CUTOFF - - ns = _SIZE_CUTOFF + np.array([-100, 100], dtype=np.int64) + size_cutoff = 50 + n = size_cutoff + offset key = time(15, 11, 30) start = key.hour * 3600 + key.minute * 60 + key.second step = 24 * 3600 - for n in ns: + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) idx = date_range("2014-11-26", periods=n, freq="s") ts = pd.Series(np.random.default_rng(2).standard_normal(n), index=idx) locs = np.arange(start, n, step, dtype=np.intp) diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py index 3d2ed1d168040..36cc8316ea5ff 100644 --- a/pandas/tests/indexing/multiindex/test_multiindex.py +++ b/pandas/tests/indexing/multiindex/test_multiindex.py @@ -1,7 +1,7 @@ import numpy as np import pytest -import pandas._libs.index as _index +import pandas._libs.index as libindex from pandas.errors import PerformanceWarning import pandas as pd @@ -33,20 +33,19 @@ def test_multiindex_perf_warn(self): with tm.assert_produces_warning(PerformanceWarning): df.loc[(0,)] - def test_indexing_over_hashtable_size_cutoff(self): - n = 10000 + @pytest.mark.parametrize("offset", [-5, 5]) + def test_indexing_over_hashtable_size_cutoff(self, monkeypatch, offset): + size_cutoff = 20 + n = size_cutoff + offset - old_cutoff = _index._SIZE_CUTOFF - _index._SIZE_CUTOFF = 20000 + with monkeypatch.context(): + monkeypatch.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + s = Series(np.arange(n), MultiIndex.from_arrays((["a"] * n, np.arange(n)))) - s = Series(np.arange(n), MultiIndex.from_arrays((["a"] * n, np.arange(n)))) - - # hai it works! - assert s[("a", 5)] == 5 - assert s[("a", 6)] == 6 - assert s[("a", 7)] == 7 - - _index._SIZE_CUTOFF = old_cutoff + # hai it works! + assert s[("a", 5)] == 5 + assert s[("a", 6)] == 6 + assert s[("a", 7)] == 7 def test_multi_nan_indexing(self): # GH 3588 diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index f7f94af92743e..c8ff42509505a 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -1833,15 +1833,14 @@ def test_encoding_latin1_118(self, datapath): @pytest.mark.slow def test_stata_119(self, datapath): # Gzipped since contains 32,999 variables and uncompressed is 20MiB + # Just validate that the reader reports correct number of variables + # to avoid high peak memory with gzip.open( datapath("io", "data", "stata", "stata1_119.dta.gz"), "rb" ) as gz: - df = read_stata(gz) - assert df.shape == (1, 32999) - assert df.iloc[0, 6] == "A" * 3000 - assert df.iloc[0, 7] == 3.14 - assert df.iloc[0, -1] == 1 - assert df.iloc[0, 0] == pd.Timestamp(datetime(2012, 12, 21, 21, 12, 21)) + with StataReader(gz) as reader: + reader._ensure_open() + assert reader._nvar == 32999 @pytest.mark.parametrize("version", [118, 119, None]) def test_utf8_writer(self, version): diff --git a/pandas/tests/resample/test_resample_api.py b/pandas/tests/resample/test_resample_api.py index 12618f42c7f07..94e50bc980e0a 100644 --- a/pandas/tests/resample/test_resample_api.py +++ b/pandas/tests/resample/test_resample_api.py @@ -376,214 +376,245 @@ def test_agg_consistency_int_str_column_mix(): # `Base` test class -def test_agg(): - # test with all three Resampler apis and TimeGrouper - +@pytest.fixture +def index(): index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") index.name = "date" - df = DataFrame( + return index + + +@pytest.fixture +def df(index): + frame = DataFrame( np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index ) - df_col = df.reset_index() + return frame + + +@pytest.fixture +def df_col(df): + return df.reset_index() + + +@pytest.fixture +def df_mult(df_col, index): df_mult = df_col.copy() df_mult.index = pd.MultiIndex.from_arrays( - [range(10), df.index], names=["index", "date"] + [range(10), index], names=["index", "date"] ) - r = df.resample("2D") - cases = [ - r, - df_col.resample("2D", on="date"), - df_mult.resample("2D", level="date"), - df.groupby(pd.Grouper(freq="2D")), - ] + return df_mult + + +@pytest.fixture +def a_mean(df): + return df.resample("2D")["A"].mean() + + +@pytest.fixture +def a_std(df): + return df.resample("2D")["A"].std() + + +@pytest.fixture +def a_sum(df): + return df.resample("2D")["A"].sum() + + +@pytest.fixture +def b_mean(df): + return df.resample("2D")["B"].mean() + + +@pytest.fixture +def b_std(df): + return df.resample("2D")["B"].std() + + +@pytest.fixture +def b_sum(df): + return df.resample("2D")["B"].sum() + + +@pytest.fixture +def df_resample(df): + return df.resample("2D") - a_mean = r["A"].mean() - a_std = r["A"].std() - a_sum = r["A"].sum() - b_mean = r["B"].mean() - b_std = r["B"].std() - b_sum = r["B"].sum() +@pytest.fixture +def df_col_resample(df_col): + return df_col.resample("2D", on="date") + + +@pytest.fixture +def df_mult_resample(df_mult): + return df_mult.resample("2D", level="date") + + +@pytest.fixture +def df_grouper_resample(df): + return df.groupby(pd.Grouper(freq="2D")) + + +@pytest.fixture( + params=["df_resample", "df_col_resample", "df_mult_resample", "df_grouper_resample"] +) +def cases(request): + return request.getfixturevalue(request.param) + + +def test_agg_mixed_column_aggregation(cases, a_mean, a_std, b_mean, b_std, request): expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) expected.columns = pd.MultiIndex.from_product([["A", "B"], ["mean", "std"]]) msg = "using SeriesGroupBy.[mean|std]" - for t in cases: - # In case 2, "date" is an index and a column, so get included in the agg - if t == cases[2]: - 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"]] - ) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.aggregate([np.mean, np.std]) - tm.assert_frame_equal(result, exp) - else: - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.aggregate([np.mean, np.std]) - tm.assert_frame_equal(result, expected) + # "date" is an index and a column, so get included in the agg + if "df_mult" in request.node.callspec.id: + date_mean = cases["date"].mean() + date_std = cases["date"].std() + expected = pd.concat([date_mean, date_std, expected], axis=1) + expected.columns = pd.MultiIndex.from_product( + [["date", "A", "B"], ["mean", "std"]] + ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = cases.aggregate([np.mean, np.std]) + tm.assert_frame_equal(result, expected) - expected = pd.concat([a_mean, b_std], axis=1) - for t in cases: - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.aggregate({"A": np.mean, "B": np.std}) - tm.assert_frame_equal(result, expected, check_like=True) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.aggregate(A=("A", np.mean), B=("B", np.std)) - tm.assert_frame_equal(result, expected, check_like=True) +@pytest.mark.parametrize( + "agg", + [ + {"func": {"A": np.mean, "B": np.std}}, + {"A": ("A", np.mean), "B": ("B", np.std)}, + {"A": NamedAgg("A", np.mean), "B": NamedAgg("B", np.std)}, + ], +) +def test_agg_both_mean_std_named_result(cases, a_mean, b_std, agg): + msg = "using SeriesGroupBy.[mean|std]" + expected = pd.concat([a_mean, b_std], axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = cases.aggregate(**agg) + tm.assert_frame_equal(result, expected, check_like=True) - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.aggregate(A=NamedAgg("A", np.mean), B=NamedAgg("B", np.std)) - tm.assert_frame_equal(result, expected, check_like=True) +def test_agg_both_mean_std_dict_of_list(cases, a_mean, a_std): expected = pd.concat([a_mean, a_std], axis=1) expected.columns = pd.MultiIndex.from_tuples([("A", "mean"), ("A", "std")]) - for t in cases: - result = t.aggregate({"A": ["mean", "std"]}) - tm.assert_frame_equal(result, expected) + result = cases.aggregate({"A": ["mean", "std"]}) + tm.assert_frame_equal(result, expected) + +@pytest.mark.parametrize( + "agg", [{"func": ["mean", "sum"]}, {"mean": "mean", "sum": "sum"}] +) +def test_agg_both_mean_sum(cases, a_mean, a_sum, agg): expected = pd.concat([a_mean, a_sum], axis=1) expected.columns = ["mean", "sum"] - for t in cases: - result = t["A"].aggregate(["mean", "sum"]) - tm.assert_frame_equal(result, expected) + result = cases["A"].aggregate(**agg) + tm.assert_frame_equal(result, expected) - result = t["A"].aggregate(mean="mean", sum="sum") - tm.assert_frame_equal(result, expected) +@pytest.mark.parametrize( + "agg", + [ + {"A": {"mean": "mean", "sum": "sum"}}, + { + "A": {"mean": "mean", "sum": "sum"}, + "B": {"mean2": "mean", "sum2": "sum"}, + }, + ], +) +def test_agg_dict_of_dict_specificationerror(cases, agg): msg = "nested renamer is not supported" - for t in cases: - with pytest.raises(pd.errors.SpecificationError, match=msg): - t.aggregate({"A": {"mean": "mean", "sum": "sum"}}) + with pytest.raises(pd.errors.SpecificationError, match=msg): + cases.aggregate(agg) - expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1) - expected.columns = pd.MultiIndex.from_tuples( - [("A", "mean"), ("A", "sum"), ("B", "mean2"), ("B", "sum2")] - ) - for t in cases: - with pytest.raises(pd.errors.SpecificationError, match=msg): - t.aggregate( - { - "A": {"mean": "mean", "sum": "sum"}, - "B": {"mean2": "mean", "sum2": "sum"}, - } - ) +def test_agg_dict_of_lists(cases, a_mean, a_std, b_mean, b_std): expected = pd.concat([a_mean, a_std, b_mean, b_std], axis=1) expected.columns = pd.MultiIndex.from_tuples( [("A", "mean"), ("A", "std"), ("B", "mean"), ("B", "std")] ) - for t in cases: - result = t.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]}) - tm.assert_frame_equal(result, expected, check_like=True) - - expected = pd.concat([a_mean, a_sum, b_mean, b_sum], axis=1) - expected.columns = pd.MultiIndex.from_tuples( - [ - ("r1", "A", "mean"), - ("r1", "A", "sum"), - ("r2", "B", "mean"), - ("r2", "B", "sum"), - ] - ) + result = cases.aggregate({"A": ["mean", "std"], "B": ["mean", "std"]}) + tm.assert_frame_equal(result, expected, check_like=True) -def test_agg_misc(): - # test with all three Resampler apis and TimeGrouper - - index = date_range(datetime(2005, 1, 1), datetime(2005, 1, 10), freq="D") - index.name = "date" - df = DataFrame( - np.random.default_rng(2).random((10, 2)), columns=list("AB"), index=index - ) - df_col = df.reset_index() - df_mult = df_col.copy() - df_mult.index = pd.MultiIndex.from_arrays( - [range(10), df.index], names=["index", "date"] - ) - - r = df.resample("2D") - cases = [ - r, - df_col.resample("2D", on="date"), - df_mult.resample("2D", level="date"), - df.groupby(pd.Grouper(freq="2D")), - ] - +@pytest.mark.parametrize( + "agg", + [ + {"func": {"A": np.sum, "B": lambda x: np.std(x, ddof=1)}}, + {"A": ("A", np.sum), "B": ("B", lambda x: np.std(x, ddof=1))}, + {"A": NamedAgg("A", np.sum), "B": NamedAgg("B", lambda x: np.std(x, ddof=1))}, + ], +) +def test_agg_with_lambda(cases, agg): # passed lambda msg = "using SeriesGroupBy.sum" - for t in cases: - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)}) - rcustom = t["B"].apply(lambda x: np.std(x, ddof=1)) - expected = pd.concat([r["A"].sum(), rcustom], axis=1) - tm.assert_frame_equal(result, expected, check_like=True) - - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.agg(A=("A", np.sum), B=("B", lambda x: np.std(x, ddof=1))) - tm.assert_frame_equal(result, expected, check_like=True) - - with tm.assert_produces_warning(FutureWarning, match=msg): - result = t.agg( - A=NamedAgg("A", np.sum), B=NamedAgg("B", lambda x: np.std(x, ddof=1)) - ) - tm.assert_frame_equal(result, expected, check_like=True) + rcustom = cases["B"].apply(lambda x: np.std(x, ddof=1)) + expected = pd.concat([cases["A"].sum(), rcustom], axis=1) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = cases.agg(**agg) + tm.assert_frame_equal(result, expected, check_like=True) - # agg with renamers - expected = pd.concat( - [t["A"].sum(), t["B"].sum(), t["A"].mean(), t["B"].mean()], axis=1 - ) - expected.columns = pd.MultiIndex.from_tuples( - [("result1", "A"), ("result1", "B"), ("result2", "A"), ("result2", "B")] - ) +@pytest.mark.parametrize( + "agg", + [ + {"func": {"result1": np.sum, "result2": np.mean}}, + {"A": ("result1", np.sum), "B": ("result2", np.mean)}, + {"A": NamedAgg("result1", np.sum), "B": NamedAgg("result2", np.mean)}, + ], +) +def test_agg_no_column(cases, agg): msg = r"Column\(s\) \['result1', 'result2'\] do not exist" - for t in cases: - with pytest.raises(KeyError, match=msg): - t[["A", "B"]].agg({"result1": np.sum, "result2": np.mean}) - - with pytest.raises(KeyError, match=msg): - t[["A", "B"]].agg(A=("result1", np.sum), B=("result2", np.mean)) + with pytest.raises(KeyError, match=msg): + cases[["A", "B"]].agg(**agg) - with pytest.raises(KeyError, match=msg): - t[["A", "B"]].agg( - A=NamedAgg("result1", np.sum), B=NamedAgg("result2", np.mean) - ) +@pytest.mark.parametrize( + "cols, agg", + [ + [None, {"A": ["sum", "std"], "B": ["mean", "std"]}], + [ + [ + "A", + "B", + ], + {"A": ["sum", "std"], "B": ["mean", "std"]}, + ], + ], +) +def test_agg_specificationerror_nested(cases, cols, agg, a_sum, a_std, b_mean, b_std): # agg with different hows - expected = pd.concat( - [t["A"].sum(), t["A"].std(), t["B"].mean(), t["B"].std()], axis=1 - ) + # equivalent of using a selection list / or not + expected = pd.concat([a_sum, a_std, b_mean, b_std], axis=1) expected.columns = pd.MultiIndex.from_tuples( [("A", "sum"), ("A", "std"), ("B", "mean"), ("B", "std")] ) - for t in cases: - result = t.agg({"A": ["sum", "std"], "B": ["mean", "std"]}) - tm.assert_frame_equal(result, expected, check_like=True) + if cols is not None: + obj = cases[cols] + else: + obj = cases + + result = obj.agg(agg) + tm.assert_frame_equal(result, expected, check_like=True) - # equivalent of using a selection list / or not - for t in cases: - result = t[["A", "B"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) - tm.assert_frame_equal(result, expected, check_like=True) +@pytest.mark.parametrize( + "agg", [{"A": ["sum", "std"]}, {"A": ["sum", "std"], "B": ["mean", "std"]}] +) +def test_agg_specificationerror_series(cases, agg): msg = "nested renamer is not supported" # series like aggs - for t in cases: - with pytest.raises(pd.errors.SpecificationError, match=msg): - t["A"].agg({"A": ["sum", "std"]}) + with pytest.raises(pd.errors.SpecificationError, match=msg): + cases["A"].agg(agg) - with pytest.raises(pd.errors.SpecificationError, match=msg): - t["A"].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) +def test_agg_specificationerror_invalid_names(cases): # errors # invalid names in the agg specification msg = r"Column\(s\) \['B'\] do not exist" - for t in cases: - with pytest.raises(KeyError, match=msg): - t[["A"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) + with pytest.raises(KeyError, match=msg): + cases[["A"]].agg({"A": ["sum", "std"], "B": ["mean", "std"]}) @pytest.mark.parametrize(
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55962
2023-11-14T21:26:13Z
2023-11-16T17:37:19Z
2023-11-16T17:37:19Z
2023-11-16T17:37:22Z
BUG: PeriodIndex.__new__ with keyword mismatch
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 3203dc083faf6..ea25d8d92c16f 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -420,6 +420,7 @@ I/O Period ^^^^^^ +- Bug in :class:`PeriodIndex` construction when more than one of ``data``, ``ordinal`` and ``**fields`` are passed failing to raise ``ValueError`` (:issue:`55961`) - Bug in :class:`Period` addition silently wrapping around instead of raising ``OverflowError`` (:issue:`55503`) - diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 09b41d9c32ec2..faf058eff4bf4 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -249,6 +249,11 @@ def __new__( dtype = PeriodDtype(freq) data = PeriodArray(data, dtype=dtype) + elif fields: + if data is not None: + raise ValueError("Cannot pass both data and fields") + raise ValueError("Cannot pass both ordinal and fields") + else: freq = validate_dtype_freq(dtype, freq) @@ -261,10 +266,11 @@ def __new__( data = data.asfreq(freq) if data is None and ordinal is not None: - # we strangely ignore `ordinal` if data is passed. ordinal = np.asarray(ordinal, dtype=np.int64) dtype = PeriodDtype(freq) data = PeriodArray(ordinal, dtype=dtype) + elif data is not None and ordinal is not None: + raise ValueError("Cannot pass both data and ordinal") else: # don't pass copy here, since we copy later. data = period_array(data=data, freq=freq) diff --git a/pandas/tests/indexes/period/test_constructors.py b/pandas/tests/indexes/period/test_constructors.py index 865bfdc725f9c..79837af79c189 100644 --- a/pandas/tests/indexes/period/test_constructors.py +++ b/pandas/tests/indexes/period/test_constructors.py @@ -20,6 +20,22 @@ class TestPeriodIndex: + def test_keyword_mismatch(self): + # GH#55961 we should get exactly one of data/ordinals/**fields + per = Period("2016-01-01", "D") + + err_msg1 = "Cannot pass both data and ordinal" + with pytest.raises(ValueError, match=err_msg1): + PeriodIndex(data=[per], ordinal=[per.ordinal], freq=per.freq) + + err_msg2 = "Cannot pass both data and fields" + with pytest.raises(ValueError, match=err_msg2): + PeriodIndex(data=[per], year=[per.year], freq=per.freq) + + err_msg3 = "Cannot pass both ordinal and fields" + with pytest.raises(ValueError, match=err_msg3): + PeriodIndex(ordinal=[per.ordinal], year=[per.year], freq=per.freq) + def test_construction_base_constructor(self): # GH 13664 arr = [Period("2011-01", freq="M"), NaT, Period("2011-03", freq="M")]
- [ ] 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/55961
2023-11-14T18:06:37Z
2023-11-14T21:00:54Z
2023-11-14T21:00:54Z
2023-11-14T21:40:58Z
TST: parametrize tests over dt64 unit
diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index b0a91401b5181..b1b4e738a6365 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -473,6 +473,12 @@ def test_date_range_businesshour(self): rng = date_range("2014-07-04 09:00", "2014-07-08 16:00", freq="bh") tm.assert_index_equal(idx, rng) + def test_date_range_business_hour_short(self, unit): + # GH#49835 + idx4 = date_range(start="2014-07-01 10:00", freq="bh", periods=1, unit=unit) + expected4 = DatetimeIndex(["2014-07-01 10:00"], freq="bh").as_unit(unit) + tm.assert_index_equal(idx4, expected4) + def test_date_range_timedelta(self): start = "2020-01-01" end = "2020-01-11" diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index fcf297fd1b092..dea40eff8d2ac 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -86,7 +86,11 @@ def test_properties(self, closed): [ [1, 1, 2, 5, 15, 53, 217, 1014, 5335, 31240, 201608], [-np.inf, -100, -10, 0.5, 1, 1.5, 3.8, 101, 202, np.inf], - pd.to_datetime(["20170101", "20170202", "20170303", "20170404"]), + date_range("2017-01-01", "2017-01-04"), + pytest.param( + date_range("2017-01-01", "2017-01-04", unit="s"), + marks=pytest.mark.xfail(reason="mismatched result unit"), + ), pd.to_timedelta(["1ns", "2ms", "3s", "4min", "5h", "6D"]), ], ) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 560b2377ada70..17227e7cfabc7 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -822,24 +822,23 @@ def test_numpy_argmax(self): # See GH#16830 data = np.arange(1, 11) - s = Series(data, index=data) - result = np.argmax(s) + ser = Series(data, index=data) + result = np.argmax(ser) expected = np.argmax(data) assert result == expected - result = s.argmax() + result = ser.argmax() assert result == expected msg = "the 'out' parameter is not supported" with pytest.raises(ValueError, match=msg): - np.argmax(s, out=data) + np.argmax(ser, out=data) - def test_idxmin_dt64index(self): + def test_idxmin_dt64index(self, unit): # GH#43587 should have NaT instead of NaN - ser = Series( - [1.0, 2.0, np.nan], index=DatetimeIndex(["NaT", "2015-02-08", "NaT"]) - ) + dti = DatetimeIndex(["NaT", "2015-02-08", "NaT"]).as_unit(unit) + ser = Series([1.0, 2.0, np.nan], index=dti) msg = "The behavior of Series.idxmin with all-NA values" with tm.assert_produces_warning(FutureWarning, match=msg): res = ser.idxmin(skipna=False) @@ -853,12 +852,12 @@ def test_idxmin_dt64index(self): msg = "The behavior of DataFrame.idxmin with all-NA values" with tm.assert_produces_warning(FutureWarning, match=msg): res = df.idxmin(skipna=False) - assert res.dtype == "M8[ns]" + assert res.dtype == f"M8[{unit}]" assert res.isna().all() msg = "The behavior of DataFrame.idxmax with all-NA values" with tm.assert_produces_warning(FutureWarning, match=msg): res = df.idxmax(skipna=False) - assert res.dtype == "M8[ns]" + assert res.dtype == f"M8[{unit}]" assert res.isna().all() def test_idxmin(self): diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 21937a35629a0..16c1c7caa9e3a 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1357,15 +1357,16 @@ def test_resample_consistency(unit): @pytest.mark.parametrize("dates", [dates1, dates2, dates3]) -def test_resample_timegrouper(dates): +def test_resample_timegrouper(dates, unit): # GH 7227 + dates = DatetimeIndex(dates).as_unit(unit) df = DataFrame({"A": dates, "B": np.arange(len(dates))}) result = df.set_index("A").resample("ME").count() exp_idx = DatetimeIndex( ["2014-07-31", "2014-08-31", "2014-09-30", "2014-10-31", "2014-11-30"], freq="ME", name="A", - ) + ).as_unit(unit) expected = DataFrame({"B": [1, 0, 2, 2, 1]}, index=exp_idx) if df["A"].isna().any(): expected.index = expected.index._with_freq(None) @@ -2039,26 +2040,39 @@ def test_resample_BM_deprecated(): tm.assert_series_equal(result, expected) -def test_resample_ms_closed_right(): +def test_resample_ms_closed_right(unit): # https://github.com/pandas-dev/pandas/issues/55271 - dti = date_range(start="2020-01-31", freq="1min", periods=6000) + dti = date_range(start="2020-01-31", freq="1min", periods=6000, unit=unit) df = DataFrame({"ts": dti}, index=dti) grouped = df.resample("MS", closed="right") result = grouped.last() + exp_dti = DatetimeIndex( + [datetime(2020, 1, 1), datetime(2020, 2, 1)], freq="MS" + ).as_unit(unit) expected = DataFrame( {"ts": [datetime(2020, 2, 1), datetime(2020, 2, 4, 3, 59)]}, - index=DatetimeIndex([datetime(2020, 1, 1), datetime(2020, 2, 1)], freq="MS"), - ) + index=exp_dti, + ).astype(f"M8[{unit}]") tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("freq", ["B", "C"]) -def test_resample_c_b_closed_right(freq: str): +def test_resample_c_b_closed_right(freq: str, unit): # https://github.com/pandas-dev/pandas/issues/55281 - dti = date_range(start="2020-01-31", freq="1min", periods=6000) + dti = date_range(start="2020-01-31", freq="1min", periods=6000, unit=unit) df = DataFrame({"ts": dti}, index=dti) grouped = df.resample(freq, closed="right") result = grouped.last() + + exp_dti = DatetimeIndex( + [ + datetime(2020, 1, 30), + datetime(2020, 1, 31), + datetime(2020, 2, 3), + datetime(2020, 2, 4), + ], + freq=freq, + ).as_unit(unit) expected = DataFrame( { "ts": [ @@ -2068,35 +2082,28 @@ def test_resample_c_b_closed_right(freq: str): datetime(2020, 2, 4, 3, 59), ] }, - index=DatetimeIndex( - [ - datetime(2020, 1, 30), - datetime(2020, 1, 31), - datetime(2020, 2, 3), - datetime(2020, 2, 4), - ], - freq=freq, - ), - ) + index=exp_dti, + ).astype(f"M8[{unit}]") tm.assert_frame_equal(result, expected) -def test_resample_b_55282(): +def test_resample_b_55282(unit): # https://github.com/pandas-dev/pandas/issues/55282 - s = Series( - [1, 2, 3, 4, 5, 6], index=date_range("2023-09-26", periods=6, freq="12h") - ) - result = s.resample("B", closed="right", label="right").mean() + dti = date_range("2023-09-26", periods=6, freq="12h", unit=unit) + ser = Series([1, 2, 3, 4, 5, 6], index=dti) + result = ser.resample("B", closed="right", label="right").mean() + + exp_dti = DatetimeIndex( + [ + datetime(2023, 9, 26), + datetime(2023, 9, 27), + datetime(2023, 9, 28), + datetime(2023, 9, 29), + ], + freq="B", + ).as_unit(unit) expected = Series( [1.0, 2.5, 4.5, 6.0], - index=DatetimeIndex( - [ - datetime(2023, 9, 26), - datetime(2023, 9, 27), - datetime(2023, 9, 28), - datetime(2023, 9, 29), - ], - freq="B", - ), + index=exp_dti, ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index e583de1f489db..363ae1fa9c644 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -309,13 +309,13 @@ def test_td_add_sub_td64_ndarray(self): def test_td_add_sub_dt64_ndarray(self): td = Timedelta("1 day") - other = pd.to_datetime(["2000-01-01"]).values + other = np.array(["2000-01-01"], dtype="M8[ns]") - expected = pd.to_datetime(["2000-01-02"]).values + expected = np.array(["2000-01-02"], dtype="M8[ns]") tm.assert_numpy_array_equal(td + other, expected) tm.assert_numpy_array_equal(other + td, expected) - expected = pd.to_datetime(["1999-12-31"]).values + expected = np.array(["1999-12-31"], dtype="M8[ns]") tm.assert_numpy_array_equal(-td + other, expected) tm.assert_numpy_array_equal(other - td, expected) diff --git a/pandas/tests/series/methods/test_map.py b/pandas/tests/series/methods/test_map.py index 6b357281c831b..6d78ecd61cdcb 100644 --- a/pandas/tests/series/methods/test_map.py +++ b/pandas/tests/series/methods/test_map.py @@ -418,38 +418,44 @@ def __missing__(self, key): tm.assert_series_equal(result, expected) -def test_map_box(): +def test_map_box_dt64(unit): vals = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")] - s = Series(vals) - assert s.dtype == "datetime64[ns]" + ser = Series(vals).dt.as_unit(unit) + assert ser.dtype == f"datetime64[{unit}]" # boxed value must be Timestamp instance - res = s.map(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}") + res = ser.map(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}") exp = Series(["Timestamp_1_None", "Timestamp_2_None"]) tm.assert_series_equal(res, exp) + +def test_map_box_dt64tz(unit): vals = [ pd.Timestamp("2011-01-01", tz="US/Eastern"), pd.Timestamp("2011-01-02", tz="US/Eastern"), ] - s = Series(vals) - assert s.dtype == "datetime64[ns, US/Eastern]" - res = s.map(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}") + ser = Series(vals).dt.as_unit(unit) + assert ser.dtype == f"datetime64[{unit}, US/Eastern]" + res = ser.map(lambda x: f"{type(x).__name__}_{x.day}_{x.tz}") exp = Series(["Timestamp_1_US/Eastern", "Timestamp_2_US/Eastern"]) tm.assert_series_equal(res, exp) + +def test_map_box_td64(unit): # timedelta vals = [pd.Timedelta("1 days"), pd.Timedelta("2 days")] - s = Series(vals) - assert s.dtype == "timedelta64[ns]" - res = s.map(lambda x: f"{type(x).__name__}_{x.days}") + ser = Series(vals).dt.as_unit(unit) + assert ser.dtype == f"timedelta64[{unit}]" + res = ser.map(lambda x: f"{type(x).__name__}_{x.days}") exp = Series(["Timedelta_1", "Timedelta_2"]) tm.assert_series_equal(res, exp) + +def test_map_box_period(): # period vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")] - s = Series(vals) - assert s.dtype == "Period[M]" - res = s.map(lambda x: f"{type(x).__name__}_{x.freqstr}") + ser = Series(vals) + assert ser.dtype == "Period[M]" + res = ser.map(lambda x: f"{type(x).__name__}_{x.freqstr}") exp = Series(["Period_M", "Period_M"]) tm.assert_series_equal(res, exp) diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py index 70ad6b3016a57..016635a50fdf4 100644 --- a/pandas/tests/series/methods/test_quantile.py +++ b/pandas/tests/series/methods/test_quantile.py @@ -48,7 +48,8 @@ def test_quantile(self, datetime_series): with pytest.raises(ValueError, match=msg): s.quantile(percentile_array) - def test_quantile_multi(self, datetime_series): + def test_quantile_multi(self, datetime_series, unit): + datetime_series.index = datetime_series.index.as_unit(unit) qs = [0.1, 0.9] result = datetime_series.quantile(qs) expected = Series( @@ -68,6 +69,7 @@ def test_quantile_multi(self, datetime_series): [Timestamp("2000-01-10 19:12:00"), Timestamp("2000-01-10 19:12:00")], index=[0.2, 0.2], name="xxx", + dtype=f"M8[{unit}]", ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/methods/test_tz_localize.py b/pandas/tests/series/methods/test_tz_localize.py index c2b1569d3f391..45620a721f442 100644 --- a/pandas/tests/series/methods/test_tz_localize.py +++ b/pandas/tests/series/methods/test_tz_localize.py @@ -70,11 +70,11 @@ def test_series_tz_localize_matching_index(self): ["foo", "invalid"], ], ) - def test_tz_localize_nonexistent(self, warsaw, method, exp): + def test_tz_localize_nonexistent(self, warsaw, method, exp, unit): # GH 8917 tz = warsaw n = 60 - dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min") + dti = date_range(start="2015-03-29 02:00:00", periods=n, freq="min", unit=unit) ser = Series(1, index=dti) df = ser.to_frame() @@ -101,7 +101,7 @@ def test_tz_localize_nonexistent(self, warsaw, method, exp): else: result = ser.tz_localize(tz, nonexistent=method) - expected = Series(1, index=DatetimeIndex([exp] * n, tz=tz)) + expected = Series(1, index=DatetimeIndex([exp] * n, tz=tz).as_unit(unit)) tm.assert_series_equal(result, expected) result = df.tz_localize(tz, nonexistent=method) diff --git a/pandas/tests/series/methods/test_value_counts.py b/pandas/tests/series/methods/test_value_counts.py index bde9902fec6e9..859010d9c79c6 100644 --- a/pandas/tests/series/methods/test_value_counts.py +++ b/pandas/tests/series/methods/test_value_counts.py @@ -12,7 +12,7 @@ class TestSeriesValueCounts: - def test_value_counts_datetime(self): + def test_value_counts_datetime(self, unit): # most dtypes are tested in tests/base values = [ pd.Timestamp("2011-01-01 09:00"), @@ -26,13 +26,13 @@ def test_value_counts_datetime(self): exp_idx = pd.DatetimeIndex( ["2011-01-01 09:00", "2011-01-01 11:00", "2011-01-01 10:00"], name="xxx", - ) + ).as_unit(unit) exp = Series([3, 2, 1], index=exp_idx, name="count") - ser = Series(values, name="xxx") + ser = Series(values, name="xxx").dt.as_unit(unit) tm.assert_series_equal(ser.value_counts(), exp) # check DatetimeIndex outputs the same result - idx = pd.DatetimeIndex(values, name="xxx") + idx = pd.DatetimeIndex(values, name="xxx").as_unit(unit) tm.assert_series_equal(idx.value_counts(), exp) # normalize @@ -40,7 +40,7 @@ def test_value_counts_datetime(self): tm.assert_series_equal(ser.value_counts(normalize=True), exp) tm.assert_series_equal(idx.value_counts(normalize=True), exp) - def test_value_counts_datetime_tz(self): + def test_value_counts_datetime_tz(self, unit): values = [ pd.Timestamp("2011-01-01 09:00", tz="US/Eastern"), pd.Timestamp("2011-01-01 10:00", tz="US/Eastern"), @@ -54,12 +54,12 @@ def test_value_counts_datetime_tz(self): ["2011-01-01 09:00", "2011-01-01 11:00", "2011-01-01 10:00"], tz="US/Eastern", name="xxx", - ) + ).as_unit(unit) exp = Series([3, 2, 1], index=exp_idx, name="count") - ser = Series(values, name="xxx") + ser = Series(values, name="xxx").dt.as_unit(unit) tm.assert_series_equal(ser.value_counts(), exp) - idx = pd.DatetimeIndex(values, name="xxx") + idx = pd.DatetimeIndex(values, name="xxx").as_unit(unit) tm.assert_series_equal(idx.value_counts(), exp) exp = Series(np.array([3.0, 2.0, 1]) / 6.0, index=exp_idx, name="proportion") diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 656f6736f03ee..b835be6d8e501 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -749,13 +749,17 @@ def test_series_add_aware_naive_raises(self): with pytest.raises(Exception, match=msg): ser_utc + ser - def test_datetime_understood(self): + # TODO: belongs in tests/arithmetic? + def test_datetime_understood(self, unit): # Ensures it doesn't fail to create the right series # reported in issue#16726 - series = Series(date_range("2012-01-01", periods=3)) + series = Series(date_range("2012-01-01", periods=3, unit=unit)) offset = pd.offsets.DateOffset(days=6) result = series - offset - expected = Series(pd.to_datetime(["2011-12-26", "2011-12-27", "2011-12-28"])) + exp_dti = pd.to_datetime(["2011-12-26", "2011-12-27", "2011-12-28"]).as_unit( + unit + ) + expected = Series(exp_dti) tm.assert_series_equal(result, expected) def test_align_date_objects_with_datetimeindex(self): diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index e1a78136935db..97119127b1665 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -757,23 +757,6 @@ def test_order_of_appearance(self): result = pd.unique(Series([2] + [1] * 5)) tm.assert_numpy_array_equal(result, np.array([2, 1], dtype="int64")) - result = pd.unique(Series([Timestamp("20160101"), Timestamp("20160101")])) - expected = np.array(["2016-01-01T00:00:00.000000000"], dtype="datetime64[ns]") - tm.assert_numpy_array_equal(result, expected) - - result = pd.unique( - Index( - [ - Timestamp("20160101", tz="US/Eastern"), - Timestamp("20160101", tz="US/Eastern"), - ] - ) - ) - expected = DatetimeIndex( - ["2016-01-01 00:00:00"], dtype="datetime64[ns, US/Eastern]", freq=None - ) - tm.assert_index_equal(result, expected) - msg = "unique with argument that is not not a Series, Index," with tm.assert_produces_warning(FutureWarning, match=msg): result = pd.unique(list("aabc")) @@ -784,6 +767,25 @@ def test_order_of_appearance(self): expected = Categorical(list("abc")) tm.assert_categorical_equal(result, expected) + def test_order_of_appearance_dt64(self, unit): + ser = Series([Timestamp("20160101"), Timestamp("20160101")]).dt.as_unit(unit) + result = pd.unique(ser) + expected = np.array(["2016-01-01T00:00:00.000000000"], dtype=f"M8[{unit}]") + tm.assert_numpy_array_equal(result, expected) + + def test_order_of_appearance_dt64tz(self, unit): + dti = DatetimeIndex( + [ + Timestamp("20160101", tz="US/Eastern"), + Timestamp("20160101", tz="US/Eastern"), + ] + ).as_unit(unit) + result = pd.unique(dti) + expected = DatetimeIndex( + ["2016-01-01 00:00:00"], dtype=f"datetime64[{unit}, US/Eastern]", freq=None + ) + tm.assert_index_equal(result, expected) + @pytest.mark.parametrize( "arg ,expected", [ diff --git a/pandas/tests/tseries/holiday/test_calendar.py b/pandas/tests/tseries/holiday/test_calendar.py index 57acf15443ca8..99829857e6836 100644 --- a/pandas/tests/tseries/holiday/test_calendar.py +++ b/pandas/tests/tseries/holiday/test_calendar.py @@ -57,8 +57,11 @@ def __init__(self, name=None, rules=None) -> None: jan2 = TestCalendar(rules=[Holiday("jan2", year=2015, month=1, day=2)]) # Getting holidays for Jan 1 should not alter results for Jan 2. - tm.assert_index_equal(jan1.holidays(), DatetimeIndex(["01-Jan-2015"])) - tm.assert_index_equal(jan2.holidays(), DatetimeIndex(["02-Jan-2015"])) + expected = DatetimeIndex(["01-Jan-2015"]).as_unit("ns") + tm.assert_index_equal(jan1.holidays(), expected) + + expected2 = DatetimeIndex(["02-Jan-2015"]).as_unit("ns") + tm.assert_index_equal(jan2.holidays(), expected2) def test_calendar_observance_dates(): diff --git a/pandas/tests/tseries/holiday/test_holiday.py b/pandas/tests/tseries/holiday/test_holiday.py index e751339ca2cd0..b2eefd04ef93b 100644 --- a/pandas/tests/tseries/holiday/test_holiday.py +++ b/pandas/tests/tseries/holiday/test_holiday.py @@ -327,5 +327,6 @@ def test_holidays_with_timezone_specified_but_no_occurences(): start_date, end_date, return_name=True ) expected_results = Series("New Year's Day", index=[start_date]) + expected_results.index = expected_results.index.as_unit("ns") tm.assert_equal(test_case, expected_results) diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py index 28e660f677e28..227cf6a495c91 100644 --- a/pandas/tests/tseries/offsets/test_business_hour.py +++ b/pandas/tests/tseries/offsets/test_business_hour.py @@ -978,12 +978,6 @@ def test_datetimeindex(self): for idx in [idx1, idx2, idx3]: tm.assert_index_equal(idx, expected) - def test_short_datetimeindex_creation(self): - # gh-49835 - idx4 = date_range(start="2014-07-01 10:00", freq="bh", periods=1) - expected4 = DatetimeIndex(["2014-07-01 10:00"], freq="bh") - tm.assert_index_equal(idx4, expected4) - @pytest.mark.parametrize("td_unit", ["s", "ms", "us", "ns"]) @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) def test_bday_ignores_timedeltas(self, unit, td_unit): diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index b4f6fde6850a2..f353a7fa2f0fe 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -977,20 +977,23 @@ def scaled_sum(*args): @pytest.mark.parametrize("add", [0.0, 2.0]) -def test_rolling_numerical_accuracy_kahan_mean(add): +def test_rolling_numerical_accuracy_kahan_mean(add, unit): # GH: 36031 implementing kahan summation - df = DataFrame( - {"A": [3002399751580331.0 + add, -0.0, -0.0]}, - index=[ + dti = DatetimeIndex( + [ Timestamp("19700101 09:00:00"), Timestamp("19700101 09:00:03"), Timestamp("19700101 09:00:06"), - ], + ] + ).as_unit(unit) + df = DataFrame( + {"A": [3002399751580331.0 + add, -0.0, -0.0]}, + index=dti, ) result = ( df.resample("1s").ffill().rolling("3s", closed="left", min_periods=3).mean() ) - dates = date_range("19700101 09:00:00", periods=7, freq="s") + dates = date_range("19700101 09:00:00", periods=7, freq="s", unit=unit) expected = DataFrame( { "A": [ @@ -1196,8 +1199,19 @@ def test_rolling_var_numerical_issues(func, third_value, values): tm.assert_series_equal(result == 0, expected == 0) -def test_timeoffset_as_window_parameter_for_corr(): +def test_timeoffset_as_window_parameter_for_corr(unit): # GH: 28266 + dti = DatetimeIndex( + [ + Timestamp("20130101 09:00:00"), + Timestamp("20130102 09:00:02"), + Timestamp("20130103 09:00:03"), + Timestamp("20130105 09:00:05"), + Timestamp("20130106 09:00:06"), + ] + ).as_unit(unit) + mi = MultiIndex.from_product([dti, ["B", "A"]]) + exp = DataFrame( { "B": [ @@ -1225,31 +1239,12 @@ def test_timeoffset_as_window_parameter_for_corr(): 1.0000000000000002, ], }, - index=MultiIndex.from_tuples( - [ - (Timestamp("20130101 09:00:00"), "B"), - (Timestamp("20130101 09:00:00"), "A"), - (Timestamp("20130102 09:00:02"), "B"), - (Timestamp("20130102 09:00:02"), "A"), - (Timestamp("20130103 09:00:03"), "B"), - (Timestamp("20130103 09:00:03"), "A"), - (Timestamp("20130105 09:00:05"), "B"), - (Timestamp("20130105 09:00:05"), "A"), - (Timestamp("20130106 09:00:06"), "B"), - (Timestamp("20130106 09:00:06"), "A"), - ] - ), + index=mi, ) df = DataFrame( {"B": [0, 1, 2, 4, 3], "A": [7, 4, 6, 9, 3]}, - index=[ - Timestamp("20130101 09:00:00"), - Timestamp("20130102 09:00:02"), - Timestamp("20130103 09:00:03"), - Timestamp("20130105 09:00:05"), - Timestamp("20130106 09:00:06"), - ], + index=dti, ) res = df.rolling(window="3d").corr() diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index 482c8992feb13..c99fc8a8eb60f 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -3,7 +3,7 @@ from pandas import ( DataFrame, - Index, + DatetimeIndex, MultiIndex, NaT, Series, @@ -178,21 +178,22 @@ def test_frame_on(self): result = df.rolling("2s", on="A")[["B"]].sum() tm.assert_frame_equal(result, expected) - def test_frame_on2(self): + def test_frame_on2(self, unit): # using multiple aggregation columns + dti = DatetimeIndex( + [ + Timestamp("20130101 09:00:00"), + Timestamp("20130101 09:00:02"), + Timestamp("20130101 09:00:03"), + Timestamp("20130101 09:00:05"), + Timestamp("20130101 09:00:06"), + ] + ).as_unit(unit) df = DataFrame( { "A": [0, 1, 2, 3, 4], "B": [0, 1, 2, np.nan, 4], - "C": Index( - [ - Timestamp("20130101 09:00:00"), - Timestamp("20130101 09:00:02"), - Timestamp("20130101 09:00:03"), - Timestamp("20130101 09:00:05"), - Timestamp("20130101 09:00:06"), - ] - ), + "C": dti, }, columns=["A", "C", "B"], ) @@ -248,18 +249,22 @@ def test_min_periods(self, regular): result = df.rolling("2s", min_periods=1).sum() tm.assert_frame_equal(result, expected) - def test_closed(self, regular): + def test_closed(self, regular, unit): # xref GH13965 - df = DataFrame( - {"A": [1] * 5}, - index=[ + dti = DatetimeIndex( + [ Timestamp("20130101 09:00:01"), Timestamp("20130101 09:00:02"), Timestamp("20130101 09:00:03"), Timestamp("20130101 09:00:04"), Timestamp("20130101 09:00:06"), - ], + ] + ).as_unit(unit) + + df = DataFrame( + {"A": [1] * 5}, + index=dti, ) # closed must be 'right', 'left', 'both', 'neither' @@ -642,15 +647,17 @@ def test_rolling_cov_offset(self): expected2 = ss.rolling(3, min_periods=1).cov() tm.assert_series_equal(result, expected2) - def test_rolling_on_decreasing_index(self): + def test_rolling_on_decreasing_index(self, unit): # GH-19248, GH-32385 - index = [ - Timestamp("20190101 09:00:30"), - Timestamp("20190101 09:00:27"), - Timestamp("20190101 09:00:20"), - Timestamp("20190101 09:00:18"), - Timestamp("20190101 09:00:10"), - ] + index = DatetimeIndex( + [ + Timestamp("20190101 09:00:30"), + Timestamp("20190101 09:00:27"), + Timestamp("20190101 09:00:20"), + Timestamp("20190101 09:00:18"), + Timestamp("20190101 09:00:10"), + ] + ).as_unit(unit) df = DataFrame({"column": [3, 4, 4, 5, 6]}, index=index) result = df.rolling("5s").min()
Aimed at reducing the diff in #55901
https://api.github.com/repos/pandas-dev/pandas/pulls/55959
2023-11-14T17:41:58Z
2023-11-14T20:59:10Z
2023-11-14T20:59:09Z
2023-11-14T21:46:26Z
BUG: astype, asfreq with non-nano
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 3203dc083faf6..b78924b39073d 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -421,6 +421,7 @@ I/O Period ^^^^^^ - Bug in :class:`Period` addition silently wrapping around instead of raising ``OverflowError`` (:issue:`55503`) +- Bug in casting from :class:`PeriodDtype` with ``astype`` to ``datetime64`` or :class:`DatetimeTZDtype` with non-nanosecond unit incorrectly returning with nanosecond unit (:issue:`55958`) - Plotting @@ -433,6 +434,7 @@ Groupby/resample/rolling - Bug in :class:`.Rolling` where duplicate datetimelike indexes are treated as consecutive rather than equal with ``closed='left'`` and ``closed='neither'`` (:issue:`20712`) - Bug in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, and :meth:`.SeriesGroupBy.idxmax` would not retain :class:`.Categorical` dtype when the index was a :class:`.CategoricalIndex` that contained NA values (:issue:`54234`) - Bug in :meth:`.DataFrameGroupBy.transform` and :meth:`.SeriesGroupBy.transform` when ``observed=False`` and ``f="idxmin"`` or ``f="idxmax"`` would incorrectly raise on unobserved categories (:issue:`54234`) +- Bug in :meth:`DataFrame.asfreq` and :meth:`Series.asfreq` with a :class:`DatetimeIndex` with non-nanosecond resolution incorrectly converting to nanosecond resolution (:issue:`55958`) - Bug in :meth:`DataFrame.resample` not respecting ``closed`` and ``label`` arguments for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55282`) - Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55281`) - Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.MonthBegin` (:issue:`55271`) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index f188b73b4fc64..25659d8738057 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -784,7 +784,8 @@ def astype(self, dtype, copy: bool = True): if lib.is_np_dtype(dtype, "M") or isinstance(dtype, DatetimeTZDtype): # GH#45038 match PeriodIndex behavior. tz = getattr(dtype, "tz", None) - return self.to_timestamp().tz_localize(tz) + unit = dtl.dtype_to_unit(dtype) + return self.to_timestamp().tz_localize(tz).as_unit(unit) return super().astype(dtype, copy=copy) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 0827f9c8da4cc..14cd77ec8559b 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -2782,7 +2782,11 @@ def asfreq( new_obj.index = _asfreq_compat(obj.index, freq) else: - dti = date_range(obj.index.min(), obj.index.max(), freq=freq) + unit = None + if isinstance(obj.index, DatetimeIndex): + # TODO: should we disallow non-DatetimeIndex? + unit = obj.index.unit + dti = date_range(obj.index.min(), obj.index.max(), freq=freq, unit=unit) dti.name = obj.index.name new_obj = obj.reindex(dti, method=method, fill_value=fill_value) if normalize: diff --git a/pandas/tests/indexes/period/methods/test_astype.py b/pandas/tests/indexes/period/methods/test_astype.py index 07595b6b8c1dd..ba60ffd1fff4d 100644 --- a/pandas/tests/indexes/period/methods/test_astype.py +++ b/pandas/tests/indexes/period/methods/test_astype.py @@ -139,10 +139,13 @@ def test_astype_array_fallback(self): expected = np.array([True, True]) tm.assert_numpy_array_equal(result, expected) - def test_period_astype_to_timestamp(self): + def test_period_astype_to_timestamp(self, unit): + # GH#55958 pi = PeriodIndex(["2011-01", "2011-02", "2011-03"], freq="M") - exp = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern") - res = pi.astype("datetime64[ns, US/Eastern]") + exp = DatetimeIndex( + ["2011-01-01", "2011-02-01", "2011-03-01"], tz="US/Eastern" + ).as_unit(unit) + res = pi.astype(f"datetime64[{unit}, US/Eastern]") tm.assert_index_equal(res, exp) assert res.freq == exp.freq diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 21937a35629a0..0bda66de6a785 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1263,10 +1263,14 @@ def test_resample_not_monotonic(unit): ), ], ) -def test_resample_median_bug_1688(dtype): +def test_resample_median_bug_1688(dtype, unit): + # GH#55958 + dti = DatetimeIndex( + [datetime(2012, 1, 1, 0, 0, 0), datetime(2012, 1, 1, 0, 5, 0)] + ).as_unit(unit) df = DataFrame( [1, 2], - index=[datetime(2012, 1, 1, 0, 0, 0), datetime(2012, 1, 1, 0, 5, 0)], + index=dti, dtype=dtype, )
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] 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/55958
2023-11-14T17:03:35Z
2023-11-14T20:57:48Z
2023-11-14T20:57:48Z
2023-11-14T21:46:57Z
TST: split and parametrize
diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 637fc6270b78d..dcec68ab3530d 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -376,7 +376,6 @@ def test_quantile_datetime(self, unit): {"a": Timestamp("2010-07-02 12:00:00").as_unit(unit), "b": 2.5}, index=[0.5], ) - # expected["a"] = expected["a"].dt.as_unit(unit) tm.assert_frame_equal(result, expected) # axis = 1 diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index cd504616b6c5d..f7f94af92743e 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -184,6 +184,7 @@ def test_read_dta2(self, datapath): parsed_115 = self.read_dta(path2) with tm.assert_produces_warning(UserWarning): parsed_117 = self.read_dta(path3) + # FIXME: don't leave commented-out # 113 is buggy due to limits of date format support in Stata # parsed_113 = self.read_dta( # datapath("io", "data", "stata", "stata2_113.dta") diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 21937a35629a0..b0a58070d72ad 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1119,7 +1119,7 @@ def test_nanosecond_resample_error(): tm.assert_series_equal(result, exp) -def test_resample_anchored_intraday(simple_date_range_series, unit): +def test_resample_anchored_intraday(unit): # #1471, #1458 rng = date_range("1/1/2012", "4/1/2012", freq="100min").as_unit(unit) @@ -1141,6 +1141,8 @@ def test_resample_anchored_intraday(simple_date_range_series, unit): assert exp.index.freq == "ME" tm.assert_frame_equal(result, exp) + +def test_resample_anchored_intraday2(unit): rng = date_range("1/1/2012", "4/1/2012", freq="100min").as_unit(unit) df = DataFrame(rng.month, index=rng) @@ -1161,6 +1163,8 @@ def test_resample_anchored_intraday(simple_date_range_series, unit): expected.index = expected.index.as_unit(unit) tm.assert_frame_equal(result, expected) + +def test_resample_anchored_intraday3(simple_date_range_series, unit): ts = simple_date_range_series("2012-04-29 23:00", "2012-04-30 5:00", freq="h") ts.index = ts.index.as_unit(unit) resampled = ts.resample("ME").mean() @@ -1374,8 +1378,17 @@ def test_resample_timegrouper(dates): result = df.groupby(Grouper(freq="ME", key="A")).count() tm.assert_frame_equal(result, expected) + +@pytest.mark.parametrize("dates", [dates1, dates2, dates3]) +def test_resample_timegrouper2(dates): df = DataFrame({"A": dates, "B": np.arange(len(dates)), "C": np.arange(len(dates))}) result = df.set_index("A").resample("ME").count() + + exp_idx = DatetimeIndex( + ["2014-07-31", "2014-08-31", "2014-09-30", "2014-10-31", "2014-11-30"], + freq="ME", + name="A", + ) expected = DataFrame( {"B": [1, 0, 2, 2, 1], "C": [1, 0, 2, 2, 1]}, index=exp_idx, @@ -1574,6 +1587,8 @@ def test_resample_dst_anchor(unit): ), ) + +def test_resample_dst_anchor2(unit): dti = date_range( "2013-09-30", "2013-11-02", freq="30Min", tz="Europe/Paris" ).as_unit(unit) @@ -1581,73 +1596,86 @@ def test_resample_dst_anchor(unit): df = DataFrame({"a": values, "b": values, "c": values}, index=dti, dtype="int64") how = {"a": "min", "b": "max", "c": "count"} + rs = df.resample("W-MON") + result = rs.agg(how)[["a", "b", "c"]] + expected = DataFrame( + { + "a": [0, 48, 384, 720, 1056, 1394], + "b": [47, 383, 719, 1055, 1393, 1586], + "c": [48, 336, 336, 336, 338, 193], + }, + index=date_range( + "9/30/2013", "11/4/2013", freq="W-MON", tz="Europe/Paris" + ).as_unit(unit), + ) tm.assert_frame_equal( - df.resample("W-MON").agg(how)[["a", "b", "c"]], - DataFrame( - { - "a": [0, 48, 384, 720, 1056, 1394], - "b": [47, 383, 719, 1055, 1393, 1586], - "c": [48, 336, 336, 336, 338, 193], - }, - index=date_range( - "9/30/2013", "11/4/2013", freq="W-MON", tz="Europe/Paris" - ).as_unit(unit), - ), + result, + expected, "W-MON Frequency", ) + rs2 = df.resample("2W-MON") + result2 = rs2.agg(how)[["a", "b", "c"]] + expected2 = DataFrame( + { + "a": [0, 48, 720, 1394], + "b": [47, 719, 1393, 1586], + "c": [48, 672, 674, 193], + }, + index=date_range( + "9/30/2013", "11/11/2013", freq="2W-MON", tz="Europe/Paris" + ).as_unit(unit), + ) tm.assert_frame_equal( - df.resample("2W-MON").agg(how)[["a", "b", "c"]], - DataFrame( - { - "a": [0, 48, 720, 1394], - "b": [47, 719, 1393, 1586], - "c": [48, 672, 674, 193], - }, - index=date_range( - "9/30/2013", "11/11/2013", freq="2W-MON", tz="Europe/Paris" - ).as_unit(unit), - ), + result2, + expected2, "2W-MON Frequency", ) - tm.assert_frame_equal( - df.resample("MS").agg(how)[["a", "b", "c"]], - DataFrame( - {"a": [0, 48, 1538], "b": [47, 1537, 1586], "c": [48, 1490, 49]}, - index=date_range( - "9/1/2013", "11/1/2013", freq="MS", tz="Europe/Paris" - ).as_unit(unit), + rs3 = df.resample("MS") + result3 = rs3.agg(how)[["a", "b", "c"]] + expected3 = DataFrame( + {"a": [0, 48, 1538], "b": [47, 1537, 1586], "c": [48, 1490, 49]}, + index=date_range("9/1/2013", "11/1/2013", freq="MS", tz="Europe/Paris").as_unit( + unit ), + ) + tm.assert_frame_equal( + result3, + expected3, "MS Frequency", ) + rs4 = df.resample("2MS") + result4 = rs4.agg(how)[["a", "b", "c"]] + expected4 = DataFrame( + {"a": [0, 1538], "b": [1537, 1586], "c": [1538, 49]}, + index=date_range( + "9/1/2013", "11/1/2013", freq="2MS", tz="Europe/Paris" + ).as_unit(unit), + ) tm.assert_frame_equal( - df.resample("2MS").agg(how)[["a", "b", "c"]], - DataFrame( - {"a": [0, 1538], "b": [1537, 1586], "c": [1538, 49]}, - index=date_range( - "9/1/2013", "11/1/2013", freq="2MS", tz="Europe/Paris" - ).as_unit(unit), - ), + result4, + expected4, "2MS Frequency", ) df_daily = df["10/26/2013":"10/29/2013"] + rs_d = df_daily.resample("D") + result_d = rs_d.agg({"a": "min", "b": "max", "c": "count"})[["a", "b", "c"]] + expected_d = DataFrame( + { + "a": [1248, 1296, 1346, 1394], + "b": [1295, 1345, 1393, 1441], + "c": [48, 50, 48, 48], + }, + index=date_range( + "10/26/2013", "10/29/2013", freq="D", tz="Europe/Paris" + ).as_unit(unit), + ) tm.assert_frame_equal( - df_daily.resample("D").agg({"a": "min", "b": "max", "c": "count"})[ - ["a", "b", "c"] - ], - DataFrame( - { - "a": [1248, 1296, 1346, 1394], - "b": [1295, 1345, 1393, 1441], - "c": [48, 50, 48, 48], - }, - index=date_range( - "10/26/2013", "10/29/2013", freq="D", tz="Europe/Paris" - ).as_unit(unit), - ), + result_d, + expected_d, "D Frequency", ) @@ -1728,9 +1756,8 @@ def test_resample_with_nat(unit): "1970-01-01 00:00:01", "1970-01-01 00:00:02", ] - ) + ).as_unit(unit) frame = DataFrame([2, 3, 5, 7, 11], index=index) - frame.index = frame.index.as_unit(unit) index_1s = DatetimeIndex( ["1970-01-01 00:00:00", "1970-01-01 00:00:01", "1970-01-01 00:00:02"] @@ -1789,7 +1816,14 @@ def f(data, add_arg): expected = series.resample("D").mean().multiply(multiplier) tm.assert_series_equal(result, expected) + +def test_resample_apply_with_additional_args2(): # Testing dataframe + def f(data, add_arg): + return np.mean(data) * add_arg + + multiplier = 10 + df = DataFrame({"A": 1, "B": 2}, index=date_range("2017", periods=10)) msg = "DataFrameGroupBy.resample operated on the grouping columns" with tm.assert_produces_warning(FutureWarning, match=msg): diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index b8b2325f03889..80bb18a6a2a98 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -174,6 +174,7 @@ def test_annual_upsample(self, simple_period_range_series): exp = df["a"].resample("D").ffill() tm.assert_series_equal(rdf["a"], exp) + def test_annual_upsample2(self): rng = period_range("2000", "2003", freq="Y-DEC") ts = Series([1, 2, 3, 4], index=rng) @@ -258,20 +259,29 @@ def test_resample_incompat_freq(self): "Frequency <MonthEnd> cannot be resampled to <Week: weekday=6>, " "as they are not sub or super periods" ) + pi = period_range(start="2000", periods=3, freq="M") + ser = Series(range(3), index=pi) + rs = ser.resample("W") with pytest.raises(IncompatibleFrequency, match=msg): - Series( - range(3), index=period_range(start="2000", periods=3, freq="M") - ).resample("W").mean() + # TODO: should this raise at the resample call instead of at the mean call? + rs.mean() - def test_with_local_timezone_pytz(self): + @pytest.mark.parametrize( + "tz", + [ + pytz.timezone("America/Los_Angeles"), + dateutil.tz.gettz("America/Los_Angeles"), + ], + ) + def test_with_local_timezone(self, tz): # see gh-5430 - local_timezone = pytz.timezone("America/Los_Angeles") + local_timezone = tz start = datetime(year=2013, month=11, day=1, hour=0, minute=0, tzinfo=pytz.utc) # 1 day later end = datetime(year=2013, month=11, day=2, hour=0, minute=0, tzinfo=pytz.utc) - index = date_range(start, end, freq="h") + index = date_range(start, end, freq="h", name="idx") series = Series(1, index=index) series = series.tz_convert(local_timezone) @@ -280,52 +290,30 @@ def test_with_local_timezone_pytz(self): # Create the expected series # Index is moved back a day with the timezone conversion from UTC to # Pacific - expected_index = period_range(start=start, end=end, freq="D") - offsets.Day() + expected_index = ( + period_range(start=start, end=end, freq="D", name="idx") - offsets.Day() + ) expected = Series(1.0, index=expected_index) tm.assert_series_equal(result, expected) - def test_resample_with_pytz(self): + @pytest.mark.parametrize( + "tz", + [ + pytz.timezone("America/Los_Angeles"), + dateutil.tz.gettz("America/Los_Angeles"), + ], + ) + def test_resample_with_tz(self, tz): # GH 13238 - s = Series( - 2, index=date_range("2017-01-01", periods=48, freq="h", tz="US/Eastern") - ) - result = s.resample("D").mean() + ser = Series(2, index=date_range("2017-01-01", periods=48, freq="h", tz=tz)) + result = ser.resample("D").mean() expected = Series( 2.0, - index=pd.DatetimeIndex( - ["2017-01-01", "2017-01-02"], tz="US/Eastern", freq="D" - ), + index=pd.DatetimeIndex(["2017-01-01", "2017-01-02"], tz=tz, freq="D"), ) tm.assert_series_equal(result, expected) # Especially assert that the timezone is LMT for pytz - assert result.index.tz == pytz.timezone("US/Eastern") - - def test_with_local_timezone_dateutil(self): - # see gh-5430 - local_timezone = "dateutil/America/Los_Angeles" - - start = datetime( - year=2013, month=11, day=1, hour=0, minute=0, tzinfo=dateutil.tz.tzutc() - ) - # 1 day later - end = datetime( - year=2013, month=11, day=2, hour=0, minute=0, tzinfo=dateutil.tz.tzutc() - ) - - index = date_range(start, end, freq="h", name="idx") - - series = Series(1, index=index) - series = series.tz_convert(local_timezone) - result = series.resample("D", kind="period").mean() - - # Create the expected series - # Index is moved back a day with the timezone conversion from UTC to - # Pacific - expected_index = ( - period_range(start=start, end=end, freq="D", name="idx") - offsets.Day() - ) - expected = Series(1.0, index=expected_index) - tm.assert_series_equal(result, expected) + assert result.index.tz == tz def test_resample_nonexistent_time_bin_edge(self): # GH 19375 @@ -336,6 +324,7 @@ def test_resample_nonexistent_time_bin_edge(self): result = expected.resample("900s").mean() tm.assert_series_equal(result, expected) + def test_resample_nonexistent_time_bin_edge2(self): # GH 23742 index = date_range(start="2017-10-10", end="2017-10-20", freq="1h") index = index.tz_localize("UTC").tz_convert("America/Sao_Paulo") @@ -420,6 +409,7 @@ def test_resample_to_quarterly_start_end(self, simple_period_range_series, how): expected = ts.asfreq("Q-MAR", how=how) expected = expected.reindex(result.index, method="ffill") + # FIXME: don't leave commented-out # .to_timestamp('D') # expected = expected.resample('Q-MAR').ffill() @@ -510,6 +500,7 @@ def test_resample_tz_localized(self): # it works result = ts_local.resample("D").mean() + def test_resample_tz_localized2(self): # #2245 idx = date_range( "2001-09-20 15:59", "2001-09-20 16:00", freq="min", tz="Australia/Sydney" @@ -528,6 +519,7 @@ def test_resample_tz_localized(self): expected = Series([1.5], index=ex_index) tm.assert_series_equal(result, expected) + def test_resample_tz_localized3(self): # GH 6397 # comparing an offset that doesn't propagate tz's rng = date_range("1/1/2011", periods=20000, freq="h") @@ -694,6 +686,7 @@ def test_evenly_divisible_with_no_extra_bins(self): ) tm.assert_frame_equal(result, expected) + def test_evenly_divisible_with_no_extra_bins2(self): index = date_range(start="2001-5-4", periods=28) df = DataFrame( [ diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index ea53dea06129d..fd02216934576 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -695,8 +695,10 @@ def test_groupby_resample_on_index_with_list_of_keys_missing_column(): name="date", ), ) + gb = df.groupby("group") + rs = gb.resample("2D") with pytest.raises(KeyError, match="Columns not found"): - df.groupby("group").resample("2D")[["val_not_in_dataframe"]].mean() + rs[["val_not_in_dataframe"]] @pytest.mark.parametrize("kind", ["datetime", "period"])
- [ ] 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/55957
2023-11-14T16:44:50Z
2023-11-14T20:56:52Z
2023-11-14T20:56:51Z
2023-11-14T20:56:57Z
BUG: disallow how keyword in shared-ax plotting
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index efa4a52993a90..6755ee59f3097 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -424,6 +424,7 @@ Period Plotting ^^^^^^^^ - Bug in :meth:`DataFrame.plot.box` with ``vert=False`` and a matplotlib ``Axes`` created with ``sharey=True`` (:issue:`54941`) +- Bug in :meth:`Series.plot` when reusing an ``ax`` object failing to raise when a ``how`` keyword is passed (:issue:`55953`) - Groupby/resample/rolling diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 714ee9d162a25..5471305b03baf 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -61,6 +61,13 @@ def maybe_resample(series: Series, ax: Axes, kwargs: dict[str, Any]): # resample against axes freq if necessary + + if "how" in kwargs: + raise ValueError( + "'how' is not a valid keyword for plotting functions. If plotting " + "multiple objects on shared axes, resample manually first." + ) + freq, ax_freq = _get_freq(ax, series) if freq is None: # pragma: no cover @@ -79,7 +86,7 @@ def maybe_resample(series: Series, ax: Axes, kwargs: dict[str, Any]): ) freq = ax_freq elif _is_sup(freq, ax_freq): # one is weekly - how = kwargs.pop("how", "last") + how = "last" series = getattr(series.resample("D"), how)().dropna() series = getattr(series.resample(ax_freq), how)().dropna() freq = ax_freq diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 668379ad08e59..0f66d94535053 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -916,6 +916,21 @@ def test_nat_handling(self): assert s.index.min() <= Series(xdata).min() assert Series(xdata).max() <= s.index.max() + def test_to_weekly_resampling_disallow_how_kwd(self): + idxh = date_range("1/1/1999", periods=52, freq="W") + idxl = date_range("1/1/1999", periods=12, freq="ME") + high = Series(np.random.default_rng(2).standard_normal(len(idxh)), idxh) + low = Series(np.random.default_rng(2).standard_normal(len(idxl)), idxl) + _, ax = mpl.pyplot.subplots() + high.plot(ax=ax) + + msg = ( + "'how' is not a valid keyword for plotting functions. If plotting " + "multiple objects on shared axes, resample manually first." + ) + with pytest.raises(ValueError, match=msg): + low.plot(ax=ax, how="foo") + def test_to_weekly_resampling(self): idxh = date_range("1/1/1999", periods=52, freq="W") idxl = date_range("1/1/1999", periods=12, freq="ME")
- [ ] 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. We could make this a deprecation, but im super-skeptical that anyone is passing this.
https://api.github.com/repos/pandas-dev/pandas/pulls/55953
2023-11-14T01:52:09Z
2023-11-14T20:59:41Z
2023-11-14T20:59:41Z
2023-11-14T21:45:25Z
DOC: Updates typo in to_timedelta docs
diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 8909776d91369..df46837d4deb3 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -121,7 +121,7 @@ def to_timedelta( * 'us' / 'microseconds' / 'microsecond' / 'micro' / 'micros' / 'U' * 'ns' / 'nanoseconds' / 'nano' / 'nanos' / 'nanosecond' / 'N' - Must not be specified when `arg` context strings and ``errors="raise"``. + Must not be specified when `arg` contains strings and ``errors="raise"``. .. deprecated:: 2.2.0 Units 'H', 'T', 'S', 'L', 'U' and 'N' are deprecated and will be removed
- [x] closes #55947 - [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/55952
2023-11-14T01:33:26Z
2023-11-14T11:34:53Z
2023-11-14T11:34:53Z
2023-11-14T16:29:52Z
REF: simplify objects_to_datetime64ns
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index e30177a43f6b8..6efff2483e1ae 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2250,9 +2250,7 @@ def _sequence_to_dt64( ) return result, tz, None else: - # data comes back here as either i8 to denote UTC timestamps - # or M8[ns] to denote wall times - converted, inferred_tz = objects_to_datetime64ns( + converted, inferred_tz = objects_to_datetime64( data, dayfirst=dayfirst, yearfirst=yearfirst, @@ -2262,13 +2260,13 @@ def _sequence_to_dt64( copy = False if tz and inferred_tz: # two timezones: convert to intended from base UTC repr - assert converted.dtype == "i8" - # GH#42505 - # by convention, these are _already_ UTC, e.g + # GH#42505 by convention, these are _already_ UTC + assert converted.dtype == out_dtype, converted.dtype result = converted.view(out_dtype) elif inferred_tz: tz = inferred_tz + assert converted.dtype == out_dtype, converted.dtype result = converted.view(out_dtype) else: @@ -2360,7 +2358,7 @@ def _construct_from_dt64_naive( return result, copy -def objects_to_datetime64ns( +def objects_to_datetime64( data: np.ndarray, dayfirst, yearfirst, @@ -2388,10 +2386,11 @@ def objects_to_datetime64ns( Returns ------- result : ndarray - np.int64 dtype if returned values represent UTC timestamps - np.datetime64[ns] if returned values represent wall times + np.datetime64[out_unit] if returned values represent wall times or UTC + timestamps. object if mixed timezones inferred_tz : tzinfo or None + If not None, then the datetime64 values in `result` denote UTC timestamps. Raises ------ @@ -2414,11 +2413,8 @@ def objects_to_datetime64ns( if tz_parsed is not None: # We can take a shortcut since the datetime64 numpy array # is in UTC - # Return i8 values to denote unix timestamps - return result.view("i8"), tz_parsed + return result, tz_parsed elif result.dtype.kind == "M": - # returning M8[ns] denotes wall-times; since tz is None - # the distinction is a thin one return result, tz_parsed elif result.dtype == object: # GH#23675 when called via `pd.to_datetime`, returning an object-dtype diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 33ac5a169b08d..ea5e6e46f58ec 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -71,7 +71,7 @@ from pandas.core.arrays.base import ExtensionArray from pandas.core.arrays.datetimes import ( maybe_convert_dtype, - objects_to_datetime64ns, + objects_to_datetime64, tz_to_dtype, ) from pandas.core.construction import extract_array @@ -485,7 +485,7 @@ def _convert_listlike_datetimes( if format is not None and format != "mixed": return _array_strptime_with_fallback(arg, name, utc, format, exact, errors) - result, tz_parsed = objects_to_datetime64ns( + result, tz_parsed = objects_to_datetime64( arg, dayfirst=dayfirst, yearfirst=yearfirst, @@ -499,7 +499,7 @@ def _convert_listlike_datetimes( # is in UTC dtype = cast(DatetimeTZDtype, tz_to_dtype(tz_parsed)) dt64_values = result.view(f"M8[{dtype.unit}]") - dta = DatetimeArray(dt64_values, dtype=dtype) + dta = DatetimeArray._simple_new(dt64_values, dtype=dtype) return DatetimeIndex._simple_new(dta, name=name) return _box_as_indexlike(result, utc=utc, name=name)
This will allow me to simplify #55901 a bit.
https://api.github.com/repos/pandas-dev/pandas/pulls/55950
2023-11-13T22:29:54Z
2023-11-14T01:05:29Z
2023-11-14T01:05:29Z
2023-11-14T01:15:38Z
PERF: assert_frame_equal and assert_series_equal for frames/series with a MultiIndex
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index efa4a52993a90..b313478eb4985 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -304,6 +304,7 @@ Other Deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ +- Performance improvement in :func:`.testing.assert_frame_equal` and :func:`.testing.assert_series_equal` for objects indexed by a :class:`MultiIndex` (:issue:`55949`) - Performance improvement in :func:`concat` with ``axis=1`` and objects with unaligned indexes (:issue:`55084`) - Performance improvement in :func:`merge_asof` when ``by`` is not ``None`` (:issue:`55580`, :issue:`55678`) - Performance improvement in :func:`read_stata` for files with many variables (:issue:`55515`) diff --git a/pandas/_libs/testing.pyx b/pandas/_libs/testing.pyx index 4ba7bce51ed64..aed0f4b082d4e 100644 --- a/pandas/_libs/testing.pyx +++ b/pandas/_libs/testing.pyx @@ -78,7 +78,7 @@ cpdef assert_almost_equal(a, b, robj : str, default None Specify right object name being compared, internally used to show appropriate assertion message. - index_values : ndarray, default None + index_values : Index | ndarray, default None Specify shared index values of objects being compared, internally used to show appropriate assertion message. diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 5f14d46be8e70..8e49fcfb355fa 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -283,22 +283,37 @@ def _get_ilevel_values(index, level): right = cast(MultiIndex, right) for level in range(left.nlevels): - # cannot use get_level_values here because it can change dtype - llevel = _get_ilevel_values(left, level) - rlevel = _get_ilevel_values(right, level) - lobj = f"MultiIndex level [{level}]" - assert_index_equal( - llevel, - rlevel, - exact=exact, - check_names=check_names, - check_exact=check_exact, - check_categorical=check_categorical, - rtol=rtol, - atol=atol, - obj=lobj, - ) + try: + # try comparison on levels/codes to avoid densifying MultiIndex + assert_index_equal( + left.levels[level], + right.levels[level], + exact=exact, + check_names=check_names, + check_exact=check_exact, + check_categorical=check_categorical, + rtol=rtol, + atol=atol, + obj=lobj, + ) + assert_numpy_array_equal(left.codes[level], right.codes[level]) + except AssertionError: + # cannot use get_level_values here because it can change dtype + llevel = _get_ilevel_values(left, level) + rlevel = _get_ilevel_values(right, level) + + assert_index_equal( + llevel, + rlevel, + exact=exact, + check_names=check_names, + check_exact=check_exact, + check_categorical=check_categorical, + rtol=rtol, + atol=atol, + obj=lobj, + ) # get_level_values may change dtype _check_types(left.levels[level], right.levels[level], obj=obj) @@ -576,6 +591,9 @@ def raise_assert_detail( {message}""" + if isinstance(index_values, Index): + index_values = np.array(index_values) + if isinstance(index_values, np.ndarray): msg += f"\n[index]: {pprint_thing(index_values)}" @@ -630,7 +648,7 @@ def assert_numpy_array_equal( obj : str, default 'numpy array' Specify object name being compared, internally used to show appropriate assertion message. - index_values : numpy.ndarray, default None + index_values : Index | numpy.ndarray, default None optional index (shared by both left and right), used in output. """ __tracebackhide__ = True @@ -701,7 +719,7 @@ def assert_extension_array_equal( The two arrays to compare. check_dtype : bool, default True Whether to check if the ExtensionArray dtypes are identical. - index_values : numpy.ndarray, default None + index_values : Index | numpy.ndarray, default None Optional index (shared by both left and right), used in output. check_exact : bool, default False Whether to compare number exactly. @@ -932,7 +950,7 @@ def assert_series_equal( left_values, right_values, check_dtype=check_dtype, - index_values=np.asarray(left.index), + index_values=left.index, obj=str(obj), ) else: @@ -941,7 +959,7 @@ def assert_series_equal( right_values, check_dtype=check_dtype, obj=str(obj), - index_values=np.asarray(left.index), + index_values=left.index, ) elif check_datetimelike_compat and ( needs_i8_conversion(left.dtype) or needs_i8_conversion(right.dtype) @@ -972,7 +990,7 @@ def assert_series_equal( atol=atol, check_dtype=bool(check_dtype), obj=str(obj), - index_values=np.asarray(left.index), + index_values=left.index, ) elif isinstance(left.dtype, ExtensionDtype) and isinstance( right.dtype, ExtensionDtype @@ -983,7 +1001,7 @@ def assert_series_equal( rtol=rtol, atol=atol, check_dtype=check_dtype, - index_values=np.asarray(left.index), + index_values=left.index, obj=str(obj), ) elif is_extension_array_dtype_and_needs_i8_conversion( @@ -993,7 +1011,7 @@ def assert_series_equal( left._values, right._values, check_dtype=check_dtype, - index_values=np.asarray(left.index), + index_values=left.index, obj=str(obj), ) elif needs_i8_conversion(left.dtype) and needs_i8_conversion(right.dtype): @@ -1002,7 +1020,7 @@ def assert_series_equal( left._values, right._values, check_dtype=check_dtype, - index_values=np.asarray(left.index), + index_values=left.index, obj=str(obj), ) else: @@ -1013,7 +1031,7 @@ def assert_series_equal( atol=atol, check_dtype=bool(check_dtype), obj=str(obj), - index_values=np.asarray(left.index), + index_values=left.index, ) # metadata comparison diff --git a/pandas/tests/frame/methods/test_value_counts.py b/pandas/tests/frame/methods/test_value_counts.py index f30db91f82b60..4136d641ef67f 100644 --- a/pandas/tests/frame/methods/test_value_counts.py +++ b/pandas/tests/frame/methods/test_value_counts.py @@ -147,7 +147,7 @@ def test_data_frame_value_counts_dropna_false(nulls_fixture): index=pd.MultiIndex( levels=[ pd.Index(["Anne", "Beth", "John"]), - pd.Index(["Louise", "Smith", nulls_fixture]), + pd.Index(["Louise", "Smith", np.nan]), ], codes=[[0, 1, 2, 2], [2, 0, 1, 2]], names=["first_name", "middle_name"],
- [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.2.0.rst` file if fixing a bug or adding a new feature. ``` import pandas as pd N = 500 dates = pd.date_range("2000-01-01", periods=N) strings = pd._testing.makeStringIndex(N) mi = pd.MultiIndex.from_product([dates, strings]) df1 = pd.DataFrame({"a": 1}, index=mi) df2 = df1.copy(deep=True) %timeit pd.testing.assert_frame_equal(df1, df2) # 4.27 s ± 245 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) -> main # 10 ms ± 415 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) -> PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/55949
2023-11-13T22:27:17Z
2023-11-14T15:54:26Z
2023-11-14T15:54:26Z
2023-11-16T12:56:48Z
REF: melt
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 3203dc083faf6..b00064a107800 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -442,8 +442,8 @@ Reshaping - Bug in :func:`concat` ignoring ``sort`` parameter when passed :class:`DatetimeIndex` indexes (:issue:`54769`) - Bug in :func:`merge_asof` raising ``TypeError`` when ``by`` dtype is not ``object``, ``int64``, or ``uint64`` (:issue:`22794`) - Bug in :func:`merge` returning columns in incorrect order when left and/or right is empty (:issue:`51929`) +- Bug in :meth:`pandas.DataFrame.melt` where an exception was raised if ``var_name`` was not a string (:issue:`55948`) - Bug in :meth:`pandas.DataFrame.melt` where it would not preserve the datetime (:issue:`55254`) -- Sparse ^^^^^^ diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 03423a85db853..e333d263a6b7a 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -13,11 +13,7 @@ import pandas.core.algorithms as algos from pandas.core.arrays import Categorical -import pandas.core.common as com -from pandas.core.indexes.api import ( - Index, - MultiIndex, -) +from pandas.core.indexes.api import MultiIndex from pandas.core.reshape.concat import concat from pandas.core.reshape.util import tile_compat from pandas.core.shared_docs import _shared_docs @@ -31,6 +27,20 @@ from pandas import DataFrame +def ensure_list_vars(arg_vars, variable: str, columns) -> list: + if arg_vars is not None: + if not is_list_like(arg_vars): + return [arg_vars] + elif isinstance(columns, MultiIndex) and not isinstance(arg_vars, list): + raise ValueError( + f"{variable} must be a list of tuples when columns are a MultiIndex" + ) + else: + return list(arg_vars) + else: + return [] + + @Appender(_shared_docs["melt"] % {"caller": "pd.melt(df, ", "other": "DataFrame.melt"}) def melt( frame: DataFrame, @@ -41,61 +51,35 @@ def melt( col_level=None, ignore_index: bool = True, ) -> DataFrame: - # If multiindex, gather names of columns on all level for checking presence - # of `id_vars` and `value_vars` - if isinstance(frame.columns, MultiIndex): - cols = [x for c in frame.columns for x in c] - else: - cols = list(frame.columns) - if value_name in frame.columns: raise ValueError( f"value_name ({value_name}) cannot match an element in " "the DataFrame columns." ) + id_vars = ensure_list_vars(id_vars, "id_vars", frame.columns) + value_vars_was_not_none = value_vars is not None + value_vars = ensure_list_vars(value_vars, "value_vars", frame.columns) - if id_vars is not None: - if not is_list_like(id_vars): - id_vars = [id_vars] - elif isinstance(frame.columns, MultiIndex) and not isinstance(id_vars, list): - raise ValueError( - "id_vars must be a list of tuples when columns are a MultiIndex" - ) - else: - # Check that `id_vars` are in frame - id_vars = list(id_vars) - missing = Index(com.flatten(id_vars)).difference(cols) - if not missing.empty: - raise KeyError( - "The following 'id_vars' are not present " - f"in the DataFrame: {list(missing)}" - ) - else: - id_vars = [] - - if value_vars is not None: - if not is_list_like(value_vars): - value_vars = [value_vars] - elif isinstance(frame.columns, MultiIndex) and not isinstance(value_vars, list): - raise ValueError( - "value_vars must be a list of tuples when columns are a MultiIndex" - ) - else: - value_vars = list(value_vars) - # Check that `value_vars` are in frame - missing = Index(com.flatten(value_vars)).difference(cols) - if not missing.empty: - raise KeyError( - "The following 'value_vars' are not present in " - f"the DataFrame: {list(missing)}" - ) + if id_vars or value_vars: if col_level is not None: - idx = frame.columns.get_level_values(col_level).get_indexer( - id_vars + value_vars + level = frame.columns.get_level_values(col_level) + else: + level = frame.columns + labels = id_vars + value_vars + idx = level.get_indexer_for(labels) + missing = idx == -1 + if missing.any(): + missing_labels = [ + lab for lab, not_found in zip(labels, missing) if not_found + ] + raise KeyError( + "The following id_vars or value_vars are not present in " + f"the DataFrame: {missing_labels}" ) + if value_vars_was_not_none: + frame = frame.iloc[:, algos.unique(idx)] else: - idx = algos.unique(frame.columns.get_indexer_for(id_vars + value_vars)) - frame = frame.iloc[:, idx] + frame = frame.copy() else: frame = frame.copy() @@ -113,24 +97,26 @@ def melt( var_name = [ frame.columns.name if frame.columns.name is not None else "variable" ] - if isinstance(var_name, str): + elif is_list_like(var_name): + raise ValueError(f"{var_name=} must be a scalar.") + else: var_name = [var_name] - N, K = frame.shape - K -= len(id_vars) + num_rows, K = frame.shape + num_cols_adjusted = K - len(id_vars) mdata: dict[Hashable, AnyArrayLike] = {} for col in id_vars: id_data = frame.pop(col) if not isinstance(id_data.dtype, np.dtype): # i.e. ExtensionDtype - if K > 0: - mdata[col] = concat([id_data] * K, ignore_index=True) + if num_cols_adjusted > 0: + mdata[col] = concat([id_data] * num_cols_adjusted, ignore_index=True) else: # We can't concat empty list. (GH 46044) mdata[col] = type(id_data)([], name=id_data.name, dtype=id_data.dtype) else: - mdata[col] = np.tile(id_data._values, K) + mdata[col] = np.tile(id_data._values, num_cols_adjusted) mcolumns = id_vars + var_name + [value_name] @@ -143,12 +129,12 @@ def melt( else: mdata[value_name] = frame._values.ravel("F") for i, col in enumerate(var_name): - mdata[col] = frame.columns._get_level_values(i).repeat(N) + mdata[col] = frame.columns._get_level_values(i).repeat(num_rows) result = frame._constructor(mdata, columns=mcolumns) if not ignore_index: - result.index = tile_compat(frame.index, K) + result.index = tile_compat(frame.index, num_cols_adjusted) return result diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index 4bbbd9266a94a..fdb8ef1cc5dad 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -208,17 +208,17 @@ Parameters ---------- -id_vars : tuple, list, or ndarray, optional +id_vars : scalar, tuple, list, or ndarray, optional Column(s) to use as identifier variables. -value_vars : tuple, list, or ndarray, optional +value_vars : scalar, tuple, list, or ndarray, optional Column(s) to unpivot. If not specified, uses all columns that are not set as `id_vars`. -var_name : scalar +var_name : scalar, default None Name to use for the 'variable' column. If None it uses ``frame.columns.name`` or 'variable'. value_name : scalar, default 'value' Name to use for the 'value' column, can't be an existing column label. -col_level : int or str, optional +col_level : scalar, optional If columns are a MultiIndex then use this level to melt. ignore_index : bool, default True If True, original index is ignored. If False, the original index is retained. diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index ef748e264188c..b10436889d829 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -327,32 +327,28 @@ def test_melt_missing_columns_raises(self): ) # Try to melt with missing `value_vars` column name - msg = "The following '{Var}' are not present in the DataFrame: {Col}" - with pytest.raises( - KeyError, match=msg.format(Var="value_vars", Col="\\['C'\\]") - ): + msg = "The following id_vars or value_vars are not present in the DataFrame:" + with pytest.raises(KeyError, match=msg): df.melt(["a", "b"], ["C", "d"]) # Try to melt with missing `id_vars` column name - with pytest.raises(KeyError, match=msg.format(Var="id_vars", Col="\\['A'\\]")): + with pytest.raises(KeyError, match=msg): df.melt(["A", "b"], ["c", "d"]) # Multiple missing with pytest.raises( KeyError, - match=msg.format(Var="id_vars", Col="\\['not_here', 'or_there'\\]"), + match=msg, ): df.melt(["a", "b", "not_here", "or_there"], ["c", "d"]) # Multiindex melt fails if column is missing from multilevel melt multi = df.copy() multi.columns = [list("ABCD"), list("abcd")] - with pytest.raises(KeyError, match=msg.format(Var="id_vars", Col="\\['E'\\]")): + with pytest.raises(KeyError, match=msg): multi.melt([("E", "a")], [("B", "b")]) # Multiindex fails if column is missing from single level melt - with pytest.raises( - KeyError, match=msg.format(Var="value_vars", Col="\\['F'\\]") - ): + with pytest.raises(KeyError, match=msg): multi.melt(["A"], ["F"], col_level=0) def test_melt_mixed_int_str_id_vars(self): @@ -500,6 +496,40 @@ def test_melt_preserves_datetime(self): ) tm.assert_frame_equal(result, expected) + def test_melt_allows_non_scalar_id_vars(self): + df = DataFrame( + data={"a": [1, 2, 3], "b": [4, 5, 6]}, + index=["11", "22", "33"], + ) + result = df.melt( + id_vars="a", + var_name=0, + value_name=1, + ) + expected = DataFrame({"a": [1, 2, 3], 0: ["b"] * 3, 1: [4, 5, 6]}) + tm.assert_frame_equal(result, expected) + + def test_melt_allows_non_string_var_name(self): + df = DataFrame( + data={"a": [1, 2, 3], "b": [4, 5, 6]}, + index=["11", "22", "33"], + ) + result = df.melt( + id_vars=["a"], + var_name=0, + value_name=1, + ) + expected = DataFrame({"a": [1, 2, 3], 0: ["b"] * 3, 1: [4, 5, 6]}) + tm.assert_frame_equal(result, expected) + + def test_melt_non_scalar_var_name_raises(self): + df = DataFrame( + data={"a": [1, 2, 3], "b": [4, 5, 6]}, + index=["11", "22", "33"], + ) + with pytest.raises(ValueError, match=r".* must be a scalar."): + df.melt(id_vars=["a"], var_name=[1, 2]) + class TestLreshape: def test_pairs(self):
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55948
2023-11-13T22:13:59Z
2023-11-14T20:37:54Z
2023-11-14T20:37:54Z
2023-11-14T20:37:58Z
REF: Remove un-used attribute-pinning in plotting
diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 848fb77c942fb..0eb3318ac96c5 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -983,10 +983,7 @@ def __init__( def _get_default_locs(self, vmin, vmax): """Returns the default locations of ticks.""" - if self.plot_obj.date_axis_info is None: - self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) - - locator = self.plot_obj.date_axis_info + locator = self.finder(vmin, vmax, self.freq) if self.isminor: return np.compress(locator["min"], locator["val"]) @@ -997,9 +994,6 @@ def __call__(self): # axis calls Locator.set_axis inside set_m<xxxx>_formatter vi = tuple(self.axis.get_view_interval()) - if vi != self.plot_obj.view_interval: - self.plot_obj.date_axis_info = None - self.plot_obj.view_interval = vi vmin, vmax = vi if vmax < vmin: vmin, vmax = vmax, vmin @@ -1072,9 +1066,7 @@ def __init__( def _set_default_format(self, vmin, vmax): """Returns the default ticks spacing.""" - if self.plot_obj.date_axis_info is None: - self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) - info = self.plot_obj.date_axis_info + info = self.finder(vmin, vmax, self.freq) if self.isminor: format = np.compress(info["min"] & np.logical_not(info["maj"]), info) @@ -1090,10 +1082,7 @@ def set_locs(self, locs) -> None: self.locs = locs - (vmin, vmax) = vi = tuple(self.axis.get_view_interval()) - if vi != self.plot_obj.view_interval: - self.plot_obj.date_axis_info = None - self.plot_obj.view_interval = vi + (vmin, vmax) = tuple(self.axis.get_view_interval()) if vmax < vmin: (vmin, vmax) = (vmax, vmin) self._set_default_format(vmin, vmax) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 6be8284d2a0be..3c96683dca981 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1590,12 +1590,12 @@ def _ts_plot(self, ax: Axes, x, data: Series, style=None, **kwds): freq, data = maybe_resample(data, ax, kwds) # Set ax with freq info - decorate_axes(ax, freq, kwds) + decorate_axes(ax, freq) # digging deeper if hasattr(ax, "left_ax"): - decorate_axes(ax.left_ax, freq, kwds) + decorate_axes(ax.left_ax, freq) if hasattr(ax, "right_ax"): - decorate_axes(ax.right_ax, freq, kwds) + decorate_axes(ax.right_ax, freq) # TODO #54485 ax._plot_data.append((data, self._kind, kwds)) # type: ignore[attr-defined] diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index f0b68e5dde450..6d3579c7f7adb 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -111,8 +111,8 @@ def _is_sup(f1: str, f2: str) -> bool: def _upsample_others(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None: legend = ax.get_legend() - lines, labels = _replot_ax(ax, freq, kwargs) - _replot_ax(ax, freq, kwargs) + lines, labels = _replot_ax(ax, freq) + _replot_ax(ax, freq) other_ax = None if hasattr(ax, "left_ax"): @@ -121,7 +121,7 @@ def _upsample_others(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None other_ax = ax.right_ax if other_ax is not None: - rlines, rlabels = _replot_ax(other_ax, freq, kwargs) + rlines, rlabels = _replot_ax(other_ax, freq) lines.extend(rlines) labels.extend(rlabels) @@ -132,7 +132,7 @@ def _upsample_others(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None ax.legend(lines, labels, loc="best", title=title) -def _replot_ax(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]): +def _replot_ax(ax: Axes, freq: BaseOffset): data = getattr(ax, "_plot_data", None) # clear current axes and data @@ -140,7 +140,7 @@ def _replot_ax(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]): ax._plot_data = [] # type: ignore[attr-defined] ax.clear() - decorate_axes(ax, freq, kwargs) + decorate_axes(ax, freq) lines = [] labels = [] @@ -164,7 +164,7 @@ def _replot_ax(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]): return lines, labels -def decorate_axes(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None: +def decorate_axes(ax: Axes, freq: BaseOffset) -> None: """Initialize axes for time-series plotting""" if not hasattr(ax, "_plot_data"): # TODO #54485 @@ -175,15 +175,6 @@ def decorate_axes(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None: xaxis = ax.get_xaxis() # TODO #54485 xaxis.freq = freq # type: ignore[attr-defined] - if not hasattr(ax, "legendlabels"): - # TODO #54485 - ax.legendlabels = [kwargs.get("label", None)] # type: ignore[attr-defined] - else: - ax.legendlabels.append(kwargs.get("label", None)) - # TODO #54485 - ax.view_interval = None # type: ignore[attr-defined] - # TODO #54485 - ax.date_axis_info = None # type: ignore[attr-defined] def _get_ax_freq(ax: Axes):
- [ ] 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. xref #54485 @tacaswell can you confirm that matplotlib doesn't use any of these internally? Removing these doesn't break any of our tests locally, but a lot of our plotting tests are basically smoke-tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/55944
2023-11-13T22:05:30Z
2023-11-21T20:55:42Z
2023-11-21T20:55:42Z
2023-11-21T21:20:21Z
TST: Skip pyarrow csv tests that raise ParseErrors
diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py index a2ffec45cfc7f..0c28db245de31 100644 --- a/pandas/tests/io/parser/common/test_common_basic.py +++ b/pandas/tests/io/parser/common/test_common_basic.py @@ -34,6 +34,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") def test_override_set_noconvert_columns(): @@ -137,7 +138,7 @@ def test_1000_sep(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Found non-unique column index def test_unnamed_columns(all_parsers): data = """A,B,C,, 1,2,3,4,5 @@ -278,7 +279,7 @@ def test_nrows_skipfooter_errors(all_parsers): parser.read_csv(StringIO(data), skipfooter=1, nrows=5) -@xfail_pyarrow +@skip_pyarrow def test_missing_trailing_delimiters(all_parsers): parser = all_parsers data = """A,B,C,D @@ -366,7 +367,7 @@ def test_skip_initial_space(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_trailing_delimiters(all_parsers): # see gh-2442 data = """A,B,C @@ -398,7 +399,7 @@ def test_escapechar(all_parsers): tm.assert_index_equal(result.columns, Index(["SEARCH_TERM", "ACTUAL_URL"])) -@xfail_pyarrow +@xfail_pyarrow # ValueError: the 'pyarrow' engine does not support regex separators def test_ignore_leading_whitespace(all_parsers): # see gh-3374, gh-6607 parser = all_parsers @@ -409,7 +410,7 @@ def test_ignore_leading_whitespace(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow @pytest.mark.parametrize("usecols", [None, [0, 1], ["a", "b"]]) def test_uneven_lines_with_usecols(all_parsers, usecols): # see gh-12203 @@ -432,7 +433,7 @@ def test_uneven_lines_with_usecols(all_parsers, usecols): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow @pytest.mark.parametrize( "data,kwargs,expected", [ @@ -593,7 +594,7 @@ def test_empty_lines(all_parsers, sep, skip_blank_lines, exp_data, request): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_whitespace_lines(all_parsers): parser = all_parsers data = """ @@ -609,7 +610,7 @@ def test_whitespace_lines(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: the 'pyarrow' engine does not support regex separators @pytest.mark.parametrize( "data,expected", [ @@ -707,7 +708,7 @@ def test_read_csv_and_table_sys_setprofile(all_parsers, read_func): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_first_row_bom(all_parsers): # see gh-26545 parser = all_parsers @@ -718,7 +719,7 @@ def test_first_row_bom(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_first_row_bom_unquoted(all_parsers): # see gh-36343 parser = all_parsers @@ -751,7 +752,7 @@ def test_blank_lines_between_header_and_data_rows(all_parsers, nrows): tm.assert_frame_equal(df, ref[:nrows]) -@xfail_pyarrow +@skip_pyarrow def test_no_header_two_extra_columns(all_parsers): # GH 26218 column_names = ["one", "two", "three"] @@ -852,7 +853,7 @@ def test_read_table_delim_whitespace_non_default_sep(all_parsers, delimiter): parser.read_table(f, delim_whitespace=True, delimiter=delimiter) -@xfail_pyarrow +@skip_pyarrow def test_dict_keys_as_names(all_parsers): # GH: 36928 data = "1,2" @@ -865,7 +866,7 @@ def test_dict_keys_as_names(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 0 def test_encoding_surrogatepass(all_parsers): # GH39017 parser = all_parsers @@ -893,7 +894,7 @@ def test_malformed_second_line(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_short_single_line(all_parsers): # GH 47566 parser = all_parsers @@ -904,7 +905,7 @@ def test_short_single_line(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Length mismatch: Expected axis has 2 elements def test_short_multi_line(all_parsers): # GH 47566 parser = all_parsers diff --git a/pandas/tests/io/parser/common/test_data_list.py b/pandas/tests/io/parser/common/test_data_list.py index 3b0ff9e08d349..5c798316e2cea 100644 --- a/pandas/tests/io/parser/common/test_data_list.py +++ b/pandas/tests/io/parser/common/test_data_list.py @@ -16,10 +16,10 @@ "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" ) -xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") -@xfail_pyarrow +@skip_pyarrow def test_read_data_list(all_parsers): parser = all_parsers kwargs = {"index_col": 0} 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 7fd86e956b543..a6e68cb984ef4 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -27,6 +27,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @pytest.mark.network @@ -431,7 +432,7 @@ def test_context_manageri_user_provided(all_parsers, datapath): assert not reader.handles.handle.closed -@xfail_pyarrow # ParserError: Empty CSV file +@skip_pyarrow # ParserError: Empty CSV file def test_file_descriptor_leak(all_parsers, using_copy_on_write): # GH 31488 parser = all_parsers diff --git a/pandas/tests/io/parser/common/test_float.py b/pandas/tests/io/parser/common/test_float.py index 63ad3bcb249ea..4b23774ee2d5b 100644 --- a/pandas/tests/io/parser/common/test_float.py +++ b/pandas/tests/io/parser/common/test_float.py @@ -16,9 +16,10 @@ "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") -@xfail_pyarrow # ParserError: CSV parse error: Empty CSV file or block +@skip_pyarrow # ParserError: CSV parse error: Empty CSV file or block def test_float_parser(all_parsers): # see gh-9565 parser = all_parsers @@ -50,7 +51,7 @@ def test_very_negative_exponent(all_parsers_all_precisions, neg_exp): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: Attributes of DataFrame.iloc[:, 0] are different @pytest.mark.parametrize("exp", [999999999999999999, -999999999999999999]) def test_too_many_exponent_digits(all_parsers_all_precisions, exp, request): # GH#38753 diff --git a/pandas/tests/io/parser/common/test_index.py b/pandas/tests/io/parser/common/test_index.py index 7df14043f478c..038c684c90c9e 100644 --- a/pandas/tests/io/parser/common/test_index.py +++ b/pandas/tests/io/parser/common/test_index.py @@ -20,6 +20,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @pytest.mark.parametrize( @@ -108,7 +109,7 @@ def test_multi_index_no_level_names(all_parsers, index_col): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_multi_index_no_level_names_implicit(all_parsers): parser = all_parsers data = """A,B,C,D @@ -142,7 +143,7 @@ def test_multi_index_no_level_names_implicit(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # TypeError: an integer is required @pytest.mark.parametrize( "data,expected,header", [ @@ -164,7 +165,7 @@ def test_multi_index_blank_df(all_parsers, data, expected, header, round_trip): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame.columns are different def test_no_unnamed_index(all_parsers): parser = all_parsers data = """ id c0 c1 c2 @@ -207,7 +208,7 @@ def test_read_duplicate_index_explicit(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_read_duplicate_index_implicit(all_parsers): data = """A,B,C,D foo,2,3,4,5 @@ -235,7 +236,7 @@ def test_read_duplicate_index_implicit(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_read_csv_no_index_name(all_parsers, csv_dir_path): parser = all_parsers csv2 = os.path.join(csv_dir_path, "test2.csv") @@ -263,7 +264,7 @@ def test_read_csv_no_index_name(all_parsers, csv_dir_path): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_empty_with_index(all_parsers): # see gh-10184 data = "x,y" @@ -275,7 +276,7 @@ def test_empty_with_index(all_parsers): # CSV parse error: Empty CSV file or block: cannot infer number of columns -@xfail_pyarrow +@skip_pyarrow def test_empty_with_multi_index(all_parsers): # see gh-10467 data = "x,y,z" @@ -289,7 +290,7 @@ def test_empty_with_multi_index(all_parsers): # CSV parse error: Empty CSV file or block: cannot infer number of columns -@xfail_pyarrow +@skip_pyarrow def test_empty_with_reversed_multi_index(all_parsers): data = "x,y,z" parser = all_parsers diff --git a/pandas/tests/io/parser/common/test_inf.py b/pandas/tests/io/parser/common/test_inf.py index e1dc87ed0071e..74596b178d35d 100644 --- a/pandas/tests/io/parser/common/test_inf.py +++ b/pandas/tests/io/parser/common/test_inf.py @@ -20,7 +20,7 @@ xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame.index are different @pytest.mark.parametrize("na_filter", [True, False]) def test_inf_parsing(all_parsers, na_filter): parser = all_parsers @@ -44,7 +44,7 @@ def test_inf_parsing(all_parsers, na_filter): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame.index are different @pytest.mark.parametrize("na_filter", [True, False]) def test_infinity_parsing(all_parsers, na_filter): parser = all_parsers diff --git a/pandas/tests/io/parser/common/test_ints.py b/pandas/tests/io/parser/common/test_ints.py index 41bfbb55d818f..a3167346c64ef 100644 --- a/pandas/tests/io/parser/common/test_ints.py +++ b/pandas/tests/io/parser/common/test_ints.py @@ -18,6 +18,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") def test_int_conversion(all_parsers): @@ -179,7 +180,7 @@ def test_int64_overflow(all_parsers, conv, request): parser.read_csv(StringIO(data), converters={"ID": conv}) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block @pytest.mark.parametrize( "val", [np.iinfo(np.uint64).max, np.iinfo(np.int64).max, np.iinfo(np.int64).min] ) @@ -193,7 +194,7 @@ def test_int64_uint64_range(all_parsers, val): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block @pytest.mark.parametrize( "val", [np.iinfo(np.uint64).max + 1, np.iinfo(np.int64).min - 1] ) diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py index 7e841ed8b4ebd..f3794c056a256 100644 --- a/pandas/tests/io/parser/common/test_read_errors.py +++ b/pandas/tests/io/parser/common/test_read_errors.py @@ -22,6 +22,7 @@ import pandas._testing as tm xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") def test_empty_decimal_marker(all_parsers): @@ -139,7 +140,7 @@ def test_catch_too_many_names(all_parsers): parser.read_csv(StringIO(data), header=0, names=["a", "b", "c", "d"]) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block @pytest.mark.parametrize("nrows", [0, 1, 2, 3, 4, 5]) def test_raise_on_no_columns(all_parsers, nrows): parser = all_parsers diff --git a/pandas/tests/io/parser/conftest.py b/pandas/tests/io/parser/conftest.py index 471f525e229e5..eb7835bb27372 100644 --- a/pandas/tests/io/parser/conftest.py +++ b/pandas/tests/io/parser/conftest.py @@ -282,6 +282,8 @@ def numeric_decimal(request): def pyarrow_xfail(request): """ Fixture that xfails a test if the engine is pyarrow. + + Use if failure is do to unsupported keywords or inconsistent results. """ if "all_parsers" in request.fixturenames: parser = request.getfixturevalue("all_parsers") @@ -293,3 +295,21 @@ def pyarrow_xfail(request): if parser.engine == "pyarrow": mark = pytest.mark.xfail(reason="pyarrow doesn't support this.") request.applymarker(mark) + + +@pytest.fixture +def pyarrow_skip(request): + """ + Fixture that skips a test if the engine is pyarrow. + + Use if failure is do a parsing failure from pyarrow.csv.read_csv + """ + if "all_parsers" in request.fixturenames: + parser = request.getfixturevalue("all_parsers") + elif "all_parsers_all_precisions" in request.fixturenames: + # Return value is tuple of (engine, precision) + parser = request.getfixturevalue("all_parsers_all_precisions")[0] + else: + return + if parser.engine == "pyarrow": + pytest.skip(reason="https://github.com/apache/arrow/issues/38676") diff --git a/pandas/tests/io/parser/dtypes/test_categorical.py b/pandas/tests/io/parser/dtypes/test_categorical.py index b1b35447b60c2..f4aff14a5ce32 100644 --- a/pandas/tests/io/parser/dtypes/test_categorical.py +++ b/pandas/tests/io/parser/dtypes/test_categorical.py @@ -27,7 +27,7 @@ xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") -@xfail_pyarrow +@xfail_pyarrow # AssertionError: Attributes of DataFrame.iloc[:, 0] are different @pytest.mark.parametrize( "dtype", [ @@ -76,7 +76,7 @@ def test_categorical_dtype_single(all_parsers, dtype, request): tm.assert_frame_equal(actual, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: Attributes of DataFrame.iloc[:, 0] are different def test_categorical_dtype_unsorted(all_parsers): # see gh-10153 parser = all_parsers @@ -95,7 +95,7 @@ def test_categorical_dtype_unsorted(all_parsers): tm.assert_frame_equal(actual, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: Attributes of DataFrame.iloc[:, 0] are different def test_categorical_dtype_missing(all_parsers): # see gh-10153 parser = all_parsers @@ -114,7 +114,7 @@ def test_categorical_dtype_missing(all_parsers): tm.assert_frame_equal(actual, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: Attributes of DataFrame.iloc[:, 0] are different @pytest.mark.slow def test_categorical_dtype_high_cardinality_numeric(all_parsers, monkeypatch): # see gh-18186 diff --git a/pandas/tests/io/parser/dtypes/test_empty.py b/pandas/tests/io/parser/dtypes/test_empty.py index 8759c52485533..f34385b190c5f 100644 --- a/pandas/tests/io/parser/dtypes/test_empty.py +++ b/pandas/tests/io/parser/dtypes/test_empty.py @@ -17,10 +17,10 @@ ) import pandas._testing as tm -xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_dtype_all_columns_empty(all_parsers): # see gh-12048 parser = all_parsers @@ -30,7 +30,7 @@ def test_dtype_all_columns_empty(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_pass_dtype(all_parsers): parser = all_parsers @@ -43,7 +43,7 @@ def test_empty_pass_dtype(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_with_index_pass_dtype(all_parsers): parser = all_parsers @@ -58,7 +58,7 @@ def test_empty_with_index_pass_dtype(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_with_multi_index_pass_dtype(all_parsers): parser = all_parsers @@ -75,7 +75,7 @@ def test_empty_with_multi_index_pass_dtype(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers): parser = all_parsers @@ -88,7 +88,7 @@ def test_empty_with_mangled_column_pass_dtype_by_names(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers): parser = all_parsers @@ -101,7 +101,7 @@ def test_empty_with_mangled_column_pass_dtype_by_indexes(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_with_dup_column_pass_dtype_by_indexes(all_parsers): # see gh-9424 parser = all_parsers @@ -171,7 +171,7 @@ def test_empty_with_dup_column_pass_dtype_by_indexes_raises(all_parsers): ), ], ) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_dtype(all_parsers, dtype, expected): # see gh-14712 parser = all_parsers diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py index 9e1200c142d6b..3580c040688d8 100644 --- a/pandas/tests/io/parser/test_encoding.py +++ b/pandas/tests/io/parser/test_encoding.py @@ -24,6 +24,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") def test_bytes_io_input(all_parsers): @@ -37,7 +38,7 @@ def test_bytes_io_input(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_read_csv_unicode(all_parsers): parser = all_parsers data = BytesIO("\u0141aski, Jan;1".encode()) @@ -47,7 +48,7 @@ def test_read_csv_unicode(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_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): @@ -237,7 +238,7 @@ def test_parse_encoded_special_characters(encoding): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: The 'memory_map' option is not supported @pytest.mark.parametrize("encoding", ["utf-8", None, "utf-16", "cp1255", "latin-1"]) def test_encoding_memory_map(all_parsers, encoding): # GH40986 @@ -255,7 +256,7 @@ def test_encoding_memory_map(all_parsers, encoding): tm.assert_frame_equal(df, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: The 'memory_map' option is not supported def test_chunk_splits_multibyte_char(all_parsers): """ Chunk splits a multibyte character with memory_map=True @@ -275,7 +276,7 @@ def test_chunk_splits_multibyte_char(all_parsers): tm.assert_frame_equal(dfr, df) -@xfail_pyarrow +@xfail_pyarrow # ValueError: The 'memory_map' option is not supported def test_readcsv_memmap_utf8(all_parsers): """ GH 43787 diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py index 2edb389a0c830..f55f8497f318c 100644 --- a/pandas/tests/io/parser/test_header.py +++ b/pandas/tests/io/parser/test_header.py @@ -23,6 +23,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @xfail_pyarrow # TypeError: an integer is required @@ -79,7 +80,7 @@ def test_bool_header_arg(all_parsers, header): parser.read_csv(StringIO(data), header=header) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame are different def test_header_with_index_col(all_parsers): parser = all_parsers data = """foo,1,2,3 @@ -183,7 +184,7 @@ def test_header_multi_index_invalid(all_parsers, kwargs, msg): _TestTuple = namedtuple("_TestTuple", ["first", "second"]) -@xfail_pyarrow +@xfail_pyarrow # TypeError: an integer is required @pytest.mark.parametrize( "kwargs", [ @@ -231,7 +232,7 @@ def test_header_multi_index_common_format1(all_parsers, kwargs): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # TypeError: an integer is required @pytest.mark.parametrize( "kwargs", [ @@ -278,7 +279,7 @@ def test_header_multi_index_common_format2(all_parsers, kwargs): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # TypeError: an integer is required @pytest.mark.parametrize( "kwargs", [ @@ -419,7 +420,7 @@ def test_header_names_backward_compat(all_parsers, data, header, request): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block: cannot infer +@skip_pyarrow # CSV parse error: Empty CSV file or block: cannot infer @pytest.mark.parametrize("kwargs", [{}, {"index_col": False}]) def test_read_only_header_no_rows(all_parsers, kwargs): # See gh-7773 @@ -561,7 +562,7 @@ def test_multi_index_unnamed(all_parsers, index_col, columns): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Expected 2 columns, got 3 +@skip_pyarrow # CSV parse error: Expected 2 columns, got 3 def test_names_longer_than_header_but_equal_with_data_rows(all_parsers): # GH#38453 parser = all_parsers @@ -622,7 +623,7 @@ def test_read_csv_multi_header_length_check(all_parsers): parser.read_csv(StringIO(case), header=[0, 2]) -@xfail_pyarrow # CSV parse error: Expected 3 columns, got 2 +@skip_pyarrow # CSV parse error: Expected 3 columns, got 2 def test_header_none_and_implicit_index(all_parsers): # GH#22144 parser = all_parsers diff --git a/pandas/tests/io/parser/test_index_col.py b/pandas/tests/io/parser/test_index_col.py index b938b129ac38d..ba15d061b2deb 100644 --- a/pandas/tests/io/parser/test_index_col.py +++ b/pandas/tests/io/parser/test_index_col.py @@ -20,6 +20,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @pytest.mark.parametrize("with_header", [True, False]) @@ -76,7 +77,7 @@ def test_index_col_is_true(all_parsers): parser.read_csv(StringIO(data), index_col=True) -@xfail_pyarrow # CSV parse error: Expected 3 columns, got 4 +@skip_pyarrow # CSV parse error: Expected 3 columns, got 4 def test_infer_index_col(all_parsers): data = """A,B,C foo,1,2,3 @@ -94,7 +95,7 @@ def test_infer_index_col(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block @pytest.mark.parametrize( "index_col,kwargs", [ @@ -143,7 +144,7 @@ def test_index_col_empty_data(all_parsers, index_col, kwargs): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_empty_with_index_col_false(all_parsers): # see gh-10413 data = "x,y" @@ -317,7 +318,7 @@ def test_multiindex_columns_index_col_with_data(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Empty CSV file or block +@skip_pyarrow # CSV parse error: Empty CSV file or block def test_infer_types_boolean_sum(all_parsers): # GH#44079 parser = all_parsers diff --git a/pandas/tests/io/parser/test_mangle_dupes.py b/pandas/tests/io/parser/test_mangle_dupes.py index 7d148ae6c5a27..1d245f81f027c 100644 --- a/pandas/tests/io/parser/test_mangle_dupes.py +++ b/pandas/tests/io/parser/test_mangle_dupes.py @@ -18,7 +18,7 @@ ) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Found non-unique column index def test_basic(all_parsers): parser = all_parsers @@ -29,7 +29,7 @@ def test_basic(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Found non-unique column index def test_basic_names(all_parsers): # See gh-7160 parser = all_parsers @@ -50,7 +50,7 @@ def test_basic_names_raise(all_parsers): parser.read_csv(StringIO(data), names=["a", "b", "a"]) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Found non-unique column index @pytest.mark.parametrize( "data,expected", [ @@ -118,7 +118,7 @@ def test_thorough_mangle_names(all_parsers, data, names, expected): parser.read_csv(StringIO(data), names=names) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame.columns are different def test_mangled_unnamed_placeholders(all_parsers): # xref gh-13017 orig_key = "0" @@ -141,7 +141,7 @@ def test_mangled_unnamed_placeholders(all_parsers): tm.assert_frame_equal(df, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Found non-unique column index def test_mangle_dupe_cols_already_exists(all_parsers): # GH#14704 parser = all_parsers @@ -155,7 +155,7 @@ def test_mangle_dupe_cols_already_exists(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # ValueError: Found non-unique column index def test_mangle_dupe_cols_already_exists_unnamed_col(all_parsers): # GH#14704 parser = all_parsers diff --git a/pandas/tests/io/parser/test_na_values.py b/pandas/tests/io/parser/test_na_values.py index 59dae1eaa7e6c..437a5fb5e9f09 100644 --- a/pandas/tests/io/parser/test_na_values.py +++ b/pandas/tests/io/parser/test_na_values.py @@ -21,6 +21,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") def test_string_nas(all_parsers): @@ -398,7 +399,7 @@ def test_na_values_na_filter_override(all_parsers, na_filter, row_data): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Expected 8 columns, got 5: +@skip_pyarrow # CSV parse error: Expected 8 columns, got 5: def test_na_trailing_columns(all_parsers): parser = all_parsers data = """Date,Currency,Symbol,Type,Units,UnitPrice,Cost,Tax @@ -630,7 +631,7 @@ def test_nan_multi_index(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # Failed: DID NOT RAISE <class 'ValueError'> def test_bool_and_nan_to_bool(all_parsers): # GH#42808 parser = all_parsers diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 47e654fc606af..70d9171fa3c22 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -41,6 +41,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @xfail_pyarrow @@ -786,7 +787,7 @@ def test_nat_parse(all_parsers): tm.assert_frame_equal(result, df) -@xfail_pyarrow +@skip_pyarrow def test_csv_custom_parser(all_parsers): data = """A,B,C 20090101,a,1,2 @@ -806,7 +807,7 @@ def test_csv_custom_parser(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@skip_pyarrow def test_parse_dates_implicit_first_col(all_parsers): data = """A,B,C 20090101,a,1,2 @@ -2101,7 +2102,7 @@ def test_dayfirst_warnings_no_leading_zero(date_string, dayfirst): tm.assert_index_equal(expected, res) -@xfail_pyarrow # CSV parse error: Expected 3 columns, got 4 +@skip_pyarrow # CSV parse error: Expected 3 columns, got 4 def test_infer_first_column_as_index(all_parsers): # GH#11019 parser = all_parsers diff --git a/pandas/tests/io/parser/test_quoting.py b/pandas/tests/io/parser/test_quoting.py index a677d9caa4b19..0a1ba0252f106 100644 --- a/pandas/tests/io/parser/test_quoting.py +++ b/pandas/tests/io/parser/test_quoting.py @@ -18,6 +18,7 @@ "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @pytest.mark.parametrize( @@ -31,7 +32,7 @@ ({"quotechar": 2}, '"quotechar" must be string( or None)?, not int'), ], ) -@xfail_pyarrow # ParserError: CSV parse error: Empty CSV file or block +@skip_pyarrow # ParserError: CSV parse error: Empty CSV file or block def test_bad_quote_char(all_parsers, kwargs, msg): data = "1,2,3" parser = all_parsers diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py index 9146af3f969e6..47c3739c979a3 100644 --- a/pandas/tests/io/parser/test_skiprows.py +++ b/pandas/tests/io/parser/test_skiprows.py @@ -67,7 +67,7 @@ def test_deep_skip_rows(all_parsers): tm.assert_frame_equal(result, condensed_result) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame are different def test_skip_rows_blank(all_parsers): # see gh-9832 parser = all_parsers @@ -225,7 +225,7 @@ def test_skiprows_lineterminator(all_parsers, lineterminator, request): tm.assert_frame_equal(result, expected) -@xfail_pyarrow +@xfail_pyarrow # AssertionError: DataFrame are different def test_skiprows_infield_quote(all_parsers): # see gh-14459 parser = all_parsers diff --git a/pandas/tests/io/parser/usecols/test_parse_dates.py b/pandas/tests/io/parser/usecols/test_parse_dates.py index bcb1c6af80df6..042c3814ef72a 100644 --- a/pandas/tests/io/parser/usecols/test_parse_dates.py +++ b/pandas/tests/io/parser/usecols/test_parse_dates.py @@ -17,6 +17,7 @@ "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") @xfail_pyarrow # TypeError: expected bytes, int found @@ -38,7 +39,7 @@ def test_usecols_with_parse_dates(all_parsers, usecols): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # pyarrow.lib.ArrowKeyError: Column 'fdate' in include_columns +@skip_pyarrow # pyarrow.lib.ArrowKeyError: Column 'fdate' in include_columns def test_usecols_with_parse_dates2(all_parsers): # see gh-13604 parser = all_parsers diff --git a/pandas/tests/io/parser/usecols/test_usecols_basic.py b/pandas/tests/io/parser/usecols/test_usecols_basic.py index 7a620768040a7..055be81d2996d 100644 --- a/pandas/tests/io/parser/usecols/test_usecols_basic.py +++ b/pandas/tests/io/parser/usecols/test_usecols_basic.py @@ -30,6 +30,7 @@ ) xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") +skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip") pytestmark = pytest.mark.filterwarnings( "ignore:Passing a BlockManager to DataFrame is deprecated:DeprecationWarning" @@ -148,7 +149,7 @@ def test_usecols_single_string(all_parsers): parser.read_csv(StringIO(data), usecols="foo") -@xfail_pyarrow # CSV parse error in one case, AttributeError in another +@skip_pyarrow # CSV parse error in one case, AttributeError in another @pytest.mark.parametrize( "data", ["a,b,c,d\n1,2,3,4\n5,6,7,8", "a,b,c,d\n1,2,3,4,\n5,6,7,8,"] ) @@ -191,7 +192,7 @@ def test_usecols_index_col_conflict2(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Expected 3 columns, got 4 +@skip_pyarrow # CSV parse error: Expected 3 columns, got 4 def test_usecols_implicit_index_col(all_parsers): # see gh-2654 parser = all_parsers @@ -337,7 +338,7 @@ def test_callable_usecols(all_parsers, usecols, expected): # ArrowKeyError: Column 'fa' in include_columns does not exist in CSV file -@xfail_pyarrow +@skip_pyarrow @pytest.mark.parametrize("usecols", [["a", "c"], lambda x: x in ["a", "c"]]) def test_incomplete_first_row(all_parsers, usecols): # see gh-6710 @@ -350,7 +351,7 @@ def test_incomplete_first_row(all_parsers, usecols): tm.assert_frame_equal(result, expected) -@xfail_pyarrow # CSV parse error: Expected 3 columns, got 4 +@skip_pyarrow # CSV parse error: Expected 3 columns, got 4 @pytest.mark.parametrize( "data,usecols,kwargs,expected", [
xref https://github.com/apache/arrow/issues/38676 Just to be safe, skipping in general if the failure occurs from the `pyarrow.csv.read_csv` call specifically
https://api.github.com/repos/pandas-dev/pandas/pulls/55943
2023-11-13T21:24:45Z
2023-11-14T15:42:30Z
2023-11-14T15:42:30Z
2023-11-14T15:42:36Z
Backport PR #55920 on branch 2.1.x (Fix off-by-one in aggregations)
diff --git a/pandas/core/indexers/objects.py b/pandas/core/indexers/objects.py index 694a420ad2494..b516227cf8b06 100644 --- a/pandas/core/indexers/objects.py +++ b/pandas/core/indexers/objects.py @@ -102,7 +102,7 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - if center: + if center or self.window_size == 0: offset = (self.window_size - 1) // 2 else: offset = 0
Backport PR #55920: Fix off-by-one in aggregations
https://api.github.com/repos/pandas-dev/pandas/pulls/55942
2023-11-13T18:53:21Z
2023-11-13T21:02:00Z
2023-11-13T21:02:00Z
2023-11-13T21:02:00Z
Cython 3.0 faster maybe_convert_objects
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 50ea5f6d3f699..e8a69891c6093 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -2520,6 +2520,7 @@ def maybe_convert_objects(ndarray[object] objects, ndarray[int64_t] ints ndarray[uint64_t] uints ndarray[uint8_t] bools + ndarray[uint8_t] mask Seen seen = Seen() object val _TSObject tsobj
Since mask is a PyObject Cython 3.0 tries to do setting using the mapping protocol, which causes some slowdowns in tight loops. This probably should have been cdef'ed to begin with anyway though
https://api.github.com/repos/pandas-dev/pandas/pulls/55941
2023-11-13T15:33:58Z
2023-11-13T19:38:04Z
2023-11-13T19:38:04Z
2023-11-13T19:39:47Z
ENH: Improve error message when constructing period with invalid freq
diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index c5d4010d4ba47..7f3a72178a359 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -4673,7 +4673,9 @@ def _get_offset(name: str) -> BaseOffset: offset = klass._from_name(*split[1:]) except (ValueError, TypeError, KeyError) as err: # bad prefix or suffix - raise ValueError(INVALID_FREQ_ERR_MSG.format(name)) from err + raise ValueError(INVALID_FREQ_ERR_MSG.format( + f"{name}, failed to parse with error message: {repr(err)}") + ) # cache _offset_map[name] = offset @@ -4757,11 +4759,17 @@ cpdef to_offset(freq, bint is_period=False): ) name = c_OFFSET_DEPR_FREQSTR[name] if is_period is True and name in c_REVERSE_OFFSET_DEPR_FREQSTR: - raise ValueError( - f"for Period, please use " - f"\'{c_REVERSE_OFFSET_DEPR_FREQSTR.get(name)}\' " - f"instead of \'{name}\'" - ) + if name.startswith("Y"): + raise ValueError( + f"for Period, please use \'Y{name[2:]}\' " + f"instead of \'{name}\'" + ) + else: + raise ValueError( + f"for Period, please use " + f"\'{c_REVERSE_OFFSET_DEPR_FREQSTR.get(name)}\' " + f"instead of \'{name}\'" + ) elif is_period is True and name in c_OFFSET_DEPR_FREQSTR: if name.startswith("A"): warnings.warn( @@ -4813,7 +4821,9 @@ cpdef to_offset(freq, bint is_period=False): else: delta = delta + offset except (ValueError, TypeError) as err: - raise ValueError(INVALID_FREQ_ERR_MSG.format(freq)) from err + raise ValueError(INVALID_FREQ_ERR_MSG.format( + f"{freq}, failed to parse with error message: {repr(err)}") + ) else: delta = None diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 4f946edf148fd..6965aaf19f8fb 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -273,7 +273,7 @@ def test_map(self): tm.assert_index_equal(result, exp) def test_period_index_frequency_ME_error_message(self): - msg = "Invalid frequency: 2ME" + msg = "for Period, please use 'M' instead of 'ME'" with pytest.raises(ValueError, match=msg): PeriodIndex(["2020-01-01", "2020-01-02"], freq="2ME") @@ -302,7 +302,8 @@ def test_a_deprecated_from_time_series(self, freq_depr): @pytest.mark.parametrize("freq_depr", ["2ME", "2QE", "2YE"]) def test_period_index_frequency_error_message(self, freq_depr): # GH#9586 - msg = f"Invalid frequency: {freq_depr}" + msg = f"for Period, please use '{freq_depr[1:-1]}' " + f"instead of '{freq_depr[1:]}'" with pytest.raises(ValueError, match=msg): period_range("2020-01", "2020-05", freq=freq_depr) diff --git a/pandas/tests/indexes/period/test_period_range.py b/pandas/tests/indexes/period/test_period_range.py index fd6db389fbbf4..0d7bedbbe70f6 100644 --- a/pandas/tests/indexes/period/test_period_range.py +++ b/pandas/tests/indexes/period/test_period_range.py @@ -157,6 +157,6 @@ def test_errors(self): period_range(start="2017Q1", periods="foo") def test_period_range_frequency_ME_error_message(self): - msg = "Invalid frequency: 2ME" + msg = "for Period, please use 'M' instead of 'ME'" with pytest.raises(ValueError, match=msg): period_range(start="Jan-2000", end="Dec-2000", freq="2ME") diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index b8b2325f03889..2453c007b7dea 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -931,10 +931,11 @@ def test_resample_t_l_deprecated(self): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("freq_depr", ["2ME", "2QE", "2QE-FEB", "2YE"]) +@pytest.mark.parametrize("freq_depr", ["2ME", "2QE", "2QE-FEB", "2YE", "2YE-MAR"]) def test_resample_frequency_ME_QE_error_message(series_and_frame, freq_depr): # GH#9586 - msg = f"Invalid frequency: {freq_depr}" + msg = f"for Period, please use '{freq_depr[1:2]}{freq_depr[3:]}' " + f"instead of '{freq_depr[1:]}'" obj = series_and_frame with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index add7867611303..f466804fe0814 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1632,6 +1632,6 @@ def test_invalid_frequency_error_message(): def test_invalid_frequency_period_error_message(): - msg = "Invalid frequency: ME" + msg = "for Period, please use 'M' instead of 'ME'" with pytest.raises(ValueError, match=msg): Period("2012-01-02", freq="ME")
xref #55792, #52064 Improved error message when constructing period with offsets frequencies deprecated for period such as "ME" or "YE-DEC". the reason: we see the error message: `Invalid frequency: "..."` instead of the message: `for Period, please use "..." instead of "..."`
https://api.github.com/repos/pandas-dev/pandas/pulls/55940
2023-11-13T15:13:29Z
2023-11-14T20:15:08Z
2023-11-14T20:15:08Z
2023-11-14T20:15:08Z
ASV: add FrameMixedDtypesOps
diff --git a/asv_bench/benchmarks/stat_ops.py b/asv_bench/benchmarks/stat_ops.py index 1652fcf8d48da..89bda81ccf08c 100644 --- a/asv_bench/benchmarks/stat_ops.py +++ b/asv_bench/benchmarks/stat_ops.py @@ -20,6 +20,39 @@ def time_op(self, op, dtype, axis): self.df_func(axis=axis) +class FrameMixedDtypesOps: + params = [ops, [0, 1, None]] + param_names = ["op", "axis"] + + def setup(self, op, axis): + if op in ("sum", "skew", "kurt", "prod", "sem", "var") or ( + (op, axis) + in ( + ("mean", 1), + ("mean", None), + ("median", 1), + ("median", None), + ("std", 1), + ) + ): + # Skipping cases where datetime aggregations are not implemented + raise NotImplementedError + + N = 1_000_000 + df = pd.DataFrame( + { + "f": np.random.normal(0.0, 1.0, N), + "i": np.random.randint(0, N, N), + "ts": pd.date_range(start="1/1/2000", periods=N, freq="h"), + } + ) + + self.df_func = getattr(df, op) + + def time_op(self, op, axis): + self.df_func(axis=axis) + + class FrameMultiIndexOps: params = [ops] param_names = ["op"]
- [ ] closes #31075 - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). Added mixed-dtype reduction asv
https://api.github.com/repos/pandas-dev/pandas/pulls/55939
2023-11-13T14:58:45Z
2023-11-14T15:39:16Z
2023-11-14T15:39:16Z
2023-11-14T15:39:24Z
ASV: DataFrame.__setitem__ performance with object dtype
diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index d8b1bf327294a..8058b347383a7 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -515,6 +515,18 @@ def time_setitem_list(self): self.df[[100, 200, 300]] = 100 +class SetitemObjectDtype: + # GH#19299 + + def setup(self): + N = 1000 + cols = 500 + self.df = DataFrame(index=range(N), columns=range(cols), dtype=object) + + def time_setitem_object_dtype(self): + self.df.loc[0, 1] = 1.0 + + class ChainIndexing: params = [None, "warn"] param_names = ["mode"]
- [ ] closes #19299 - [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 new benchmark SetitemObjectDtype
https://api.github.com/repos/pandas-dev/pandas/pulls/55938
2023-11-13T14:16:35Z
2023-11-14T01:11:12Z
2023-11-14T01:11:12Z
2023-11-14T01:11:18Z
Backport PR #55924 on branch 2.1.x (DOC: add whatsnew for 2.1.4)
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index eef65366a2762..3af7a06428f0c 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -16,6 +16,7 @@ Version 2.1 .. toctree:: :maxdepth: 2 + v2.1.4 v2.1.3 v2.1.2 v2.1.1 diff --git a/doc/source/whatsnew/v2.1.4.rst b/doc/source/whatsnew/v2.1.4.rst new file mode 100644 index 0000000000000..04bbb0f806cbd --- /dev/null +++ b/doc/source/whatsnew/v2.1.4.rst @@ -0,0 +1,41 @@ +.. _whatsnew_214: + +What's new in 2.1.4 (December ??, 2023) +--------------------------------------- + +These are the changes in pandas 2.1.4. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.other: + +Other +~~~~~ +- +- + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.contributors: + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v2.1.3..v2.1.4|HEAD
Backport PR #55924: DOC: add whatsnew for 2.1.4
https://api.github.com/repos/pandas-dev/pandas/pulls/55937
2023-11-13T13:27:51Z
2023-11-13T17:08:11Z
2023-11-13T17:08:11Z
2023-11-13T17:08:11Z
BUG: Set check_exact to true if dtype is int
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index af14856fa3b6a..f35dff57c8566 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -315,7 +315,7 @@ See :ref:`install.dependencies` and :ref:`install.optional_dependencies` for mor Other API changes ^^^^^^^^^^^^^^^^^ -- +- ``check_exact`` now only takes effect for floating-point dtypes in :func:`testing.assert_frame_equal` and :func:`testing.assert_series_equal`. In particular, integer dtypes are always checked exactly (:issue:`55882`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 0d8fb7bfce33a..5899bae742076 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -16,6 +16,7 @@ from pandas.core.dtypes.common import ( is_bool, + is_float_dtype, is_integer_dtype, is_number, is_numeric_dtype, @@ -713,7 +714,7 @@ def assert_extension_array_equal( index_values : Index | numpy.ndarray, default None Optional index (shared by both left and right), used in output. check_exact : bool, default False - Whether to compare number exactly. + Whether to compare number exactly. Only takes effect for float dtypes. rtol : float, default 1e-5 Relative tolerance. Only used when check_exact is False. atol : float, default 1e-8 @@ -782,7 +783,10 @@ def assert_extension_array_equal( left_valid = left[~left_na].to_numpy(dtype=object) right_valid = right[~right_na].to_numpy(dtype=object) - if check_exact: + if check_exact or ( + (is_numeric_dtype(left.dtype) and not is_float_dtype(left.dtype)) + or (is_numeric_dtype(right.dtype) and not is_float_dtype(right.dtype)) + ): assert_numpy_array_equal( left_valid, right_valid, obj=obj, index_values=index_values ) @@ -836,7 +840,7 @@ def assert_series_equal( check_names : bool, default True Whether to check the Series and Index names attribute. check_exact : bool, default False - Whether to compare number exactly. + Whether to compare number exactly. Only takes effect for float dtypes. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True @@ -929,8 +933,10 @@ def assert_series_equal( pass else: assert_attr_equal("dtype", left, right, obj=f"Attributes of {obj}") - - if check_exact and is_numeric_dtype(left.dtype) and is_numeric_dtype(right.dtype): + if check_exact or ( + (is_numeric_dtype(left.dtype) and not is_float_dtype(left.dtype)) + or (is_numeric_dtype(right.dtype) and not is_float_dtype(right.dtype)) + ): left_values = left._values right_values = right._values # Only check exact if dtype is numeric @@ -1093,7 +1099,7 @@ def assert_frame_equal( Specify how to compare internal data. If False, compare by columns. If True, compare by blocks. check_exact : bool, default False - Whether to compare number exactly. + Whether to compare number exactly. Only takes effect for float dtypes. check_datetimelike_compat : bool, default False Compare datetime-like which is comparable ignoring dtype. check_categorical : bool, default True diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index b9407c7197f20..a354e5767f37f 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -7,6 +7,7 @@ from pandas._typing import Dtype from pandas.core.dtypes.common import is_bool_dtype +from pandas.core.dtypes.dtypes import NumpyEADtype from pandas.core.dtypes.missing import na_value_for_dtype import pandas as pd @@ -331,7 +332,7 @@ def test_fillna_length_mismatch(self, data_missing): data_missing.fillna(data_missing.take([1])) # Subclasses can override if we expect e.g Sparse[bool], boolean, pyarrow[bool] - _combine_le_expected_dtype: Dtype = np.dtype(bool) + _combine_le_expected_dtype: Dtype = NumpyEADtype("bool") def test_combine_le(self, data_repeated): # GH 20825 @@ -341,16 +342,20 @@ def test_combine_le(self, data_repeated): s2 = pd.Series(orig_data2) result = s1.combine(s2, lambda x1, x2: x1 <= x2) expected = pd.Series( - [a <= b for (a, b) in zip(list(orig_data1), list(orig_data2))], - dtype=self._combine_le_expected_dtype, + pd.array( + [a <= b for (a, b) in zip(list(orig_data1), list(orig_data2))], + dtype=self._combine_le_expected_dtype, + ) ) tm.assert_series_equal(result, expected) val = s1.iloc[0] result = s1.combine(val, lambda x1, x2: x1 <= x2) expected = pd.Series( - [a <= val for a in list(orig_data1)], - dtype=self._combine_le_expected_dtype, + pd.array( + [a <= val for a in list(orig_data1)], + dtype=self._combine_le_expected_dtype, + ) ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py index 32b4b1dedc3cb..0deafda750904 100644 --- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py +++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py @@ -531,6 +531,9 @@ def test_dtype_backend_pyarrow(all_parsers, request): tm.assert_frame_equal(result, expected) +# pyarrow engine failing: +# https://github.com/pandas-dev/pandas/issues/56136 +@pytest.mark.usefixtures("pyarrow_xfail") def test_ea_int_avoid_overflow(all_parsers): # GH#32134 parser = all_parsers diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 65726eb8fcbb8..b8969072b91dc 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -572,7 +572,10 @@ def test_constructor_maskedarray(self): data[1] = 1 result = Series(data, index=index) expected = Series([0, 1, 2], index=index, dtype=int) - tm.assert_series_equal(result, expected) + with pytest.raises(AssertionError, match="Series classes are different"): + # TODO should this be raising at all? + # https://github.com/pandas-dev/pandas/issues/56131 + tm.assert_series_equal(result, expected) data = ma.masked_all((3,), dtype=bool) result = Series(data) @@ -589,7 +592,10 @@ def test_constructor_maskedarray(self): data[1] = True result = Series(data, index=index) expected = Series([True, True, False], index=index, dtype=bool) - tm.assert_series_equal(result, expected) + with pytest.raises(AssertionError, match="Series classes are different"): + # TODO should this be raising at all? + # https://github.com/pandas-dev/pandas/issues/56131 + tm.assert_series_equal(result, expected) data = ma.masked_all((3,), dtype="M8[ns]") result = Series(data) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 503032293dc81..ba8edda660860 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -2116,7 +2116,13 @@ def test_float_to_datetime_raise_near_bounds(self): expected = (should_succeed * oneday_in_ns).astype(np.int64) for error_mode in ["raise", "coerce", "ignore"]: result1 = to_datetime(should_succeed, unit="D", errors=error_mode) - tm.assert_almost_equal(result1.astype(np.int64), expected, rtol=1e-10) + # Cast to `np.float64` so that `rtol` and inexact checking kick in + # (`check_exact` doesn't take place for integer dtypes) + tm.assert_almost_equal( + result1.astype(np.int64).astype(np.float64), + expected.astype(np.float64), + rtol=1e-10, + ) # just out of bounds should_fail1 = Series([0, tsmax_in_days + 0.005], dtype=float) should_fail2 = Series([0, -tsmax_in_days - 0.005], dtype=float) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index 2d3b47cd2e994..f5a8324e1896d 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -203,7 +203,10 @@ def test_assert_frame_equal_extension_dtype_mismatch(): "\\[right\\]: int[32|64]" ) - tm.assert_frame_equal(left, right, check_dtype=False) + # TODO: this shouldn't raise (or should raise a better error message) + # https://github.com/pandas-dev/pandas/issues/56131 + with pytest.raises(AssertionError, match="classes are different"): + tm.assert_frame_equal(left, right, check_dtype=False) with pytest.raises(AssertionError, match=msg): tm.assert_frame_equal(left, right, check_dtype=True) @@ -228,11 +231,18 @@ def test_assert_frame_equal_interval_dtype_mismatch(): tm.assert_frame_equal(left, right, check_dtype=True) -@pytest.mark.parametrize("right_dtype", ["Int32", "int64"]) -def test_assert_frame_equal_ignore_extension_dtype_mismatch(right_dtype): +def test_assert_frame_equal_ignore_extension_dtype_mismatch(): + # https://github.com/pandas-dev/pandas/issues/35715 + left = DataFrame({"a": [1, 2, 3]}, dtype="Int64") + right = DataFrame({"a": [1, 2, 3]}, dtype="Int32") + tm.assert_frame_equal(left, right, check_dtype=False) + + +@pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/56131") +def test_assert_frame_equal_ignore_extension_dtype_mismatch_cross_class(): # https://github.com/pandas-dev/pandas/issues/35715 left = DataFrame({"a": [1, 2, 3]}, dtype="Int64") - right = DataFrame({"a": [1, 2, 3]}, dtype=right_dtype) + right = DataFrame({"a": [1, 2, 3]}, dtype="int64") tm.assert_frame_equal(left, right, check_dtype=False) diff --git a/pandas/tests/util/test_assert_series_equal.py b/pandas/tests/util/test_assert_series_equal.py index 12b5987cdb3de..33cb32e58a27f 100644 --- a/pandas/tests/util/test_assert_series_equal.py +++ b/pandas/tests/util/test_assert_series_equal.py @@ -276,7 +276,10 @@ def test_assert_series_equal_extension_dtype_mismatch(): \\[left\\]: Int64 \\[right\\]: int[32|64]""" - tm.assert_series_equal(left, right, check_dtype=False) + # TODO: this shouldn't raise (or should raise a better error message) + # https://github.com/pandas-dev/pandas/issues/56131 + with pytest.raises(AssertionError, match="Series classes are different"): + tm.assert_series_equal(left, right, check_dtype=False) with pytest.raises(AssertionError, match=msg): tm.assert_series_equal(left, right, check_dtype=True) @@ -348,11 +351,18 @@ def test_series_equal_exact_for_nonnumeric(): tm.assert_series_equal(s3, s1, check_exact=True) -@pytest.mark.parametrize("right_dtype", ["Int32", "int64"]) -def test_assert_series_equal_ignore_extension_dtype_mismatch(right_dtype): +def test_assert_series_equal_ignore_extension_dtype_mismatch(): # https://github.com/pandas-dev/pandas/issues/35715 left = Series([1, 2, 3], dtype="Int64") - right = Series([1, 2, 3], dtype=right_dtype) + right = Series([1, 2, 3], dtype="Int32") + tm.assert_series_equal(left, right, check_dtype=False) + + +@pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/56131") +def test_assert_series_equal_ignore_extension_dtype_mismatch_cross_class(): + # https://github.com/pandas-dev/pandas/issues/35715 + left = Series([1, 2, 3], dtype="Int64") + right = Series([1, 2, 3], dtype="int64") tm.assert_series_equal(left, right, check_dtype=False) @@ -423,3 +433,12 @@ def test_check_dtype_false_different_reso(dtype): with pytest.raises(AssertionError, match="Series are different"): tm.assert_series_equal(ser_s, ser_ms, check_dtype=False) + + +@pytest.mark.parametrize("dtype", ["Int64", "int64"]) +def test_large_unequal_ints(dtype): + # https://github.com/pandas-dev/pandas/issues/55882 + left = Series([1577840521123000], dtype=dtype) + right = Series([1577840521123543], dtype=dtype) + with pytest.raises(AssertionError, match="Series are different"): + tm.assert_series_equal(left, right)
- [x] closes #55882 - [x] [Tests added and passed] - [x] All [code checks passed] - [ ] Added [type annotations] - [ ] 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/55934
2023-11-13T08:57:26Z
2023-11-27T18:41:01Z
2023-11-27T18:41:01Z
2023-12-05T08:45:48Z
BUG: pivot_table with margins and numeric columns
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index a33322aebab34..9ec71cbc36544 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -458,6 +458,7 @@ Reshaping - Bug in :func:`merge` returning columns in incorrect order when left and/or right is empty (:issue:`51929`) - Bug in :meth:`pandas.DataFrame.melt` where an exception was raised if ``var_name`` was not a string (:issue:`55948`) - Bug in :meth:`pandas.DataFrame.melt` where it would not preserve the datetime (:issue:`55254`) +- Bug in :meth:`pandas.DataFrame.pivot_table` where the row margin is incorrect when the columns have numeric names (:issue:`26568`) Sparse ^^^^^^ diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 79354fdd12a2d..c39fbfe6b6d33 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -421,9 +421,10 @@ def _all_key(key): row_margin = data[cols + values].groupby(cols, observed=observed).agg(aggfunc) row_margin = row_margin.stack(future_stack=True) - # slight hack - new_order = [len(cols)] + list(range(len(cols))) - row_margin.index = row_margin.index.reorder_levels(new_order) + # GH#26568. Use names instead of indices in case of numeric names + new_order_indices = [len(cols)] + list(range(len(cols))) + new_order_names = [row_margin.index.names[i] for i in new_order_indices] + row_margin.index = row_margin.index.reorder_levels(new_order_names) else: row_margin = data._constructor_sliced(np.nan, index=result.columns) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index aecdf0a9c6975..331bab175ec1c 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2664,3 +2664,18 @@ def test_pivot_table_handles_explicit_datetime_types(self): names=["a", "date"], ) tm.assert_index_equal(pivot.index, expected) + + def test_pivot_table_with_margins_and_numeric_column_names(self): + # GH#26568 + df = DataFrame([["a", "x", 1], ["a", "y", 2], ["b", "y", 3], ["b", "z", 4]]) + + result = df.pivot_table( + index=0, columns=1, values=2, aggfunc="sum", fill_value=0, margins=True + ) + + expected = DataFrame( + [[1, 2, 0, 3], [0, 3, 4, 7], [1, 5, 4, 10]], + columns=Index(["x", "y", "z", "All"], name=1), + index=Index(["a", "b", "All"], name=0), + ) + tm.assert_frame_equal(result, expected)
- [ ] closes #26568 - [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 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/55933
2023-11-13T08:23:50Z
2023-11-20T17:58:28Z
2023-11-20T17:58:28Z
2023-11-20T17:58:36Z
PERF: Cython 3.0 regression with frame constructor
diff --git a/pandas/_libs/lib.pyi b/pandas/_libs/lib.pyi index 15bd5a7379105..33f6f16381639 100644 --- a/pandas/_libs/lib.pyi +++ b/pandas/_libs/lib.pyi @@ -63,7 +63,11 @@ def is_string_array(values: np.ndarray, skipna: bool = ...): ... def is_float_array(values: np.ndarray, skipna: bool = ...): ... def is_integer_array(values: np.ndarray, skipna: bool = ...): ... def is_bool_array(values: np.ndarray, skipna: bool = ...): ... -def fast_multiget(mapping: dict, keys: np.ndarray, default=...) -> np.ndarray: ... +def fast_multiget( + mapping: dict, + keys: np.ndarray, # object[:] + default=..., +) -> np.ndarray: ... def fast_unique_multiple_list_gen(gen: Generator, sort: bool = ...) -> list: ... def fast_unique_multiple_list(lists: list, sort: bool | None = ...) -> list: ... def map_infer( diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 7ec70c8700a0a..50ea5f6d3f699 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -3088,7 +3088,7 @@ def to_object_array_tuples(rows: object) -> np.ndarray: @cython.wraparound(False) @cython.boundscheck(False) -def fast_multiget(dict mapping, ndarray keys, default=np.nan) -> np.ndarray: +def fast_multiget(dict mapping, object[:] keys, default=np.nan) -> np.ndarray: cdef: Py_ssize_t i, n = len(keys) object val
- [ ] 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. Handles the 5 `frame_ctor.FromDicts` regressions in #55179 There is only one use of this function: https://github.com/pandas-dev/pandas/blob/b2d9ec17c52084ee2b629633c9119c01ea11d387/pandas/core/internals/construction.py#L627 and it's guaranteed to always have object dtype: https://github.com/pandas-dev/pandas/blob/b2d9ec17c52084ee2b629633c9119c01ea11d387/pandas/core/internals/construction.py#L618-L619 ASVs on this branch: ``` | Change | Before [b2d9ec17] <perf_cython3_frame_dict_constructor~1> | After [951c5bfa] <perf_cython3_frame_dict_constructor> | Ratio | Benchmark (Parameter) | |----------|-------------------------------------------------------------|----------------------------------------------------------|---------|-----------------------------------------------------| | - | 17.2±0.2ms | 15.3±0.3ms | 0.89 | frame_ctor.FromDicts.time_nested_dict | | - | 13.2±0.2ms | 11.7±0.3ms | 0.89 | frame_ctor.FromDicts.time_nested_dict_index_columns | | - | 13.1±0.2ms | 11.3±0.3ms | 0.86 | frame_ctor.FromDicts.time_nested_dict_index | SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/55931
2023-11-13T00:00:28Z
2023-11-13T13:52:32Z
2023-11-13T13:52:32Z
2023-11-13T13:55:48Z
Fix for 55753 BUG: No kwargs in df.apply(raw=True) [ Backport to 2.1.x ]
diff --git a/doc/source/whatsnew/v2.1.4.rst b/doc/source/whatsnew/v2.1.4.rst index 04bbb0f806cbd..d61714d9473c6 100644 --- a/doc/source/whatsnew/v2.1.4.rst +++ b/doc/source/whatsnew/v2.1.4.rst @@ -21,7 +21,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +- Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55753`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/apply.py b/pandas/core/apply.py index e5683359c2fb9..43bc26f6eb637 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -923,7 +923,9 @@ def wrapper(*args, **kwargs): return wrapper - result = np.apply_along_axis(wrap_function(self.func), self.axis, self.values) + result = np.apply_along_axis( + wrap_function(self.func), self.axis, self.values, *self.args, **self.kwargs + ) # TODO: mixed type case if result.ndim == 2: diff --git a/pandas/tests/apply/test_frame_apply.py b/pandas/tests/apply/test_frame_apply.py index 3a3f73a68374b..92612861e551a 100644 --- a/pandas/tests/apply/test_frame_apply.py +++ b/pandas/tests/apply/test_frame_apply.py @@ -38,8 +38,9 @@ def test_apply(float_frame): @pytest.mark.parametrize("axis", [0, 1]) -def test_apply_args(float_frame, axis): - result = float_frame.apply(lambda x, y: x + y, axis, args=(1,)) +@pytest.mark.parametrize("raw", [True, False]) +def test_apply_args(float_frame, axis, raw): + result = float_frame.apply(lambda x, y: x + y, axis, args=(1,), raw=raw) expected = float_frame + 1 tm.assert_frame_equal(result, expected)
- [x] closes #55753 - [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/55930
2023-11-12T19:57:19Z
2023-11-14T15:40:07Z
2023-11-14T15:40:07Z
2023-11-14T23:04:02Z
BUG: Keep original values when taking with a new fill value
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index efa4a52993a90..8210bcf1feefe 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -445,7 +445,7 @@ Reshaping Sparse ^^^^^^ -- +- Bug in :meth:`SparseArray.take` when using a different fill value than the array's fill value (:issue:`55181`) - ExtensionArray diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index cf349220e4ba7..5db77db2a9c66 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -1086,9 +1086,10 @@ def _take_with_fill(self, indices, fill_value=None) -> np.ndarray: ) elif self.sp_index.npoints == 0: - # Avoid taking from the empty self.sp_values + # Use the old fill_value unless we took for an index of -1 _dtype = np.result_type(self.dtype.subtype, type(fill_value)) taken = np.full(sp_indexer.shape, fill_value=fill_value, dtype=_dtype) + taken[old_fill_indices] = self.fill_value else: taken = self.sp_values.take(sp_indexer) diff --git a/pandas/tests/arrays/sparse/test_indexing.py b/pandas/tests/arrays/sparse/test_indexing.py index d63d0fb07b404..60029ac06ddb4 100644 --- a/pandas/tests/arrays/sparse/test_indexing.py +++ b/pandas/tests/arrays/sparse/test_indexing.py @@ -166,9 +166,16 @@ def test_take(self, arr_data, arr): tm.assert_sp_array_equal(arr.take([0, 1, 2]), exp) def test_take_all_empty(self): - a = pd.array([0, 0], dtype=SparseDtype("int64")) - result = a.take([0, 1], allow_fill=True, fill_value=np.nan) - tm.assert_sp_array_equal(a, result) + sparse = pd.array([0, 0], dtype=SparseDtype("int64")) + result = sparse.take([0, 1], allow_fill=True, fill_value=np.nan) + tm.assert_sp_array_equal(sparse, result) + + def test_take_different_fill_value(self): + # Take with a different fill value shouldn't overwrite the original + sparse = pd.array([0.0], dtype=SparseDtype("float64", fill_value=0.0)) + result = sparse.take([0, -1], allow_fill=True, fill_value=np.nan) + expected = pd.array([0, np.nan], dtype=sparse.dtype) + tm.assert_sp_array_equal(expected, result) def test_take_fill_value(self): data = np.array([1, np.nan, 0, 3, 0])
- [x] closes #55181 - [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 an entry in the latest `doc/source/whatsnew/v2.2.0.rst` file if fixing a bug or adding a new feature. `SparseArray`'s `take` method could mix up the two possible fill values: the array's fill value and the `fill_value` argument provided to `take`. In the case of a non-empty sparse array whose values were all its fill value, `take` would ignore the array's fill value and only use its `fill_value` argument, even for valid indices. The return value would be all `fill_value`, rather than a mix of the two fill values.
https://api.github.com/repos/pandas-dev/pandas/pulls/55929
2023-11-12T16:11:01Z
2023-11-20T17:42:07Z
2023-11-20T17:42:07Z
2023-11-20T17:42:16Z
Fixes #55884- Added else for invalid fill_method
diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index f83a12b268b22..f8575b1b53908 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1863,9 +1863,11 @@ def get_result(self, copy: bool | None = True) -> DataFrame: right_indexer = cast("npt.NDArray[np.intp]", right_indexer) left_join_indexer = libjoin.ffill_indexer(left_indexer) right_join_indexer = libjoin.ffill_indexer(right_indexer) - else: + elif self.fill_method is None: left_join_indexer = left_indexer right_join_indexer = right_indexer + else: + raise ValueError("fill_method must be 'ffill' or None") result = self._reindex_and_concat( join_index, left_join_indexer, right_join_indexer, copy=copy diff --git a/pandas/tests/reshape/merge/test_merge_ordered.py b/pandas/tests/reshape/merge/test_merge_ordered.py index cfb4e92fb45cd..abd61026b4e37 100644 --- a/pandas/tests/reshape/merge/test_merge_ordered.py +++ b/pandas/tests/reshape/merge/test_merge_ordered.py @@ -1,3 +1,5 @@ +import re + import numpy as np import pytest @@ -209,3 +211,11 @@ def test_elements_not_in_by_but_in_df(self): msg = r"\{'h'\} not found in left columns" with pytest.raises(KeyError, match=msg): merge_ordered(left, right, on="E", left_by=["G", "h"]) + + @pytest.mark.parametrize("invalid_method", ["linear", "carrot"]) + def test_ffill_validate_fill_method(self, left, right, invalid_method): + # GH 55884 + with pytest.raises( + ValueError, match=re.escape("fill_method must be 'ffill' or None") + ): + merge_ordered(left, right, on="key", fill_method=invalid_method)
- [x] Closes #55884 - [x] Tests added and passed - [x] All code checks passed
https://api.github.com/repos/pandas-dev/pandas/pulls/55927
2023-11-12T14:29:10Z
2023-11-14T01:09:09Z
2023-11-14T01:09:09Z
2023-11-14T12:50:44Z
TST: Group by callable test
diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 8c2b95ba631ee..01768582299eb 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -297,6 +297,23 @@ def test_grouper_creation_bug3(self): expected = ser.groupby(level="one").sum() tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("func", [False, True]) + def test_grouper_returning_tuples(self, func): + # GH 22257 , both with dict and with callable + df = DataFrame({"X": ["A", "B", "A", "B"], "Y": [1, 4, 3, 2]}) + mapping = dict(zip(range(4), [("C", 5), ("D", 6)] * 2)) + + if func: + gb = df.groupby(by=lambda idx: mapping[idx], sort=False) + else: + gb = df.groupby(by=mapping, sort=False) + + name, expected = next(iter(gb)) + assert name == ("C", 5) + result = gb.get_group(name) + + tm.assert_frame_equal(result, expected) + def test_grouper_column_and_index(self): # GH 14327
The bug is fixed. Add the tests - [ ] closes #22257 - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\
https://api.github.com/repos/pandas-dev/pandas/pulls/55926
2023-11-12T12:36:36Z
2023-11-13T19:05:04Z
2023-11-13T19:05:04Z
2023-11-13T19:05:10Z
DOC: Clarify DataFrame.dropna lib.no_default kwarg behavior
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d2a9e9b1ba31f..8357dc4a48955 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6428,7 +6428,7 @@ def dropna( inplace: bool = False, ignore_index: bool = False, ) -> DataFrame | None: - """ + """dropna(self, *, axis = 0, how = 'any', thresh = no_default, subset = None, inplace = False, ignore_index = False) Remove missing values. See the :ref:`User Guide <missing_data>` for more on which values are
- [x] closes #55848 Changes <img width="745" alt="Screenshot 2023-11-11 at 9 42 37 PM" src="https://github.com/pandas-dev/pandas/assets/25352646/44286bca-31d8-45dd-a47f-a4697e53098f"> To <img width="917" alt="Screenshot 2023-11-11 at 9 42 12 PM" src="https://github.com/pandas-dev/pandas/assets/25352646/e53c7b6a-e9a6-48e7-8a3a-dfb518d39990"> by adding one-line function declaration to doc-string per sphinx default autodoc_docstring_signature behavior.
https://api.github.com/repos/pandas-dev/pandas/pulls/55925
2023-11-12T02:47:11Z
2023-11-17T13:50:22Z
null
2023-11-17T13:50:23Z
DOC: add whatsnew for 2.1.4
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index dd3599bba8e54..ec024f36d78b1 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -24,6 +24,7 @@ Version 2.1 .. toctree:: :maxdepth: 2 + v2.1.4 v2.1.3 v2.1.2 v2.1.1 diff --git a/doc/source/whatsnew/v2.1.4.rst b/doc/source/whatsnew/v2.1.4.rst new file mode 100644 index 0000000000000..04bbb0f806cbd --- /dev/null +++ b/doc/source/whatsnew/v2.1.4.rst @@ -0,0 +1,41 @@ +.. _whatsnew_214: + +What's new in 2.1.4 (December ??, 2023) +--------------------------------------- + +These are the changes in pandas 2.1.4. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.other: + +Other +~~~~~ +- +- + +.. --------------------------------------------------------------------------- +.. _whatsnew_214.contributors: + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v2.1.3..v2.1.4|HEAD
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55924
2023-11-12T02:32:46Z
2023-11-13T13:26:46Z
2023-11-13T13:26:46Z
2023-11-16T12:56:48Z
ASV: clean/simplify setup methods
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index 6ab8e4f14e979..3c78b0a9a60c8 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -1,7 +1,6 @@ from importlib import import_module import numpy as np -import pyarrow as pa import pandas as pd @@ -20,9 +19,9 @@ class Factorize: [True, False], [True, False], [ - "int", - "uint", - "float", + "int64", + "uint64", + "float64", "object", "object_str", "datetime64[ns]", @@ -36,28 +35,24 @@ class Factorize: def setup(self, unique, sort, dtype): N = 10**5 - string_index = tm.makeStringIndex(N) - string_arrow = None - if dtype == "string[pyarrow]": - try: - string_arrow = pd.array(string_index, dtype="string[pyarrow]") - except ImportError: - raise NotImplementedError - - data = { - "int": pd.Index(np.arange(N), dtype="int64"), - "uint": pd.Index(np.arange(N), dtype="uint64"), - "float": pd.Index(np.random.randn(N), dtype="float64"), - "object_str": string_index, - "object": pd.Index(np.arange(N), dtype="object"), - "datetime64[ns]": pd.date_range("2011-01-01", freq="h", periods=N), - "datetime64[ns, tz]": pd.date_range( - "2011-01-01", freq="h", periods=N, tz="Asia/Tokyo" - ), - "Int64": pd.array(np.arange(N), dtype="Int64"), - "boolean": pd.array(np.random.randint(0, 2, N), dtype="boolean"), - "string[pyarrow]": string_arrow, - }[dtype] + + if dtype in ["int64", "uint64", "Int64", "object"]: + data = pd.Index(np.arange(N), dtype=dtype) + elif dtype == "float64": + data = pd.Index(np.random.randn(N), dtype=dtype) + elif dtype == "boolean": + data = pd.array(np.random.randint(0, 2, N), dtype=dtype) + elif dtype == "datetime64[ns]": + data = pd.date_range("2011-01-01", freq="h", periods=N) + elif dtype == "datetime64[ns, tz]": + data = pd.date_range("2011-01-01", freq="h", periods=N, tz="Asia/Tokyo") + elif dtype == "object_str": + data = tm.makeStringIndex(N) + elif dtype == "string[pyarrow]": + data = pd.array(tm.makeStringIndex(N), dtype="string[pyarrow]") + else: + raise NotImplementedError + if not unique: data = data.repeat(5) self.data = data @@ -74,9 +69,9 @@ class Duplicated: [True, False], ["first", "last", False], [ - "int", - "uint", - "float", + "int64", + "uint64", + "float64", "string", "datetime64[ns]", "datetime64[ns, tz]", @@ -88,22 +83,20 @@ class Duplicated: def setup(self, unique, keep, dtype): N = 10**5 - data = { - "int": pd.Index(np.arange(N), dtype="int64"), - "uint": pd.Index(np.arange(N), dtype="uint64"), - "float": pd.Index(np.random.randn(N), dtype="float64"), - "string": tm.makeStringIndex(N), - "datetime64[ns]": pd.date_range("2011-01-01", freq="h", periods=N), - "datetime64[ns, tz]": pd.date_range( - "2011-01-01", freq="h", periods=N, tz="Asia/Tokyo" - ), - "timestamp[ms][pyarrow]": pd.Index( - np.arange(N), dtype=pd.ArrowDtype(pa.timestamp("ms")) - ), - "duration[s][pyarrow]": pd.Index( - np.arange(N), dtype=pd.ArrowDtype(pa.duration("s")) - ), - }[dtype] + if dtype in ["int64", "uint64"]: + data = pd.Index(np.arange(N), dtype=dtype) + elif dtype == "float64": + data = pd.Index(np.random.randn(N), dtype="float64") + elif dtype == "string": + data = tm.makeStringIndex(N) + elif dtype == "datetime64[ns]": + data = pd.date_range("2011-01-01", freq="h", periods=N) + elif dtype == "datetime64[ns, tz]": + data = pd.date_range("2011-01-01", freq="h", periods=N, tz="Asia/Tokyo") + elif dtype in ["timestamp[ms][pyarrow]", "duration[s][pyarrow]"]: + data = pd.Index(np.arange(N), dtype=dtype) + else: + raise NotImplementedError if not unique: data = data.repeat(5) self.idx = data @@ -181,21 +174,22 @@ class Quantile: params = [ [0, 0.5, 1], ["linear", "nearest", "lower", "higher", "midpoint"], - ["float", "int", "uint"], + ["float64", "int64", "uint64"], ] param_names = ["quantile", "interpolation", "dtype"] def setup(self, quantile, interpolation, dtype): N = 10**5 - data = { - "int": np.arange(N), - "uint": np.arange(N).astype(np.uint64), - "float": np.random.randn(N), - } - self.idx = pd.Series(data[dtype].repeat(5)) + if dtype in ["int64", "uint64"]: + data = np.arange(N, dtype=dtype) + elif dtype == "float64": + data = np.random.randn(N) + else: + raise NotImplementedError + self.ser = pd.Series(data.repeat(5)) def time_quantile(self, quantile, interpolation, dtype): - self.idx.quantile(quantile, interpolation=interpolation) + self.ser.quantile(quantile, interpolation=interpolation) class SortIntegerArray: diff --git a/asv_bench/benchmarks/array.py b/asv_bench/benchmarks/array.py index 0229cf15fbfb8..aefc6e6d3c307 100644 --- a/asv_bench/benchmarks/array.py +++ b/asv_bench/benchmarks/array.py @@ -31,9 +31,9 @@ def time_from_float_array(self): class IntegerArray: def setup(self): N = 250_000 - self.values_integer = np.array([1, 0, 1, 0] * N) - self.data = np.array([1, 2, 3, 4] * N, dtype="int64") - self.mask = np.array([False, False, True, False] * N) + self.values_integer = np.tile(np.array([1, 0, 1, 0]), N) + self.data = np.tile(np.array([1, 2, 3, 4], dtype="int64"), N) + self.mask = np.tile(np.array([False, False, True, False]), N) def time_constructor(self): pd.arrays.IntegerArray(self.data, self.mask) diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 84d4a28d675d5..7e70db5681850 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -260,18 +260,16 @@ class CategoricalSlicing: def setup(self, index): N = 10**6 categories = ["a", "b", "c"] - values = [0] * N + [1] * N + [2] * N if index == "monotonic_incr": - self.data = pd.Categorical.from_codes(values, categories=categories) + codes = np.repeat([0, 1, 2], N) elif index == "monotonic_decr": - self.data = pd.Categorical.from_codes( - list(reversed(values)), categories=categories - ) + codes = np.repeat([2, 1, 0], N) elif index == "non_monotonic": - self.data = pd.Categorical.from_codes([0, 1, 2] * N, categories=categories) + codes = np.tile([0, 1, 2], N) else: raise ValueError(f"Invalid index param: {index}") + self.data = pd.Categorical.from_codes(codes, categories=categories) self.scalar = 10000 self.list = list(range(10000)) self.cat_scalar = "b" diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index c4ab73553cf1a..f22a261041e17 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -640,7 +640,8 @@ def time_frame_nunique(self): class SeriesNuniqueWithNan: def setup(self): - self.ser = Series(100000 * (100 * [np.nan] + list(range(100)))).astype(float) + values = 100 * [np.nan] + list(range(100)) + self.ser = Series(np.tile(values, 10000), dtype=float) def time_series_nunique_nan(self): self.ser.nunique() diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index fb4523f78ccb5..c78819f75c52a 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -272,18 +272,20 @@ class ParallelReadCSV(BaseIO): def setup(self, dtype): rows = 10000 cols = 50 - data = { - "float": DataFrame(np.random.randn(rows, cols)), - "datetime": DataFrame( + if dtype == "float": + df = DataFrame(np.random.randn(rows, cols)) + elif dtype == "datetime": + df = DataFrame( np.random.randn(rows, cols), index=date_range("1/1/2000", periods=rows) - ), - "object": DataFrame( + ) + elif dtype == "object": + df = DataFrame( "foo", index=range(rows), columns=["object%03d" for _ in range(5)] - ), - } + ) + else: + raise NotImplementedError self.fname = f"__test_{dtype}__.csv" - df = data[dtype] df.to_csv(self.fname) @test_parallel(num_threads=2) diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index d36d88e7b6b42..5e3eb7c7d4dac 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -713,7 +713,7 @@ def setup(self, dtype, tie_method): if dtype == "datetime64": data = np.array([Timestamp("2011/01/01")] * N, dtype=dtype) else: - data = np.array([1] * N, dtype=dtype) + data = np.ones(N, dtype=dtype) self.df = DataFrame({"values": data, "key": ["foo"] * N}) def time_rank_ties(self, dtype, tie_method): diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py index 2d8014570466e..7e33223260e0f 100644 --- a/asv_bench/benchmarks/index_object.py +++ b/asv_bench/benchmarks/index_object.py @@ -161,9 +161,7 @@ def setup(self, dtype): self.sorted = self.idx.sort_values() half = N // 2 self.non_unique = self.idx[:half].append(self.idx[:half]) - self.non_unique_sorted = ( - self.sorted[:half].append(self.sorted[:half]).sort_values() - ) + self.non_unique_sorted = self.sorted[:half].repeat(2) self.key = self.sorted[N // 4] def time_boolean_array(self, dtype): diff --git a/asv_bench/benchmarks/indexing_engines.py b/asv_bench/benchmarks/indexing_engines.py index 6585a4be78dc6..fd3d0f0b9cf2e 100644 --- a/asv_bench/benchmarks/indexing_engines.py +++ b/asv_bench/benchmarks/indexing_engines.py @@ -71,14 +71,12 @@ def setup(self, engine_and_dtype, index_type, unique, N): if unique: arr = np.arange(N * 3, dtype=dtype) else: - values = list([1] * N + [2] * N + [3] * N) - arr = np.array(values, dtype=dtype) + arr = np.array([1, 2, 3], dtype=dtype).repeat(N) elif index_type == "monotonic_decr": if unique: arr = np.arange(N * 3, dtype=dtype)[::-1] else: - values = list([1] * N + [2] * N + [3] * N) - arr = np.array(values, dtype=dtype)[::-1] + arr = np.array([3, 2, 1], dtype=dtype).repeat(N) else: assert index_type == "non_monotonic" if unique: @@ -86,7 +84,7 @@ def setup(self, engine_and_dtype, index_type, unique, N): arr[:N] = np.arange(N * 2, N * 3, dtype=dtype) arr[N:] = np.arange(N * 2, dtype=dtype) else: - arr = np.array([1, 2, 3] * N, dtype=dtype) + arr = np.array([1, 2, 3], dtype=dtype).repeat(N) self.data = engine(arr) # code belows avoids populating the mapping etc. while timing. @@ -115,30 +113,29 @@ class MaskedNumericEngineIndexing: def setup(self, engine_and_dtype, index_type, unique, N): engine, dtype = engine_and_dtype + dtype = dtype.lower() if index_type == "monotonic_incr": if unique: - arr = np.arange(N * 3, dtype=dtype.lower()) + arr = np.arange(N * 3, dtype=dtype) else: - values = list([1] * N + [2] * N + [3] * N) - arr = np.array(values, dtype=dtype.lower()) + arr = np.array([1, 2, 3], dtype=dtype).repeat(N) mask = np.zeros(N * 3, dtype=np.bool_) elif index_type == "monotonic_decr": if unique: - arr = np.arange(N * 3, dtype=dtype.lower())[::-1] + arr = np.arange(N * 3, dtype=dtype)[::-1] else: - values = list([1] * N + [2] * N + [3] * N) - arr = np.array(values, dtype=dtype.lower())[::-1] + arr = np.array([3, 2, 1], dtype=dtype).repeat(N) mask = np.zeros(N * 3, dtype=np.bool_) else: assert index_type == "non_monotonic" if unique: - arr = np.zeros(N * 3, dtype=dtype.lower()) - arr[:N] = np.arange(N * 2, N * 3, dtype=dtype.lower()) - arr[N:] = np.arange(N * 2, dtype=dtype.lower()) + arr = np.zeros(N * 3, dtype=dtype) + arr[:N] = np.arange(N * 2, N * 3, dtype=dtype) + arr[N:] = np.arange(N * 2, dtype=dtype) else: - arr = np.array([1, 2, 3] * N, dtype=dtype.lower()) + arr = np.array([1, 2, 3], dtype=dtype).repeat(N) mask = np.zeros(N * 3, dtype=np.bool_) mask[-1] = True diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 459d562828f88..79cf8f9cd2048 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -317,7 +317,7 @@ def setup(self, func, N, dtype): if func == "argmax" and dtype in {"Int64", "boolean"}: # Skip argmax for nullable int since this doesn't work yet (GH-24382) raise NotImplementedError - self.s = Series([1] * N, dtype=dtype) + self.s = Series(np.ones(N), dtype=dtype) self.func = getattr(self.s, func) def time_func(self, func, N, dtype):
Trying to make some of the setup methods a bit more efficient. Might(?) save around a minute total on the ASV job. e.g. ``` import time from itertools import product from asv_bench.benchmarks.series_methods import NanOps param_sets = list(product(*NanOps.params)) t = time.time() for params in param_sets: try: NanOps().setup(*params) except NotImplementedError: pass print(time.time() - t) # 11.87 -> main # 1.90 -> PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/55923
2023-11-12T02:08:22Z
2023-11-14T01:08:15Z
2023-11-14T01:08:15Z
2023-11-16T12:56:48Z
Create create-issue.yml
diff --git a/.github/workflows/create-issue.yml b/.github/workflows/create-issue.yml new file mode 100644 index 0000000000000..a3d68fdbe2664 --- /dev/null +++ b/.github/workflows/create-issue.yml @@ -0,0 +1,25 @@ +name: Create Issue +on: + schedule: + # Run monthly on the 1st day of the month + - cron: '0 0 1 * *' +jobs: + linkcheck: + runs-on: ubuntu-latest + defaults: + run: + shell: bash -el {0} + + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Conda + uses: ./.github/actions/setup-conda + + - name: Build Pandas + uses: ./.github/actions/build_pandas + - name: Run create-issue script + working-directory: ./doc
This is a GIthub Action that creates a new issue (and delete the old one) reporting all the errors and label and Docs and Good First Issue for a broken link. - [x] closes #45409 (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/55922
2023-11-11T15:21:34Z
2023-11-17T14:08:32Z
null
2023-11-17T18:51:50Z
ASV: avoid "H" and "S" freq deprecations
diff --git a/asv_bench/benchmarks/algorithms.py b/asv_bench/benchmarks/algorithms.py index 192f19c36b47d..6ab8e4f14e979 100644 --- a/asv_bench/benchmarks/algorithms.py +++ b/asv_bench/benchmarks/algorithms.py @@ -50,9 +50,9 @@ def setup(self, unique, sort, dtype): "float": pd.Index(np.random.randn(N), dtype="float64"), "object_str": string_index, "object": pd.Index(np.arange(N), dtype="object"), - "datetime64[ns]": pd.date_range("2011-01-01", freq="H", periods=N), + "datetime64[ns]": pd.date_range("2011-01-01", freq="h", periods=N), "datetime64[ns, tz]": pd.date_range( - "2011-01-01", freq="H", periods=N, tz="Asia/Tokyo" + "2011-01-01", freq="h", periods=N, tz="Asia/Tokyo" ), "Int64": pd.array(np.arange(N), dtype="Int64"), "boolean": pd.array(np.random.randint(0, 2, N), dtype="boolean"), @@ -93,9 +93,9 @@ def setup(self, unique, keep, dtype): "uint": pd.Index(np.arange(N), dtype="uint64"), "float": pd.Index(np.random.randn(N), dtype="float64"), "string": tm.makeStringIndex(N), - "datetime64[ns]": pd.date_range("2011-01-01", freq="H", periods=N), + "datetime64[ns]": pd.date_range("2011-01-01", freq="h", periods=N), "datetime64[ns, tz]": pd.date_range( - "2011-01-01", freq="H", periods=N, tz="Asia/Tokyo" + "2011-01-01", freq="h", periods=N, tz="Asia/Tokyo" ), "timestamp[ms][pyarrow]": pd.Index( np.arange(N), dtype=pd.ArrowDtype(pa.timestamp("ms")) diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index 49543c166d047..d70ad144a3455 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -491,7 +491,7 @@ class BinaryOpsMultiIndex: param_names = ["func"] def setup(self, func): - array = date_range("20200101 00:00", "20200102 0:00", freq="S") + array = date_range("20200101 00:00", "20200102 0:00", freq="s") level_0_names = [str(i) for i in range(30)] index = pd.MultiIndex.from_product([level_0_names, array]) diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index e56fbf1d8c32f..c4ab73553cf1a 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -439,9 +439,9 @@ def setup(self, inplace, dtype): N, M = 10000, 100 if dtype in ("datetime64[ns]", "datetime64[ns, tz]", "timedelta64[ns]"): data = { - "datetime64[ns]": date_range("2011-01-01", freq="H", periods=N), + "datetime64[ns]": date_range("2011-01-01", freq="h", periods=N), "datetime64[ns, tz]": date_range( - "2011-01-01", freq="H", periods=N, tz="Asia/Tokyo" + "2011-01-01", freq="h", periods=N, tz="Asia/Tokyo" ), "timedelta64[ns]": timedelta_range(start="1 day", periods=N, freq="1D"), } @@ -649,7 +649,7 @@ def time_series_nunique_nan(self): class Duplicated: def setup(self): n = 1 << 20 - t = date_range("2015-01-01", freq="S", periods=(n // 64)) + t = date_range("2015-01-01", freq="s", periods=(n // 64)) xs = np.random.randn(n // 64).round(2) self.df = DataFrame( { diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index 4993ffd2c47d0..fb4523f78ccb5 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -212,7 +212,7 @@ def run(dti): def time_datetime_to_period(self): @test_parallel(num_threads=2) def run(dti): - dti.to_period("S") + dti.to_period("s") run(self.dti) diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 54c240e84243a..d36d88e7b6b42 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -238,7 +238,7 @@ def time_series_nth(self, dtype): class DateAttributes: def setup(self): - rng = date_range("1/1/2000", "12/31/2005", freq="H") + rng = date_range("1/1/2000", "12/31/2005", freq="h") self.year, self.month, self.day = rng.year, rng.month, rng.day self.ts = Series(np.random.randn(len(rng)), index=rng) diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 84d95a23bd446..d8b1bf327294a 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -232,7 +232,7 @@ def setup(self, index): N = 100000 indexes = { "int": Index(np.arange(N), dtype=np.int64), - "datetime": date_range("2011-01-01", freq="S", periods=N), + "datetime": date_range("2011-01-01", freq="s", periods=N), } index = indexes[index] self.s = Series(np.random.rand(N), index=index) @@ -465,7 +465,7 @@ def time_loc_row(self, unique_cols): class AssignTimeseriesIndex: def setup(self): N = 100000 - idx = date_range("1/1/2000", periods=N, freq="H") + idx = date_range("1/1/2000", periods=N, freq="h") self.df = DataFrame(np.random.randn(N, 1), columns=["A"], index=idx) def time_frame_assign_timeseries_index(self): diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py index 476ff14dcc92a..805b0c807452c 100644 --- a/asv_bench/benchmarks/inference.py +++ b/asv_bench/benchmarks/inference.py @@ -164,7 +164,7 @@ def time_unique_date_strings(self, cache, count): class ToDatetimeISO8601: def setup(self): - rng = date_range(start="1/1/2000", periods=20000, freq="H") + rng = date_range(start="1/1/2000", periods=20000, freq="h") self.strings = rng.strftime("%Y-%m-%d %H:%M:%S").tolist() self.strings_nosep = rng.strftime("%Y%m%d %H:%M:%S").tolist() self.strings_tz_space = [ @@ -276,7 +276,7 @@ def time_dup_string_tzoffset_dates(self, cache): # GH 43901 class ToDatetimeInferDatetimeFormat: def setup(self): - rng = date_range(start="1/1/2000", periods=100000, freq="H") + rng = date_range(start="1/1/2000", periods=100000, freq="h") self.strings = rng.strftime("%Y-%m-%d %H:%M:%S").tolist() def time_infer_datetime_format(self): diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py index c5e3e80571e30..1826291034dee 100644 --- a/asv_bench/benchmarks/io/csv.py +++ b/asv_bench/benchmarks/io/csv.py @@ -89,7 +89,7 @@ class ToCSVDatetimeIndex(BaseIO): fname = "__test__.csv" def setup(self): - rng = date_range("2000", periods=100_000, freq="S") + rng = date_range("2000", periods=100_000, freq="s") self.data = DataFrame({"a": 1}, index=rng) def time_frame_date_formatting_index(self): @@ -102,7 +102,7 @@ def time_frame_date_no_format_index(self): class ToCSVPeriod(BaseIO): fname = "__test__.csv" - params = ([1000, 10000], ["D", "H"]) + params = ([1000, 10000], ["D", "h"]) param_names = ["nobs", "freq"] def setup(self, nobs, freq): @@ -110,7 +110,7 @@ def setup(self, nobs, freq): self.data = DataFrame(rng) if freq == "D": self.default_fmt = "%Y-%m-%d" - elif freq == "H": + elif freq == "h": self.default_fmt = "%Y-%m-%d %H:00" def time_frame_period_formatting_default(self, nobs, freq): @@ -130,7 +130,7 @@ def time_frame_period_formatting(self, nobs, freq): class ToCSVPeriodIndex(BaseIO): fname = "__test__.csv" - params = ([1000, 10000], ["D", "H"]) + params = ([1000, 10000], ["D", "h"]) param_names = ["nobs", "freq"] def setup(self, nobs, freq): @@ -138,7 +138,7 @@ def setup(self, nobs, freq): self.data = DataFrame({"a": 1}, index=rng) if freq == "D": self.default_fmt = "%Y-%m-%d" - elif freq == "H": + elif freq == "h": self.default_fmt = "%Y-%m-%d %H:00" def time_frame_period_formatting_index(self, nobs, freq): @@ -253,7 +253,7 @@ class ReadCSVConcatDatetime(StringIORewind): iso8601 = "%Y-%m-%d %H:%M:%S" def setup(self): - rng = date_range("1/1/2000", periods=50000, freq="S") + rng = date_range("1/1/2000", periods=50000, freq="s") self.StringIO_input = StringIO("\n".join(rng.strftime(self.iso8601).tolist())) def time_read_csv(self): diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index c77c6b6f5727c..f8d81b0f6a699 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -25,7 +25,7 @@ def _generate_dataframe(): df = DataFrame( np.random.randn(N, C), columns=[f"float{i}" for i in range(C)], - index=date_range("20000101", periods=N, freq="H"), + index=date_range("20000101", periods=N, freq="h"), ) df["object"] = tm.makeStringIndex(N) return df diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py index f3e417e717609..195aaa158e178 100644 --- a/asv_bench/benchmarks/io/hdf.py +++ b/asv_bench/benchmarks/io/hdf.py @@ -122,7 +122,7 @@ def setup(self, format): self.df = DataFrame( np.random.randn(N, C), columns=[f"float{i}" for i in range(C)], - index=date_range("20000101", periods=N, freq="H"), + index=date_range("20000101", periods=N, freq="h"), ) self.df["object"] = tm.makeStringIndex(N) self.df.to_hdf(self.fname, "df", format=format) diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py index bebf6ee993aba..8a2e3fa87eb37 100644 --- a/asv_bench/benchmarks/io/json.py +++ b/asv_bench/benchmarks/io/json.py @@ -26,7 +26,7 @@ def setup(self, orient, index): N = 100000 indexes = { "int": np.arange(N), - "datetime": date_range("20000101", periods=N, freq="H"), + "datetime": date_range("20000101", periods=N, freq="h"), } df = DataFrame( np.random.randn(N, 5), @@ -48,7 +48,7 @@ def setup(self, index): N = 100000 indexes = { "int": np.arange(N), - "datetime": date_range("20000101", periods=N, freq="H"), + "datetime": date_range("20000101", periods=N, freq="h"), } df = DataFrame( np.random.randn(N, 5), @@ -108,7 +108,7 @@ class ToJSON(BaseIO): def setup(self, orient, frame): N = 10**5 ncols = 5 - index = date_range("20000101", periods=N, freq="H") + index = date_range("20000101", periods=N, freq="h") timedeltas = timedelta_range(start=1, periods=N, freq="s") datetimes = date_range(start=1, periods=N, freq="s") ints = np.random.randint(100000000, size=N) @@ -191,7 +191,7 @@ class ToJSONISO(BaseIO): def setup(self, orient): N = 10**5 - index = date_range("20000101", periods=N, freq="H") + index = date_range("20000101", periods=N, freq="h") timedeltas = timedelta_range(start=1, periods=N, freq="s") datetimes = date_range(start=1, periods=N, freq="s") self.df = DataFrame( @@ -214,7 +214,7 @@ class ToJSONLines(BaseIO): def setup(self): N = 10**5 ncols = 5 - index = date_range("20000101", periods=N, freq="H") + index = date_range("20000101", periods=N, freq="h") timedeltas = timedelta_range(start=1, periods=N, freq="s") datetimes = date_range(start=1, periods=N, freq="s") ints = np.random.randint(100000000, size=N) diff --git a/asv_bench/benchmarks/io/pickle.py b/asv_bench/benchmarks/io/pickle.py index c71cdcdcc5c59..54631d9236887 100644 --- a/asv_bench/benchmarks/io/pickle.py +++ b/asv_bench/benchmarks/io/pickle.py @@ -20,7 +20,7 @@ def setup(self): self.df = DataFrame( np.random.randn(N, C), columns=[f"float{i}" for i in range(C)], - index=date_range("20000101", periods=N, freq="H"), + index=date_range("20000101", periods=N, freq="h"), ) self.df["object"] = tm.makeStringIndex(N) self.df.to_pickle(self.fname) diff --git a/asv_bench/benchmarks/io/stata.py b/asv_bench/benchmarks/io/stata.py index 300b9c778f1f8..750bcf4ccee5c 100644 --- a/asv_bench/benchmarks/io/stata.py +++ b/asv_bench/benchmarks/io/stata.py @@ -23,7 +23,7 @@ def setup(self, convert_dates): self.df = DataFrame( np.random.randn(N, C), columns=[f"float{i}" for i in range(C)], - index=date_range("20000101", periods=N, freq="H"), + index=date_range("20000101", periods=N, freq="h"), ) self.df["object"] = tm.makeStringIndex(self.N) self.df["int8_"] = np.random.randint( diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py index 04ac47a892a22..23824c2c748df 100644 --- a/asv_bench/benchmarks/join_merge.py +++ b/asv_bench/benchmarks/join_merge.py @@ -213,7 +213,7 @@ class JoinNonUnique: # GH 6329 def setup(self): date_index = date_range("01-Jan-2013", "23-Jan-2013", freq="min") - daily_dates = date_index.to_period("D").to_timestamp("S", "S") + daily_dates = date_index.to_period("D").to_timestamp("s", "s") self.fracofday = date_index.values - daily_dates.values self.fracofday = self.fracofday.astype("timedelta64[ns]") self.fracofday = self.fracofday.astype(np.float64) / 86_400_000_000_000 diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py index 501fe198d41d8..ccd86cae06d58 100644 --- a/asv_bench/benchmarks/period.py +++ b/asv_bench/benchmarks/period.py @@ -45,7 +45,7 @@ def time_from_ints_daily(self, freq, is_offset): class DataFramePeriodColumn: def setup(self): - self.rng = period_range(start="1/1/1990", freq="S", periods=20000) + self.rng = period_range(start="1/1/1990", freq="s", periods=20000) self.df = DataFrame(index=range(len(self.rng))) def time_setitem_period_column(self): diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index f52f7a4bef37a..459d562828f88 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -64,7 +64,7 @@ def setup(self, dtype): N = 10**6 data = { "int": np.random.randint(1, 10, N), - "datetime": date_range("2000-01-01", freq="S", periods=N), + "datetime": date_range("2000-01-01", freq="s", periods=N), } self.s = Series(data[dtype]) if dtype == "datetime": @@ -92,7 +92,7 @@ class Fillna: def setup(self, dtype): N = 10**6 if dtype == "datetime64[ns]": - data = date_range("2000-01-01", freq="S", periods=N) + data = date_range("2000-01-01", freq="s", periods=N) na_value = NaT elif dtype in ("float64", "Float64"): data = np.random.randn(N) diff --git a/asv_bench/benchmarks/strftime.py b/asv_bench/benchmarks/strftime.py index 39cc82e1bdf79..47f25b331ab9b 100644 --- a/asv_bench/benchmarks/strftime.py +++ b/asv_bench/benchmarks/strftime.py @@ -53,7 +53,7 @@ def time_frame_datetime_formatting_custom(self, nobs): class PeriodStrftime: timeout = 1500 - params = ([1000, 10000], ["D", "H"]) + params = ([1000, 10000], ["D", "h"]) param_names = ["nobs", "freq"] def setup(self, nobs, freq): @@ -67,7 +67,7 @@ def setup(self, nobs, freq): self.data.set_index("i", inplace=True) if freq == "D": self.default_fmt = "%Y-%m-%d" - elif freq == "H": + elif freq == "h": self.default_fmt = "%Y-%m-%d %H:00" def time_frame_period_to_str(self, nobs, freq): diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index 8c78a9c1723df..8e1deb99a66a4 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -27,7 +27,7 @@ def setup(self, index_type): N = 100000 dtidxes = { "dst": date_range( - start="10/29/2000 1:00:00", end="10/29/2000 1:59:59", freq="S" + start="10/29/2000 1:00:00", end="10/29/2000 1:59:59", freq="s" ), "repeated": date_range(start="2000", periods=N / 10, freq="s").repeat(10), "tz_aware": date_range(start="2000", periods=N, freq="s", tz="US/Eastern"), @@ -72,13 +72,13 @@ class TzLocalize: def setup(self, tz): dst_rng = date_range( - start="10/29/2000 1:00:00", end="10/29/2000 1:59:59", freq="S" + start="10/29/2000 1:00:00", end="10/29/2000 1:59:59", freq="s" ) - self.index = date_range(start="10/29/2000", end="10/29/2000 00:59:59", freq="S") + self.index = date_range(start="10/29/2000", end="10/29/2000 00:59:59", freq="s") self.index = self.index.append(dst_rng) self.index = self.index.append(dst_rng) self.index = self.index.append( - date_range(start="10/29/2000 2:00:00", end="10/29/2000 3:00:00", freq="S") + date_range(start="10/29/2000 2:00:00", end="10/29/2000 3:00:00", freq="s") ) def time_infer_dst(self, tz): @@ -90,7 +90,7 @@ class ResetIndex: param_names = "tz" def setup(self, tz): - idx = date_range(start="1/1/2000", periods=1000, freq="H", tz=tz) + idx = date_range(start="1/1/2000", periods=1000, freq="h", tz=tz) self.df = DataFrame(np.random.randn(1000, 2), index=idx) def time_reset_datetimeindex(self, tz): @@ -255,7 +255,7 @@ def time_get_slice(self, monotonic): class Lookup: def setup(self): N = 1500000 - rng = date_range(start="1/1/2000", periods=N, freq="S") + rng = date_range(start="1/1/2000", periods=N, freq="s") self.ts = Series(1, index=rng) self.lookup_val = rng[N // 2]
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55921
2023-11-11T14:22:29Z
2023-11-11T19:52:01Z
2023-11-11T19:52:01Z
2023-11-16T12:56:48Z
Fix off-by-one in aggregations
diff --git a/pandas/core/indexers/objects.py b/pandas/core/indexers/objects.py index c13ec51ff3851..f2db4886a5590 100644 --- a/pandas/core/indexers/objects.py +++ b/pandas/core/indexers/objects.py @@ -102,7 +102,7 @@ def get_window_bounds( closed: str | None = None, step: int | None = None, ) -> tuple[np.ndarray, np.ndarray]: - if center: + if center or self.window_size == 0: offset = (self.window_size - 1) // 2 else: offset = 0
ref https://github.com/pandas-dev/pandas/issues/55713#issuecomment-1806580402 I'm not super familiar with this function so maybe there is a more intelligent way of doing this. But the segfault occurs when self.window_size == 0 because of these lines: ```python end = np.arange(1 + offset, num_values + 1 + offset, step, dtype="int64") start = end - self.window_size ``` In the segfaulting example, `num_values` is 20 for an array with 20 elements. `end` ends up becoming 1-20 as does start with the window_size of 0. Later code then tries to index the 20th index in array, hence the address violation
https://api.github.com/repos/pandas-dev/pandas/pulls/55920
2023-11-11T13:17:28Z
2023-11-13T18:53:11Z
2023-11-13T18:53:11Z
2023-11-13T19:02:05Z
TST: de-xfail some pyarrow tests
diff --git a/pandas/io/parsers/arrow_parser_wrapper.py b/pandas/io/parsers/arrow_parser_wrapper.py index 35965c90ee7fb..a1d69deb6a21e 100644 --- a/pandas/io/parsers/arrow_parser_wrapper.py +++ b/pandas/io/parsers/arrow_parser_wrapper.py @@ -13,6 +13,7 @@ ) from pandas.util._exceptions import find_stack_level +from pandas.core.dtypes.common import pandas_dtype from pandas.core.dtypes.inference import is_integer import pandas as pd @@ -203,7 +204,13 @@ def _finalize_pandas_output(self, frame: DataFrame) -> DataFrame: # Ignore non-existent columns from dtype mapping # like other parsers do if isinstance(self.dtype, dict): - self.dtype = {k: v for k, v in self.dtype.items() if k in frame.columns} + self.dtype = { + k: pandas_dtype(v) + for k, v in self.dtype.items() + if k in frame.columns + } + else: + self.dtype = pandas_dtype(self.dtype) try: frame = frame.astype(self.dtype) except TypeError as e: diff --git a/pandas/tests/io/parser/common/test_common_basic.py b/pandas/tests/io/parser/common/test_common_basic.py index 3abbd14c20e16..a2ffec45cfc7f 100644 --- a/pandas/tests/io/parser/common/test_common_basic.py +++ b/pandas/tests/io/parser/common/test_common_basic.py @@ -119,7 +119,6 @@ def test_read_csv_local(all_parsers, csv1): tm.assert_frame_equal(result, expected) -@xfail_pyarrow def test_1000_sep(all_parsers): parser = all_parsers data = """A|B|C @@ -128,6 +127,12 @@ def test_1000_sep(all_parsers): """ expected = DataFrame({"A": [1, 10], "B": [2334, 13], "C": [5, 10.0]}) + if parser.engine == "pyarrow": + msg = "The 'thousands' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), sep="|", thousands=",") + return + result = parser.read_csv(StringIO(data), sep="|", thousands=",") tm.assert_frame_equal(result, expected) @@ -161,7 +166,6 @@ def test_csv_mixed_type(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow def test_read_csv_low_memory_no_rows_with_index(all_parsers): # see gh-21141 parser = all_parsers @@ -174,6 +178,13 @@ def test_read_csv_low_memory_no_rows_with_index(all_parsers): 2,2,3,4 3,3,4,5 """ + + if parser.engine == "pyarrow": + msg = "The 'nrows' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0) + return + result = parser.read_csv(StringIO(data), low_memory=True, index_col=0, nrows=0) expected = DataFrame(columns=["A", "B", "C"]) tm.assert_frame_equal(result, expected) @@ -212,7 +223,6 @@ def test_read_csv_dataframe(all_parsers, csv1): tm.assert_frame_equal(result, expected) -@xfail_pyarrow @pytest.mark.parametrize("nrows", [3, 3.0]) def test_read_nrows(all_parsers, nrows): # see gh-10476 @@ -230,11 +240,16 @@ def test_read_nrows(all_parsers, nrows): ) parser = all_parsers + if parser.engine == "pyarrow": + msg = "The 'nrows' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), nrows=nrows) + return + result = parser.read_csv(StringIO(data), nrows=nrows) tm.assert_frame_equal(result, expected) -@xfail_pyarrow @pytest.mark.parametrize("nrows", [1.2, "foo", -1]) def test_read_nrows_bad(all_parsers, nrows): data = """index,A,B,C,D @@ -247,6 +262,8 @@ def test_read_nrows_bad(all_parsers, nrows): """ msg = r"'nrows' must be an integer >=0" parser = all_parsers + if parser.engine == "pyarrow": + msg = "The 'nrows' option is not supported with the 'pyarrow' engine" with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), nrows=nrows) @@ -277,7 +294,6 @@ def test_missing_trailing_delimiters(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow def test_skip_initial_space(all_parsers): data = ( '"09-Apr-2012", "01:10:18.300", 2456026.548822908, 12849, ' @@ -289,6 +305,18 @@ def test_skip_initial_space(all_parsers): ) parser = all_parsers + if parser.engine == "pyarrow": + msg = "The 'skipinitialspace' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(data), + names=list(range(33)), + header=None, + na_values=["-9999.0"], + skipinitialspace=True, + ) + return + result = parser.read_csv( StringIO(data), names=list(range(33)), @@ -437,7 +465,6 @@ def test_read_empty_with_usecols(all_parsers, data, kwargs, expected): tm.assert_frame_equal(result, expected) -@xfail_pyarrow @pytest.mark.parametrize( "kwargs,expected", [ @@ -467,6 +494,12 @@ def test_trailing_spaces(all_parsers, kwargs, expected): data = "A B C \nrandom line with trailing spaces \nskip\n1,2,3\n1,2.,4.\nrandom line with trailing tabs\t\t\t\n \n5.1,NaN,10.0\n" # noqa: E501 parser = all_parsers + if parser.engine == "pyarrow": + msg = "The 'delim_whitespace' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data.replace(",", " ")), **kwargs) + return + result = parser.read_csv(StringIO(data.replace(",", " ")), **kwargs) tm.assert_frame_equal(result, expected) @@ -488,7 +521,6 @@ def test_read_filepath_or_buffer(all_parsers): parser.read_csv(filepath_or_buffer=b"input") -@xfail_pyarrow @pytest.mark.parametrize("delim_whitespace", [True, False]) def test_single_char_leading_whitespace(all_parsers, delim_whitespace): # see gh-9710 @@ -501,6 +533,15 @@ def test_single_char_leading_whitespace(all_parsers, delim_whitespace): b\n""" expected = DataFrame({"MyColumn": list("abab")}) + + if parser.engine == "pyarrow": + msg = "The 'skipinitialspace' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(data), skipinitialspace=True, delim_whitespace=delim_whitespace + ) + return + result = parser.read_csv( StringIO(data), skipinitialspace=True, delim_whitespace=delim_whitespace ) @@ -688,7 +729,6 @@ def test_first_row_bom_unquoted(all_parsers): tm.assert_frame_equal(result, expected) -@xfail_pyarrow @pytest.mark.parametrize("nrows", range(1, 6)) def test_blank_lines_between_header_and_data_rows(all_parsers, nrows): # GH 28071 @@ -698,6 +738,15 @@ def test_blank_lines_between_header_and_data_rows(all_parsers, nrows): ) csv = "\nheader\n\na,b\n\n\n1,2\n\n3,4" parser = all_parsers + + if parser.engine == "pyarrow": + msg = "The 'nrows' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False + ) + return + df = parser.read_csv(StringIO(csv), header=3, nrows=nrows, skip_blank_lines=False) tm.assert_frame_equal(df, ref[:nrows]) @@ -731,11 +780,16 @@ def test_read_csv_names_not_accepting_sets(all_parsers): parser.read_csv(StringIO(data), names=set("QAZ")) -@xfail_pyarrow def test_read_table_delim_whitespace_default_sep(all_parsers): # GH: 35958 f = StringIO("a b c\n1 -2 -3\n4 5 6") parser = all_parsers + + if parser.engine == "pyarrow": + msg = "The 'delim_whitespace' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_table(f, delim_whitespace=True) + return result = parser.read_table(f, delim_whitespace=True) expected = DataFrame({"a": [1, 4], "b": [-2, 5], "c": [-3, 6]}) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_decimal.py b/pandas/tests/io/parser/common/test_decimal.py index b8a68c138eeff..4ceca037f589a 100644 --- a/pandas/tests/io/parser/common/test_decimal.py +++ b/pandas/tests/io/parser/common/test_decimal.py @@ -13,10 +13,7 @@ "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" ) -xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") - -@xfail_pyarrow @pytest.mark.parametrize( "data,thousands,decimal", [ @@ -42,6 +39,14 @@ def test_1000_sep_with_decimal(all_parsers, data, thousands, decimal): parser = all_parsers expected = DataFrame({"A": [1, 10], "B": [2334.01, 13], "C": [5, 10.0]}) + if parser.engine == "pyarrow": + msg = "The 'thousands' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(data), sep="|", thousands=thousands, decimal=decimal + ) + return + result = parser.read_csv( StringIO(data), sep="|", thousands=thousands, decimal=decimal ) 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 5d5814e880f8b..7fd86e956b543 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -214,8 +214,14 @@ def test_eof_states(all_parsers, data, kwargs, expected, msg, request): # see gh-10728, gh-10548 parser = all_parsers + if parser.engine == "pyarrow" and "comment" in kwargs: + msg = "The 'comment' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), **kwargs) + return + if parser.engine == "pyarrow" and "\r" not in data: - mark = pytest.mark.xfail(reason="The 'comment' option is not supported") + mark = pytest.mark.xfail(reason="Mismatched exception type/message") request.applymarker(mark) if expected is None: @@ -356,7 +362,6 @@ def test_read_csv_file_handle(all_parsers, io_class, encoding): assert not handle.closed -@xfail_pyarrow # ValueError: The 'memory_map' option is not supported def test_memory_map_compression(all_parsers, compression): """ Support memory map for compressed files. @@ -369,19 +374,32 @@ def test_memory_map_compression(all_parsers, compression): with tm.ensure_clean() as path: expected.to_csv(path, index=False, compression=compression) - tm.assert_frame_equal( - parser.read_csv(path, memory_map=True, compression=compression), - expected, - ) + if parser.engine == "pyarrow": + msg = "The 'memory_map' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(path, memory_map=True, compression=compression) + return + + result = parser.read_csv(path, memory_map=True, compression=compression) + + tm.assert_frame_equal( + result, + expected, + ) -@xfail_pyarrow # ValueError: The 'chunksize' option is not supported def test_context_manager(all_parsers, datapath): # make sure that opened files are closed parser = all_parsers path = datapath("io", "data", "csv", "iris.csv") + if parser.engine == "pyarrow": + msg = "The 'chunksize' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(path, chunksize=1) + return + reader = parser.read_csv(path, chunksize=1) assert not reader.handles.handle.closed try: @@ -392,12 +410,17 @@ def test_context_manager(all_parsers, datapath): assert reader.handles.handle.closed -@xfail_pyarrow # ValueError: The 'chunksize' option is not supported def test_context_manageri_user_provided(all_parsers, datapath): # make sure that user-provided handles are not closed parser = all_parsers with open(datapath("io", "data", "csv", "iris.csv"), encoding="utf-8") as path: + if parser.engine == "pyarrow": + msg = "The 'chunksize' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(path, chunksize=1) + return + reader = parser.read_csv(path, chunksize=1) assert not reader.handles.handle.closed try: @@ -417,7 +440,6 @@ def test_file_descriptor_leak(all_parsers, using_copy_on_write): parser.read_csv(path) -@xfail_pyarrow # ValueError: The 'memory_map' option is not supported def test_memory_map(all_parsers, csv_dir_path): mmap_file = os.path.join(csv_dir_path, "test_mmap.csv") parser = all_parsers @@ -426,5 +448,11 @@ def test_memory_map(all_parsers, csv_dir_path): {"a": [1, 2, 3], "b": ["one", "two", "three"], "c": ["I", "II", "III"]} ) + if parser.engine == "pyarrow": + msg = "The 'memory_map' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(mmap_file, memory_map=True) + return + result = parser.read_csv(mmap_file, memory_map=True) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/parser/common/test_ints.py b/pandas/tests/io/parser/common/test_ints.py index 086b43be59823..41bfbb55d818f 100644 --- a/pandas/tests/io/parser/common/test_ints.py +++ b/pandas/tests/io/parser/common/test_ints.py @@ -126,10 +126,8 @@ def test_int64_min_issues(all_parsers): tm.assert_frame_equal(result, expected) -# ValueError: The 'converters' option is not supported with the 'pyarrow' engine -@xfail_pyarrow @pytest.mark.parametrize("conv", [None, np.int64, np.uint64]) -def test_int64_overflow(all_parsers, conv): +def test_int64_overflow(all_parsers, conv, request): data = """ID 00013007854817840016671868 00013007854817840016749251 @@ -143,6 +141,10 @@ def test_int64_overflow(all_parsers, conv): if conv is None: # 13007854817840016671868 > UINT64_MAX, so this # will overflow and return object as the dtype. + if parser.engine == "pyarrow": + mark = pytest.mark.xfail(reason="parses to float64") + request.applymarker(mark) + result = parser.read_csv(StringIO(data)) expected = DataFrame( [ @@ -161,13 +163,19 @@ def test_int64_overflow(all_parsers, conv): # 13007854817840016671868 > UINT64_MAX, so attempts # to cast to either int64 or uint64 will result in # an OverflowError being raised. - msg = ( - "(Python int too large to convert to C long)|" - "(long too big to convert)|" - "(int too big to convert)" + msg = "|".join( + [ + "Python int too large to convert to C long", + "long too big to convert", + "int too big to convert", + ] ) + err = OverflowError + if parser.engine == "pyarrow": + err = ValueError + msg = "The 'converters' option is not supported with the 'pyarrow' engine" - with pytest.raises(OverflowError, match=msg): + with pytest.raises(err, match=msg): parser.read_csv(StringIO(data), converters={"ID": conv}) diff --git a/pandas/tests/io/parser/common/test_iterator.py b/pandas/tests/io/parser/common/test_iterator.py index 26619857bd231..a521c84aa007d 100644 --- a/pandas/tests/io/parser/common/test_iterator.py +++ b/pandas/tests/io/parser/common/test_iterator.py @@ -15,10 +15,8 @@ pytestmark = pytest.mark.filterwarnings( "ignore:Passing a BlockManager to DataFrame:DeprecationWarning" ) -xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") -@xfail_pyarrow # ValueError: The 'iterator' option is not supported def test_iterator(all_parsers): # see gh-6607 data = """index,A,B,C,D @@ -33,6 +31,13 @@ def test_iterator(all_parsers): kwargs = {"index_col": 0} expected = parser.read_csv(StringIO(data), **kwargs) + + if parser.engine == "pyarrow": + msg = "The 'iterator' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), iterator=True, **kwargs) + return + with parser.read_csv(StringIO(data), iterator=True, **kwargs) as reader: first_chunk = reader.read(3) tm.assert_frame_equal(first_chunk, expected[:3]) @@ -41,7 +46,6 @@ def test_iterator(all_parsers): tm.assert_frame_equal(last_chunk, expected[3:]) -@xfail_pyarrow # ValueError: The 'iterator' option is not supported def test_iterator2(all_parsers): parser = all_parsers data = """A,B,C @@ -50,6 +54,12 @@ def test_iterator2(all_parsers): baz,7,8,9 """ + if parser.engine == "pyarrow": + msg = "The 'iterator' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), iterator=True) + return + with parser.read_csv(StringIO(data), iterator=True) as reader: result = list(reader) @@ -61,7 +71,6 @@ def test_iterator2(all_parsers): tm.assert_frame_equal(result[0], expected) -@xfail_pyarrow # ValueError: The 'chunksize' option is not supported def test_iterator_stop_on_chunksize(all_parsers): # gh-3967: stopping iteration when chunksize is specified parser = all_parsers @@ -70,6 +79,11 @@ def test_iterator_stop_on_chunksize(all_parsers): bar,4,5,6 baz,7,8,9 """ + if parser.engine == "pyarrow": + msg = "The 'chunksize' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), chunksize=1) + return with parser.read_csv(StringIO(data), chunksize=1) as reader: result = list(reader) @@ -83,7 +97,6 @@ def test_iterator_stop_on_chunksize(all_parsers): tm.assert_frame_equal(concat(result), expected) -@xfail_pyarrow # AssertionError: Regex pattern did not match @pytest.mark.parametrize( "kwargs", [{"iterator": True, "chunksize": 1}, {"iterator": True}, {"chunksize": 1}] ) @@ -92,6 +105,12 @@ def test_iterator_skipfooter_errors(all_parsers, kwargs): parser = all_parsers data = "a\n1\n2" + if parser.engine == "pyarrow": + msg = ( + "The '(chunksize|iterator)' option is not supported with the " + "'pyarrow' engine" + ) + with pytest.raises(ValueError, match=msg): with parser.read_csv(StringIO(data), skipfooter=1, **kwargs) as _: pass diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py index 52ddb38192a6b..7e841ed8b4ebd 100644 --- a/pandas/tests/io/parser/common/test_read_errors.py +++ b/pandas/tests/io/parser/common/test_read_errors.py @@ -63,7 +63,6 @@ def test_bad_stream_exception(all_parsers, csv_dir_path): parser.read_csv(stream) -@xfail_pyarrow # ValueError: The 'comment' option is not supported def test_malformed(all_parsers): # see gh-6607 parser = all_parsers @@ -74,11 +73,14 @@ def test_malformed(all_parsers): 2,3,4 """ msg = "Expected 3 fields in line 4, saw 5" - with pytest.raises(ParserError, match=msg): + err = ParserError + if parser.engine == "pyarrow": + msg = "The 'comment' option is not supported with the 'pyarrow' engine" + err = ValueError + with pytest.raises(err, match=msg): parser.read_csv(StringIO(data), header=1, comment="#") -@xfail_pyarrow # ValueError: The 'iterator' option is not supported @pytest.mark.parametrize("nrows", [5, 3, None]) def test_malformed_chunks(all_parsers, nrows): data = """ignore @@ -90,6 +92,20 @@ def test_malformed_chunks(all_parsers, nrows): 2,3,4 """ parser = all_parsers + + if parser.engine == "pyarrow": + msg = "The 'iterator' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(data), + header=1, + comment="#", + iterator=True, + chunksize=1, + skiprows=[2], + ) + return + msg = "Expected 3 fields in line 6, saw 5" with parser.read_csv( StringIO(data), header=1, comment="#", iterator=True, chunksize=1, skiprows=[2] @@ -239,19 +255,21 @@ def test_null_byte_char(request, all_parsers): parser.read_csv(StringIO(data), names=names) -# ValueError: the 'pyarrow' engine does not support sep=None with delim_whitespace=False -@xfail_pyarrow @pytest.mark.filterwarnings("always::ResourceWarning") def test_open_file(request, all_parsers): # GH 39024 parser = all_parsers + + msg = "Could not determine delimiter" + err = csv.Error if parser.engine == "c": - request.applymarker( - pytest.mark.xfail( - reason=f"{parser.engine} engine does not support sep=None " - f"with delim_whitespace=False" - ) + msg = "the 'c' engine does not support sep=None with delim_whitespace=False" + err = ValueError + elif parser.engine == "pyarrow": + msg = ( + "the 'pyarrow' engine does not support sep=None with delim_whitespace=False" ) + err = ValueError with tm.ensure_clean() as path: file = Path(path) @@ -259,7 +277,7 @@ def test_open_file(request, all_parsers): with tm.assert_produces_warning(None): # should not trigger a ResourceWarning - with pytest.raises(csv.Error, match="Could not determine delimiter"): + with pytest.raises(err, match=msg): parser.read_csv(file, sep=None, encoding_errors="replace") diff --git a/pandas/tests/io/parser/common/test_verbose.py b/pandas/tests/io/parser/common/test_verbose.py index bcfb9cd4032ad..14deba8b40b22 100644 --- a/pandas/tests/io/parser/common/test_verbose.py +++ b/pandas/tests/io/parser/common/test_verbose.py @@ -6,10 +6,7 @@ import pytest -xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail") - -@xfail_pyarrow # ValueError: The 'verbose' option is not supported def test_verbose_read(all_parsers, capsys): parser = all_parsers data = """a,b,c,d @@ -22,6 +19,12 @@ def test_verbose_read(all_parsers, capsys): one,1,2,3 two,1,2,3""" + if parser.engine == "pyarrow": + msg = "The 'verbose' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), verbose=True) + return + # Engines are verbose in different ways. parser.read_csv(StringIO(data), verbose=True) captured = capsys.readouterr() @@ -33,7 +36,6 @@ def test_verbose_read(all_parsers, capsys): assert captured.out == "Filled 3 NA values in column a\n" -@xfail_pyarrow # ValueError: The 'verbose' option is not supported def test_verbose_read2(all_parsers, capsys): parser = all_parsers data = """a,b,c,d @@ -46,6 +48,12 @@ def test_verbose_read2(all_parsers, capsys): seven,1,2,3 eight,1,2,3""" + if parser.engine == "pyarrow": + msg = "The 'verbose' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), verbose=True, index_col=0) + return + parser.read_csv(StringIO(data), verbose=True, index_col=0) captured = capsys.readouterr() diff --git a/pandas/tests/io/parser/dtypes/test_categorical.py b/pandas/tests/io/parser/dtypes/test_categorical.py index c7586bd9334ef..b1b35447b60c2 100644 --- a/pandas/tests/io/parser/dtypes/test_categorical.py +++ b/pandas/tests/io/parser/dtypes/test_categorical.py @@ -146,8 +146,6 @@ def test_categorical_dtype_utf16(all_parsers, csv_dir_path): tm.assert_frame_equal(actual, expected) -# ValueError: The 'chunksize' option is not supported with the 'pyarrow' engine -@xfail_pyarrow def test_categorical_dtype_chunksize_infer_categories(all_parsers): # see gh-10153 parser = all_parsers @@ -160,6 +158,13 @@ def test_categorical_dtype_chunksize_infer_categories(all_parsers): DataFrame({"a": [1, 1], "b": Categorical(["a", "b"])}), DataFrame({"a": [1, 2], "b": Categorical(["b", "c"])}, index=[2, 3]), ] + + if parser.engine == "pyarrow": + msg = "The 'chunksize' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), dtype={"b": "category"}, chunksize=2) + return + with parser.read_csv( StringIO(data), dtype={"b": "category"}, chunksize=2 ) as actuals: @@ -167,8 +172,6 @@ def test_categorical_dtype_chunksize_infer_categories(all_parsers): tm.assert_frame_equal(actual, expected) -# ValueError: The 'chunksize' option is not supported with the 'pyarrow' engine -@xfail_pyarrow def test_categorical_dtype_chunksize_explicit_categories(all_parsers): # see gh-10153 parser = all_parsers @@ -186,6 +189,13 @@ def test_categorical_dtype_chunksize_explicit_categories(all_parsers): ), ] dtype = CategoricalDtype(cats) + + if parser.engine == "pyarrow": + msg = "The 'chunksize' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) + return + with parser.read_csv(StringIO(data), dtype={"b": dtype}, chunksize=2) as actuals: for actual, expected in zip(actuals, expecteds): tm.assert_frame_equal(actual, expected) diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py index 3f3d340ab2e08..32b4b1dedc3cb 100644 --- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py +++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py @@ -73,7 +73,6 @@ def test_dtype_per_column(all_parsers): tm.assert_frame_equal(result, expected) -@pytest.mark.usefixtures("pyarrow_xfail") def test_invalid_dtype_per_column(all_parsers): parser = all_parsers data = """\ @@ -87,7 +86,6 @@ def test_invalid_dtype_per_column(all_parsers): parser.read_csv(StringIO(data), dtype={"one": "foo", 1: "int"}) -@pytest.mark.usefixtures("pyarrow_xfail") def test_raise_on_passed_int_dtype_with_nas(all_parsers): # see gh-2631 parser = all_parsers @@ -96,22 +94,31 @@ def test_raise_on_passed_int_dtype_with_nas(all_parsers): 2001,,11 2001,106380451,67""" - msg = ( - "Integer column has NA values" - if parser.engine == "c" - else "Unable to convert column DOY" - ) + if parser.engine == "c": + msg = "Integer column has NA values" + elif parser.engine == "pyarrow": + msg = "The 'skipinitialspace' option is not supported with the 'pyarrow' engine" + else: + msg = "Unable to convert column DOY" + with pytest.raises(ValueError, match=msg): parser.read_csv(StringIO(data), dtype={"DOY": np.int64}, skipinitialspace=True) -@pytest.mark.usefixtures("pyarrow_xfail") def test_dtype_with_converters(all_parsers): parser = all_parsers data = """a,b 1.1,2.2 1.2,2.3""" + if parser.engine == "pyarrow": + msg = "The 'converters' option is not supported with the 'pyarrow' engine" + with pytest.raises(ValueError, match=msg): + parser.read_csv( + StringIO(data), dtype={"a": "i8"}, converters={"a": lambda x: str(x)} + ) + return + # Dtype spec ignored if converted specified. result = parser.read_csv_check_warnings( ParserWarning,
Test that we are giving useful exception messages, also these execute more quickly than xfails.
https://api.github.com/repos/pandas-dev/pandas/pulls/55918
2023-11-10T22:11:38Z
2023-11-11T01:39:51Z
2023-11-11T01:39:51Z
2023-11-17T22:14:57Z
REF: less state in scatterplot
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index d59220a1f97f8..31b61906cac53 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -22,6 +22,7 @@ import matplotlib as mpl import numpy as np +from pandas._libs import lib from pandas.errors import AbstractMethodError from pandas.util._decorators import cache_readonly from pandas.util._exceptions import find_stack_level @@ -1221,13 +1222,6 @@ def __init__(self, data, x, y, **kwargs) -> None: if is_integer(y) and not self.data.columns._holds_integer(): y = self.data.columns[y] - # Scatter plot allows to plot objects data - if self._kind == "hexbin": - if len(self.data[x]._get_numeric_data()) == 0: - raise ValueError(self._kind + " requires x column to be numeric") - if len(self.data[y]._get_numeric_data()) == 0: - raise ValueError(self._kind + " requires y column to be numeric") - self.x = x self.y = y @@ -1269,14 +1263,30 @@ class ScatterPlot(PlanePlot): def _kind(self) -> Literal["scatter"]: return "scatter" - def __init__(self, data, x, y, s=None, c=None, **kwargs) -> None: + def __init__( + self, + data, + x, + y, + s=None, + c=None, + *, + colorbar: bool | lib.NoDefault = lib.no_default, + norm=None, + **kwargs, + ) -> None: if s is None: # hide the matplotlib default for size, in case we want to change # the handling of this argument later s = 20 elif is_hashable(s) and s in data.columns: s = data[s] - super().__init__(data, x, y, s=s, **kwargs) + self.s = s + + self.colorbar = colorbar + self.norm = norm + + super().__init__(data, x, y, **kwargs) if is_integer(c) and not self.data.columns._holds_integer(): c = self.data.columns[c] self.c = c @@ -1292,6 +1302,44 @@ def _make_plot(self, fig: Figure): ) color = self.kwds.pop("color", None) + c_values = self._get_c_values(color, color_by_categorical, c_is_column) + norm, cmap = self._get_norm_and_cmap(c_values, color_by_categorical) + cb = self._get_colorbar(c_values, c_is_column) + + if self.legend: + label = self.label + else: + label = None + scatter = ax.scatter( + data[x].values, + data[y].values, + c=c_values, + label=label, + cmap=cmap, + norm=norm, + s=self.s, + **self.kwds, + ) + if cb: + cbar_label = c if c_is_column else "" + cbar = self._plot_colorbar(ax, fig=fig, label=cbar_label) + if color_by_categorical: + n_cats = len(self.data[c].cat.categories) + cbar.set_ticks(np.linspace(0.5, n_cats - 0.5, n_cats)) + cbar.ax.set_yticklabels(self.data[c].cat.categories) + + if label is not None: + self._append_legend_handles_labels(scatter, label) + + errors_x = self._get_errorbars(label=x, index=0, yerr=False) + errors_y = self._get_errorbars(label=y, index=0, xerr=False) + if len(errors_x) > 0 or len(errors_y) > 0: + err_kwds = dict(errors_x, **errors_y) + err_kwds["ecolor"] = scatter.get_facecolor()[0] + ax.errorbar(data[x].values, data[y].values, linestyle="none", **err_kwds) + + def _get_c_values(self, color, color_by_categorical: bool, c_is_column: bool): + c = self.c if c is not None and color is not None: raise TypeError("Specify exactly one of `c` and `color`") if c is None and color is None: @@ -1304,7 +1352,10 @@ def _make_plot(self, fig: Figure): c_values = self.data[c].values else: c_values = c + return c_values + def _get_norm_and_cmap(self, c_values, color_by_categorical: bool): + c = self.c if self.colormap is not None: cmap = mpl.colormaps.get_cmap(self.colormap) # cmap is only used if c_values are integers, otherwise UserWarning. @@ -1323,45 +1374,21 @@ def _make_plot(self, fig: Figure): cmap = colors.ListedColormap([cmap(i) for i in range(cmap.N)]) bounds = np.linspace(0, n_cats, n_cats + 1) norm = colors.BoundaryNorm(bounds, cmap.N) + # TODO: warn that we are ignoring self.norm if user specified it? + # Doesn't happen in any tests 2023-11-09 else: - norm = self.kwds.pop("norm", None) + norm = self.norm + return norm, cmap + + def _get_colorbar(self, c_values, c_is_column: bool) -> bool: # plot colorbar if # 1. colormap is assigned, and # 2.`c` is a column containing only numeric values plot_colorbar = self.colormap or c_is_column - cb = self.kwds.pop("colorbar", is_numeric_dtype(c_values) and plot_colorbar) - - if self.legend and hasattr(self, "label"): - label = self.label - else: - label = None - scatter = ax.scatter( - data[x].values, - data[y].values, - c=c_values, - label=label, - cmap=cmap, - norm=norm, - **self.kwds, - ) - if cb: - cbar_label = c if c_is_column else "" - cbar = self._plot_colorbar(ax, fig=fig, label=cbar_label) - if color_by_categorical: - cbar.set_ticks(np.linspace(0.5, n_cats - 0.5, n_cats)) - cbar.ax.set_yticklabels(self.data[c].cat.categories) - - if label is not None: - self._append_legend_handles_labels(scatter, label) - else: - self.legend = False - - errors_x = self._get_errorbars(label=x, index=0, yerr=False) - errors_y = self._get_errorbars(label=y, index=0, xerr=False) - if len(errors_x) > 0 or len(errors_y) > 0: - err_kwds = dict(errors_x, **errors_y) - err_kwds["ecolor"] = scatter.get_facecolor()[0] - ax.errorbar(data[x].values, data[y].values, linestyle="none", **err_kwds) + cb = self.colorbar + if cb is lib.no_default: + return is_numeric_dtype(c_values) and plot_colorbar + return cb class HexBinPlot(PlanePlot): @@ -1369,19 +1396,27 @@ class HexBinPlot(PlanePlot): def _kind(self) -> Literal["hexbin"]: return "hexbin" - def __init__(self, data, x, y, C=None, **kwargs) -> None: + def __init__(self, data, x, y, C=None, *, colorbar: bool = True, **kwargs) -> None: super().__init__(data, x, y, **kwargs) if is_integer(C) and not self.data.columns._holds_integer(): C = self.data.columns[C] self.C = C + self.colorbar = colorbar + + # Scatter plot allows to plot objects data + if len(self.data[self.x]._get_numeric_data()) == 0: + raise ValueError(self._kind + " requires x column to be numeric") + if len(self.data[self.y]._get_numeric_data()) == 0: + raise ValueError(self._kind + " requires y column to be numeric") + def _make_plot(self, fig: Figure) -> None: x, y, data, C = self.x, self.y, self.data, self.C ax = self.axes[0] # pandas uses colormap, matplotlib uses cmap. cmap = self.colormap or "BuGn" cmap = mpl.colormaps.get_cmap(cmap) - cb = self.kwds.pop("colorbar", True) + cb = self.colorbar if C is None: c_values = 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/55917
2023-11-10T20:21:09Z
2023-11-10T22:51:00Z
2023-11-10T22:51:00Z
2023-11-11T00:46:01Z
Fix Cython 3.0 regression with time_loc_dups
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index f0dd16b6c75e4..0dc139781f58d 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -1,4 +1,5 @@ cimport cython +from cpython.sequence cimport PySequence_GetItem import numpy as np @@ -77,7 +78,7 @@ cdef ndarray _get_bool_indexer(ndarray values, object val, ndarray mask = None): indexer = np.empty(len(values), dtype=np.uint8) for i in range(len(values)): - item = values[i] + item = PySequence_GetItem(values, i) indexer[i] = is_matching_na(item, val) else: @@ -405,7 +406,7 @@ cdef class IndexEngine: found_nas = set() for i in range(n): - val = values[i] + val = PySequence_GetItem(values, i) # GH#43870 # handle lookup for nas @@ -437,7 +438,7 @@ cdef class IndexEngine: d[val].append(i) for i in range(n_t): - val = targets[i] + val = PySequence_GetItem(targets, i) # ensure there are nas in values before looking for a matching na if check_na_values and checknull(val): @@ -488,22 +489,22 @@ cdef Py_ssize_t _bin_search(ndarray values, object val) except -1: Py_ssize_t mid = 0, lo = 0, hi = len(values) - 1 object pval - if hi == 0 or (hi > 0 and val > values[hi]): + if hi == 0 or (hi > 0 and val > PySequence_GetItem(values, hi)): return len(values) while lo < hi: mid = (lo + hi) // 2 - pval = values[mid] + pval = PySequence_GetItem(values, mid) if val < pval: hi = mid elif val > pval: lo = mid + 1 else: - while mid > 0 and val == values[mid - 1]: + while mid > 0 and val == PySequence_GetItem(values, mid - 1): mid -= 1 return mid - if val <= values[mid]: + if val <= PySequence_GetItem(values, mid): return mid else: return mid + 1 @@ -591,7 +592,7 @@ cdef class DatetimeEngine(Int64Engine): loc = values.searchsorted(conv, side="left") - if loc == len(values) or values[loc] != conv: + if loc == len(values) or PySequence_GetItem(values, loc) != conv: raise KeyError(val) return loc @@ -962,7 +963,7 @@ cdef class SharedEngine: res = np.empty(N, dtype=np.intp) for i in range(N): - val = values[i] + val = PySequence_GetItem(values, i) try: loc = self.get_loc(val) # Because we are unique, loc should always be an integer @@ -996,7 +997,7 @@ cdef class SharedEngine: # See also IntervalIndex.get_indexer_pointwise for i in range(N): - val = targets[i] + val = PySequence_GetItem(targets, i) try: locs = self.get_loc(val) @@ -1176,9 +1177,9 @@ cdef class MaskedIndexEngine(IndexEngine): na_pos = [] for i in range(n): - val = values[i] + val = PySequence_GetItem(values, i) - if mask[i]: + if PySequence_GetItem(mask, i): na_pos.append(i) else: @@ -1188,9 +1189,9 @@ cdef class MaskedIndexEngine(IndexEngine): d[val].append(i) for i in range(n_t): - val = target_vals[i] + val = PySequence_GetItem(target_vals, i) - if target_mask[i]: + if PySequence_GetItem(target_mask, i): if na_pos: for na_idx in na_pos: # realloc if needed
re https://github.com/pandas-dev/pandas/pull/55179 From discussion in https://github.com/cython/cython/issues/1807#issuecomment-1802656280 it looks like Cython prior to 3.0 would always use the sequence protocol for indexing with an integral value. However, Python prefers the object protocol first if available, and Cython switched to match that logic with 3.0 NumPy arrays implement both the sequence and the mapping protocol. In cases where we have untyped arrays that fall back to Python calls we will see a performance regression since this will now route through the mapping space The changes in this PR are not meant to be an exhaustive review of the codebase, rather just a quick POC to reset the time_loc_dups benchmark
https://api.github.com/repos/pandas-dev/pandas/pulls/55915
2023-11-10T15:52:27Z
2023-11-10T22:49:02Z
2023-11-10T22:49:02Z
2023-11-11T00:07:37Z
Backport PR #55907 on branch 2.1.x (DOC: Add release date for 2.1.3)
diff --git a/doc/source/whatsnew/v2.1.3.rst b/doc/source/whatsnew/v2.1.3.rst index 531559c259b44..af626895a9e0e 100644 --- a/doc/source/whatsnew/v2.1.3.rst +++ b/doc/source/whatsnew/v2.1.3.rst @@ -1,6 +1,6 @@ .. _whatsnew_213: -What's new in 2.1.3 (November ??, 2023) +What's new in 2.1.3 (November 10, 2023) --------------------------------------- These are the changes in pandas 2.1.3. See :ref:`release` for a full changelog @@ -14,7 +14,6 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed infinite recursion from operations that return a new object on some DataFrame subclasses (:issue:`55763`) -- .. --------------------------------------------------------------------------- .. _whatsnew_213.bug_fixes: @@ -25,14 +24,6 @@ Bug fixes - Bug in :meth:`Index.isin` raising for Arrow backed string and ``None`` value (:issue:`55821`) - Fix :func:`read_parquet` and :func:`read_feather` for `CVE-2023-47248 <https://www.cve.org/CVERecord?id=CVE-2023-47248>`__ (:issue:`55894`) -.. --------------------------------------------------------------------------- -.. _whatsnew_213.other: - -Other -~~~~~ -- -- - .. --------------------------------------------------------------------------- .. _whatsnew_213.contributors:
Backport PR #55907: DOC: Add release date for 2.1.3
https://api.github.com/repos/pandas-dev/pandas/pulls/55913
2023-11-10T13:36:32Z
2023-11-10T13:54:05Z
2023-11-10T13:54:05Z
2023-11-10T13:54:06Z
Backport PR #55911 on branch 2.1.x (DOC: convert outdated example of NumPy's broadcasting to literal code block)
diff --git a/doc/source/whatsnew/v0.17.0.rst b/doc/source/whatsnew/v0.17.0.rst index abbda2ffc9be2..5a668e5fabd9c 100644 --- a/doc/source/whatsnew/v0.17.0.rst +++ b/doc/source/whatsnew/v0.17.0.rst @@ -726,10 +726,10 @@ be broadcast: or it can return False if broadcasting can not be done: -.. ipython:: python - :okwarning: +.. code-block:: ipython - np.array([1, 2, 3]) == np.array([1, 2]) + In [11]: np.array([1, 2, 3]) == np.array([1, 2]) + Out[11]: False Changes to boolean comparisons vs. None ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Backport PR #55911: DOC: convert outdated example of NumPy's broadcasting to literal code block
https://api.github.com/repos/pandas-dev/pandas/pulls/55912
2023-11-10T13:35:48Z
2023-11-10T15:41:44Z
2023-11-10T15:41:44Z
2023-11-10T15:41:44Z
DOC: convert outdated example of NumPy's broadcasting to literal code block
diff --git a/doc/source/whatsnew/v0.17.0.rst b/doc/source/whatsnew/v0.17.0.rst index ec441688fc91e..fb71ec60a22f0 100644 --- a/doc/source/whatsnew/v0.17.0.rst +++ b/doc/source/whatsnew/v0.17.0.rst @@ -727,10 +727,10 @@ be broadcast: or it can return False if broadcasting can not be done: -.. ipython:: python - :okwarning: +.. code-block:: ipython - np.array([1, 2, 3]) == np.array([1, 2]) + In [11]: np.array([1, 2, 3]) == np.array([1, 2]) + Out[11]: False Changes to boolean comparisons vs. None ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Similar like https://github.com/pandas-dev/pandas/pull/55427, and breaking this off from https://github.com/pandas-dev/pandas/pull/55885
https://api.github.com/repos/pandas-dev/pandas/pulls/55911
2023-11-10T13:32:50Z
2023-11-10T13:34:44Z
2023-11-10T13:34:44Z
2023-11-10T13:34:48Z
WIP set full column if using self.index in loc
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 13756dd5a70e4..8a9880354a24a 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1454,6 +1454,9 @@ def _convert_to_indexer(self, key, axis: AxisInt): if isinstance(key, slice): return labels._convert_slice_indexer(key, kind="loc") + if key is self.obj.index: + return slice(None, None, None) + if ( isinstance(key, tuple) and not isinstance(labels, MultiIndex) diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 49dd7a3c4df9b..9f79fa3c59caa 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -1351,3 +1351,11 @@ def test_frame_setitem_empty_dataframe(self): index=Index([], dtype="datetime64[ns]", name="date"), ) tm.assert_frame_equal(df, expected) + + def test_setitem_frame_with_dataframes_own_index(self): + # https://github.com/pandas-dev/pandas/issues/55791 + df1 = DataFrame({"a": [1]}) + df2 = DataFrame({"d": [True]}) + df1.loc[df1.index, df2.columns] = df2 + expected = DataFrame({"a": [1], "d": [True]}) + tm.assert_frame_equal(df1, 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. closes https://github.com/pandas-dev/pandas/issues/55791
https://api.github.com/repos/pandas-dev/pandas/pulls/55910
2023-11-10T12:37:20Z
2023-11-10T14:19:54Z
null
2023-11-10T14:32:57Z
DOC: Add release date for 2.1.3
diff --git a/doc/source/whatsnew/v2.1.3.rst b/doc/source/whatsnew/v2.1.3.rst index 531559c259b44..af626895a9e0e 100644 --- a/doc/source/whatsnew/v2.1.3.rst +++ b/doc/source/whatsnew/v2.1.3.rst @@ -1,6 +1,6 @@ .. _whatsnew_213: -What's new in 2.1.3 (November ??, 2023) +What's new in 2.1.3 (November 10, 2023) --------------------------------------- These are the changes in pandas 2.1.3. See :ref:`release` for a full changelog @@ -14,7 +14,6 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed infinite recursion from operations that return a new object on some DataFrame subclasses (:issue:`55763`) -- .. --------------------------------------------------------------------------- .. _whatsnew_213.bug_fixes: @@ -25,14 +24,6 @@ Bug fixes - Bug in :meth:`Index.isin` raising for Arrow backed string and ``None`` value (:issue:`55821`) - Fix :func:`read_parquet` and :func:`read_feather` for `CVE-2023-47248 <https://www.cve.org/CVERecord?id=CVE-2023-47248>`__ (:issue:`55894`) -.. --------------------------------------------------------------------------- -.. _whatsnew_213.other: - -Other -~~~~~ -- -- - .. --------------------------------------------------------------------------- .. _whatsnew_213.contributors:
- [ ] 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/55907
2023-11-10T03:49:44Z
2023-11-10T13:36:25Z
2023-11-10T13:36:25Z
2023-11-10T13:36:25Z
REF: avoid altering self.data in get_xticks
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index d59220a1f97f8..d455612487b11 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -45,15 +45,13 @@ ) from pandas.core.dtypes.generic import ( ABCDataFrame, + ABCDatetimeIndex, ABCIndex, ABCMultiIndex, ABCPeriodIndex, ABCSeries, ) -from pandas.core.dtypes.missing import ( - isna, - notna, -) +from pandas.core.dtypes.missing import isna import pandas.core.common as com from pandas.core.frame import DataFrame @@ -94,10 +92,7 @@ npt, ) - from pandas import ( - PeriodIndex, - Series, - ) + from pandas import Series def _color_in_style(style: str) -> bool: @@ -887,26 +882,25 @@ def plt(self): _need_to_set_index = False @final - def _get_xticks(self, convert_period: bool = False): + def _get_xticks(self): index = self.data.index is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time") x: list[int] | np.ndarray if self.use_index: - if convert_period and isinstance(index, ABCPeriodIndex): - self.data = self.data.reindex(index=index.sort_values()) - index = cast("PeriodIndex", self.data.index) + if isinstance(index, ABCPeriodIndex): + # test_mixed_freq_irreg_period x = index.to_timestamp()._mpl_repr() + # TODO: why do we need to do to_timestamp() here but not other + # places where we call mpl_repr? elif is_any_real_numeric_dtype(index.dtype): # Matplotlib supports numeric values or datetime objects as # xaxis values. Taking LBYL approach here, by the time # matplotlib raises exception when using non numeric/datetime # values for xaxis, several actions are already taken by plt. x = index._mpl_repr() - elif is_datetype: - self.data = self.data[notna(self.data.index)] - self.data = self.data.sort_index() - x = self.data.index._mpl_repr() + elif isinstance(index, ABCDatetimeIndex) or is_datetype: + x = index._mpl_repr() else: self._need_to_set_index = True x = list(range(len(index))) @@ -1434,7 +1428,7 @@ def _make_plot(self, fig: Figure) -> None: plotf = self._ts_plot it = data.items() else: - x = self._get_xticks(convert_period=True) + x = self._get_xticks() # error: Incompatible types in assignment (expression has type # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 2ef1f065f603d..f002d7a6e66ab 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -1362,16 +1362,27 @@ def test_specified_props_kwd_plot_box(self, props, expected): assert result[expected][0].get_color() == "C1" def test_unordered_ts(self): + # GH#2609, GH#55906 + index = [date(2012, 10, 1), date(2012, 9, 1), date(2012, 8, 1)] + values = [3.0, 2.0, 1.0] df = DataFrame( - np.array([3.0, 2.0, 1.0]), - index=[date(2012, 10, 1), date(2012, 9, 1), date(2012, 8, 1)], + np.array(values), + index=index, columns=["test"], ) ax = df.plot() xticks = ax.lines[0].get_xdata() - assert xticks[0] < xticks[1] + tm.assert_numpy_array_equal(xticks, np.array(index, dtype=object)) ydata = ax.lines[0].get_ydata() - tm.assert_numpy_array_equal(ydata, np.array([1.0, 2.0, 3.0])) + tm.assert_numpy_array_equal(ydata, np.array(values)) + + # even though we don't sort the data before passing it to matplotlib, + # the ticks are sorted + xticks = ax.xaxis.get_ticklabels() + xlocs = [x.get_position()[0] for x in xticks] + assert pd.Index(xlocs).is_monotonic_increasing + xlabels = [x.get_text() for x in xticks] + assert pd.to_datetime(xlabels, format="%Y-%m-%d").is_monotonic_increasing @pytest.mark.parametrize("kind", plotting.PlotAccessor._common_kinds) def test_kind_both_ways(self, kind):
- [ ] 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/55906
2023-11-10T02:07:10Z
2023-11-10T22:53:17Z
2023-11-10T22:53:17Z
2023-11-11T00:44:46Z
REF: avoid statefulness in 'color' args
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index fa45e6b21fbef..05e6d2bcfb46a 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -10,6 +10,7 @@ from matplotlib.artist import setp import numpy as np +from pandas._libs import lib from pandas.util._decorators import cache_readonly from pandas.util._exceptions import find_stack_level @@ -113,26 +114,26 @@ def _plot( # type: ignore[override] else: return ax, bp - def _validate_color_args(self): - if "color" in self.kwds: - if self.colormap is not None: - warnings.warn( - "'color' and 'colormap' cannot be used " - "simultaneously. Using 'color'", - stacklevel=find_stack_level(), - ) - self.color = self.kwds.pop("color") + def _validate_color_args(self, color, colormap): + if color is lib.no_default: + return None - if isinstance(self.color, dict): - valid_keys = ["boxes", "whiskers", "medians", "caps"] - for key in self.color: - if key not in valid_keys: - raise ValueError( - f"color dict contains invalid key '{key}'. " - f"The key must be either {valid_keys}" - ) - else: - self.color = None + if colormap is not None: + warnings.warn( + "'color' and 'colormap' cannot be used " + "simultaneously. Using 'color'", + stacklevel=find_stack_level(), + ) + + if isinstance(color, dict): + valid_keys = ["boxes", "whiskers", "medians", "caps"] + for key in color: + if key not in valid_keys: + raise ValueError( + f"color dict contains invalid key '{key}'. " + f"The key must be either {valid_keys}" + ) + return color @cache_readonly def _color_attrs(self): @@ -182,16 +183,8 @@ def maybe_color_bp(self, bp) -> None: medians = self.color or self._medians_c caps = self.color or self._caps_c - # GH 30346, when users specifying those arguments explicitly, our defaults - # for these four kwargs should be overridden; if not, use Pandas settings - if not self.kwds.get("boxprops"): - setp(bp["boxes"], color=boxes, alpha=1) - if not self.kwds.get("whiskerprops"): - setp(bp["whiskers"], color=whiskers, alpha=1) - if not self.kwds.get("medianprops"): - setp(bp["medians"], color=medians, alpha=1) - if not self.kwds.get("capprops"): - setp(bp["caps"], color=caps, alpha=1) + color_tup = (boxes, whiskers, medians, caps) + maybe_color_bp(bp, color_tup=color_tup, **self.kwds) def _make_plot(self, fig: Figure) -> None: if self.subplots: @@ -276,6 +269,19 @@ def result(self): return self._return_obj +def maybe_color_bp(bp, color_tup, **kwds) -> None: + # GH#30346, when users specifying those arguments explicitly, our defaults + # for these four kwargs should be overridden; if not, use Pandas settings + if not kwds.get("boxprops"): + setp(bp["boxes"], color=color_tup[0], alpha=1) + if not kwds.get("whiskerprops"): + setp(bp["whiskers"], color=color_tup[1], alpha=1) + if not kwds.get("medianprops"): + setp(bp["medians"], color=color_tup[2], alpha=1) + if not kwds.get("capprops"): + setp(bp["caps"], color=color_tup[3], alpha=1) + + def _grouped_plot_by_column( plotf, data, @@ -389,18 +395,6 @@ def _get_colors(): return result - def maybe_color_bp(bp, **kwds) -> None: - # GH 30346, when users specifying those arguments explicitly, our defaults - # for these four kwargs should be overridden; if not, use Pandas settings - if not kwds.get("boxprops"): - setp(bp["boxes"], color=colors[0], alpha=1) - if not kwds.get("whiskerprops"): - setp(bp["whiskers"], color=colors[1], alpha=1) - if not kwds.get("medianprops"): - setp(bp["medians"], color=colors[2], alpha=1) - if not kwds.get("capprops"): - setp(bp["caps"], color=colors[3], alpha=1) - def plot_group(keys, values, ax: Axes, **kwds): # GH 45465: xlabel/ylabel need to be popped out before plotting happens xlabel, ylabel = kwds.pop("xlabel", None), kwds.pop("ylabel", None) @@ -419,7 +413,7 @@ def plot_group(keys, values, ax: Axes, **kwds): _set_ticklabels( ax=ax, labels=keys, is_vertical=kwds.get("vert", True), rotation=rot ) - maybe_color_bp(bp, **kwds) + maybe_color_bp(bp, color_tup=colors, **kwds) # Return axes in multiplot case, maybe revisit later # 985 if return_type == "dict": diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index d4796b335003a..463204d33c92c 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -271,7 +271,10 @@ def __init__( self.kwds = kwds - self._validate_color_args() + color = kwds.pop("color", lib.no_default) + self.color = self._validate_color_args(color, self.colormap) + assert "color" not in self.kwds + self.data = self._ensure_frame(self.data) @final @@ -396,34 +399,31 @@ def _validate_subplots_kwarg( out.append((idx_loc,)) return out - def _validate_color_args(self): - if ( - "color" in self.kwds - and self.nseries == 1 - and self.kwds["color"] is not None - and not is_list_like(self.kwds["color"]) - ): + def _validate_color_args(self, color, colormap): + if color is lib.no_default: + # It was not provided by the user + if "colors" in self.kwds and colormap is not None: + warnings.warn( + "'color' and 'colormap' cannot be used simultaneously. " + "Using 'color'", + stacklevel=find_stack_level(), + ) + return None + if self.nseries == 1 and color is not None and not is_list_like(color): # support series.plot(color='green') - self.kwds["color"] = [self.kwds["color"]] + color = [color] - if ( - "color" in self.kwds - and isinstance(self.kwds["color"], tuple) - and self.nseries == 1 - and len(self.kwds["color"]) in (3, 4) - ): + if isinstance(color, tuple) and self.nseries == 1 and len(color) in (3, 4): # support RGB and RGBA tuples in series plot - self.kwds["color"] = [self.kwds["color"]] + color = [color] - if ( - "color" in self.kwds or "colors" in self.kwds - ) and self.colormap is not None: + if colormap is not None: warnings.warn( "'color' and 'colormap' cannot be used simultaneously. Using 'color'", stacklevel=find_stack_level(), ) - if "color" in self.kwds and self.style is not None: + if self.style is not None: if is_list_like(self.style): styles = self.style else: @@ -436,6 +436,7 @@ def _validate_color_args(self): "'color' keyword argument. Please use one or the " "other or pass 'style' without a color symbol" ) + return color @final @staticmethod @@ -1058,11 +1059,14 @@ def _get_colors( ): if num_colors is None: num_colors = self.nseries - + if color_kwds == "color": + color = self.color + else: + color = self.kwds.get(color_kwds) return get_standard_colors( num_colors=num_colors, colormap=self.colormap, - color=self.kwds.get(color_kwds), + color=color, ) # TODO: tighter typing for first return? @@ -1302,7 +1306,7 @@ def _make_plot(self, fig: Figure): self.data[c].dtype, CategoricalDtype ) - color = self.kwds.pop("color", None) + color = self.color c_values = self._get_c_values(color, color_by_categorical, c_is_column) norm, cmap = self._get_norm_and_cmap(c_values, color_by_categorical) cb = self._get_colorbar(c_values, c_is_column) @@ -1487,6 +1491,8 @@ def _make_plot(self, fig: Figure) -> None: for i, (label, y) in enumerate(it): ax = self._get_ax(i) kwds = self.kwds.copy() + if self.color is not None: + kwds["color"] = self.color style, kwds = self._apply_style_colors( colors, kwds, @@ -1998,8 +2004,9 @@ def __init__(self, data, kind=None, **kwargs) -> None: self.logx = False self.loglog = False - def _validate_color_args(self) -> None: - pass + def _validate_color_args(self, color, colormap) -> None: + # TODO: warn if color is passed and ignored? + return None def _make_plot(self, fig: Figure) -> None: colors = self._get_colors(num_colors=len(self.data), color_kwds="colors") diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index cdb0c4da203e9..f5b415f12f37d 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -140,6 +140,8 @@ def _make_plot(self, fig: Figure) -> None: ax = self._get_ax(i) kwds = self.kwds.copy() + if self.color is not None: + kwds["color"] = self.color label = pprint_thing(label) label = self._mark_right_label(label, index=i)
- [ ] 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/55904
2023-11-09T23:59:52Z
2023-11-13T19:07:23Z
2023-11-13T19:07:23Z
2023-11-13T21:01:19Z
BLD: Bump our C standard to 11
diff --git a/meson.build b/meson.build index 68018046c081f..0bc04c59d8716 100644 --- a/meson.build +++ b/meson.build @@ -7,7 +7,7 @@ project( meson_version: '>=1.2.1', default_options: [ 'buildtype=release', - 'c_std=c99' + 'c_std=c11' ] )
We're getting Cython compilation errors with Cython < 3 and C99, on the wheel builders. NOTE: Cython 3 seems to handle this OK. Let's see if C11 fixes it since we can't go directly to Cython 3 yet. - [ ] 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/55902
2023-11-09T22:36:26Z
2023-11-11T00:08:29Z
2023-11-11T00:08:29Z
2023-11-11T13:01:26Z
Backport PR #55894 on 2.1.x: Parquet/Feather IO: disable PyExtensionType autoload
diff --git a/doc/source/whatsnew/v2.1.3.rst b/doc/source/whatsnew/v2.1.3.rst index 264cd440907fd..531559c259b44 100644 --- a/doc/source/whatsnew/v2.1.3.rst +++ b/doc/source/whatsnew/v2.1.3.rst @@ -22,7 +22,8 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Bug in :meth:`DatetimeIndex.diff` raising ``TypeError`` (:issue:`55080`) -- +- Bug in :meth:`Index.isin` raising for Arrow backed string and ``None`` value (:issue:`55821`) +- Fix :func:`read_parquet` and :func:`read_feather` for `CVE-2023-47248 <https://www.cve.org/CVERecord?id=CVE-2023-47248>`__ (:issue:`55894`) .. --------------------------------------------------------------------------- .. _whatsnew_213.other: diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 684e9dccdc0f9..6896945344b24 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -31,6 +31,7 @@ pa_version_under11p0, pa_version_under13p0, pa_version_under14p0, + pa_version_under14p1, ) if TYPE_CHECKING: @@ -188,6 +189,7 @@ def get_bz2_file() -> type[pandas.compat.compressors.BZ2File]: "pa_version_under11p0", "pa_version_under13p0", "pa_version_under14p0", + "pa_version_under14p1", "IS64", "ISMUSL", "PY310", diff --git a/pandas/compat/pyarrow.py b/pandas/compat/pyarrow.py index 12f58be109d98..96501b47e07f6 100644 --- a/pandas/compat/pyarrow.py +++ b/pandas/compat/pyarrow.py @@ -16,6 +16,7 @@ pa_version_under12p0 = _palv < Version("12.0.0") pa_version_under13p0 = _palv < Version("13.0.0") pa_version_under14p0 = _palv < Version("14.0.0") + pa_version_under14p1 = _palv < Version("14.0.1") except ImportError: pa_version_under7p0 = True pa_version_under8p0 = True @@ -25,3 +26,4 @@ pa_version_under12p0 = True pa_version_under13p0 = True pa_version_under14p0 = True + pa_version_under14p1 = True diff --git a/pandas/core/arrays/arrow/extension_types.py b/pandas/core/arrays/arrow/extension_types.py index 3249c1c829546..36d536bf86847 100644 --- a/pandas/core/arrays/arrow/extension_types.py +++ b/pandas/core/arrays/arrow/extension_types.py @@ -5,6 +5,8 @@ import pyarrow +from pandas.compat import pa_version_under14p1 + from pandas.core.dtypes.dtypes import ( IntervalDtype, PeriodDtype, @@ -112,3 +114,61 @@ def to_pandas_dtype(self): # register the type with a dummy instance _interval_type = ArrowIntervalType(pyarrow.int64(), "left") pyarrow.register_extension_type(_interval_type) + + +_ERROR_MSG = """\ +Disallowed deserialization of 'arrow.py_extension_type': +storage_type = {storage_type} +serialized = {serialized} +pickle disassembly:\n{pickle_disassembly} + +Reading of untrusted Parquet or Feather files with a PyExtensionType column +allows arbitrary code execution. +If you trust this file, you can enable reading the extension type by one of: + +- upgrading to pyarrow >= 14.0.1, and call `pa.PyExtensionType.set_auto_load(True)` +- install pyarrow-hotfix (`pip install pyarrow-hotfix`) and disable it by running + `import pyarrow_hotfix; pyarrow_hotfix.uninstall()` + +We strongly recommend updating your Parquet/Feather files to use extension types +derived from `pyarrow.ExtensionType` instead, and register this type explicitly. +""" + + +def patch_pyarrow(): + # starting from pyarrow 14.0.1, it has its own mechanism + if not pa_version_under14p1: + return + + # if https://github.com/pitrou/pyarrow-hotfix was installed and enabled + if getattr(pyarrow, "_hotfix_installed", False): + return + + class ForbiddenExtensionType(pyarrow.ExtensionType): + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + import io + import pickletools + + out = io.StringIO() + pickletools.dis(serialized, out) + raise RuntimeError( + _ERROR_MSG.format( + storage_type=storage_type, + serialized=serialized, + pickle_disassembly=out.getvalue(), + ) + ) + + pyarrow.unregister_extension_type("arrow.py_extension_type") + pyarrow.register_extension_type( + ForbiddenExtensionType(pyarrow.null(), "arrow.py_extension_type") + ) + + pyarrow._hotfix_installed = True + + +patch_pyarrow() diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index c463f6e4d2759..b018b5720d126 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -117,6 +117,9 @@ def read_feather( import_optional_dependency("pyarrow") from pyarrow import feather + # import utils to register the pyarrow extension types + import pandas.core.arrays.arrow.extension_types # pyright: ignore[reportUnusedImport] # noqa: F401,E501 + check_dtype_backend(dtype_backend) with get_handle(
Backport PR #55894: Parquet/Feather IO: disable PyExtensionType autoload
https://api.github.com/repos/pandas-dev/pandas/pulls/55900
2023-11-09T21:35:24Z
2023-11-09T23:24:32Z
2023-11-09T23:24:32Z
2023-11-10T07:40:20Z
provide right index name if the index is not unique
diff --git a/pandas/core/ops/common.py b/pandas/core/ops/common.py index 559977bacf881..689ddf5003abb 100644 --- a/pandas/core/ops/common.py +++ b/pandas/core/ops/common.py @@ -93,11 +93,7 @@ def get_op_result_name(left, right): name : object Usually a string """ - if isinstance(right, (ABCSeries, ABCIndex)): - name = _maybe_match_name(left, right) - else: - name = left.name - return name + return left.name def _maybe_match_name(a, b):
- [x] closes #55815 - [ ] [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/55899
2023-11-09T21:21:47Z
2023-12-09T19:37:24Z
null
2023-12-09T19:37:25Z
PERF: array_strptime
diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 381575c439dcc..a99d63f821dcd 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -47,7 +47,10 @@ from numpy cimport ( ) from pandas._libs.missing cimport checknull_with_nat_and_na -from pandas._libs.tslibs.conversion cimport get_datetime64_nanos +from pandas._libs.tslibs.conversion cimport ( + get_datetime64_nanos, + parse_pydatetime, +) from pandas._libs.tslibs.dtypes cimport ( get_supported_reso, npy_unit_to_abbrev, @@ -55,6 +58,7 @@ from pandas._libs.tslibs.dtypes cimport ( ) from pandas._libs.tslibs.nattype cimport ( NPY_NAT, + c_NaT as NaT, c_nat_strings as nat_strings, ) from pandas._libs.tslibs.np_datetime cimport ( @@ -65,7 +69,6 @@ from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, npy_datetimestruct_to_datetime, pydate_to_dt64, - pydatetime_to_dt64, string_to_dts, ) @@ -82,6 +85,8 @@ from pandas._libs.util cimport ( from pandas._libs.tslibs.timestamps import Timestamp +from pandas._libs.tslibs.tzconversion cimport tz_localize_to_utc_single + cnp.import_array() @@ -314,11 +319,13 @@ def array_strptime( Py_ssize_t i, n = len(values) npy_datetimestruct dts int64_t[::1] iresult - object[::1] result_timezone object val, tz + bint seen_datetime_offset = False bint is_raise = errors=="raise" bint is_ignore = errors=="ignore" bint is_coerce = errors=="coerce" + bint is_same_offsets + set out_tzoffset_vals = set() tzinfo tz_out = None bint iso_format = format_is_iso(fmt) NPY_DATETIMEUNIT out_bestunit, item_reso @@ -338,7 +345,6 @@ def array_strptime( abbrev = npy_unit_to_abbrev(creso) result = np.empty(n, dtype=f"M8[{abbrev}]") iresult = result.view("i8") - result_timezone = np.empty(n, dtype="object") dts.us = dts.ps = dts.as = 0 @@ -361,16 +367,10 @@ def array_strptime( if infer_reso: creso = state.creso tz_out = state.process_datetime(val, tz_out, utc) - if isinstance(val, _Timestamp): - val = (<_Timestamp>val)._as_creso(creso) - iresult[i] = val.tz_localize(None)._value - else: - iresult[i] = pydatetime_to_dt64( - val.replace(tzinfo=None), &dts, reso=creso - ) - result_timezone[i] = val.tzinfo + iresult[i] = parse_pydatetime(val, &dts, state.creso) continue elif PyDate_Check(val): + state.found_other = True item_reso = NPY_DATETIMEUNIT.NPY_FR_s state.update_creso(item_reso) if infer_reso: @@ -378,6 +378,7 @@ def array_strptime( iresult[i] = pydate_to_dt64(val, &dts, reso=creso) continue elif cnp.is_datetime64_object(val): + state.found_other = True item_reso = get_supported_reso(get_datetime64_unit(val)) state.update_creso(item_reso) if infer_reso: @@ -418,13 +419,17 @@ def array_strptime( f"Out of bounds {attrname} timestamp: {val}" ) from err if out_local == 1: - # Store the out_tzoffset in seconds - # since we store the total_seconds of - # dateutil.tz.tzoffset objects + nsecs = out_tzoffset * 60 + out_tzoffset_vals.add(nsecs) + seen_datetime_offset = True tz = timezone(timedelta(minutes=out_tzoffset)) - result_timezone[i] = tz - out_local = 0 - out_tzoffset = 0 + value = tz_localize_to_utc_single( + value, tz, ambiguous="raise", nonexistent=None, creso=creso + ) + else: + tz = None + out_tzoffset_vals.add("naive") + state.found_naive_str = True iresult[i] = value continue @@ -450,6 +455,7 @@ def array_strptime( state.update_creso(item_reso) if infer_reso: creso = state.creso + try: iresult[i] = npy_datetimestruct_to_datetime(creso, &dts) except OverflowError as err: @@ -457,7 +463,26 @@ def array_strptime( raise OutOfBoundsDatetime( f"Out of bounds {attrname} timestamp: {val}" ) from err - result_timezone[i] = tz + + if tz is not None: + ival = iresult[i] + iresult[i] = tz_localize_to_utc_single( + ival, tz, ambiguous="raise", nonexistent=None, creso=creso + ) + nsecs = (ival - iresult[i]) + if creso == NPY_FR_ns: + nsecs = nsecs // 10**9 + elif creso == NPY_DATETIMEUNIT.NPY_FR_us: + nsecs = nsecs // 10**6 + elif creso == NPY_DATETIMEUNIT.NPY_FR_ms: + nsecs = nsecs // 10**3 + + out_tzoffset_vals.add(nsecs) + seen_datetime_offset = True + else: + state.found_naive_str = True + tz = None + out_tzoffset_vals.add("naive") except (ValueError, OutOfBoundsDatetime) as ex: ex.args = ( @@ -474,7 +499,37 @@ def array_strptime( continue elif is_raise: raise - return values, [] + return values, None + + if seen_datetime_offset and not utc: + is_same_offsets = len(out_tzoffset_vals) == 1 + if not is_same_offsets or (state.found_naive or state.found_other): + result2 = _array_strptime_object_fallback( + values, fmt=fmt, exact=exact, errors=errors, utc=utc + ) + return result2, None + elif tz_out is not None: + # GH#55693 + tz_offset = out_tzoffset_vals.pop() + tz_out2 = timezone(timedelta(seconds=tz_offset)) + if not tz_compare(tz_out, tz_out2): + # e.g. test_to_datetime_mixed_offsets_with_utc_false_deprecated + result2 = _array_strptime_object_fallback( + values, fmt=fmt, exact=exact, errors=errors, utc=utc + ) + return result2, None + # e.g. test_guess_datetime_format_with_parseable_formats + else: + # e.g. test_to_datetime_iso8601_with_timezone_valid + tz_offset = out_tzoffset_vals.pop() + tz_out = timezone(timedelta(seconds=tz_offset)) + elif not utc: + if tz_out and (state.found_other or state.found_naive_str): + # found_other indicates a tz-naive int, float, dt64, or date + result2 = _array_strptime_object_fallback( + values, fmt=fmt, exact=exact, errors=errors, utc=utc + ) + return result2, None if infer_reso: if state.creso_ever_changed: @@ -488,7 +543,6 @@ def array_strptime( utc=utc, creso=state.creso, ) - elif state.creso == NPY_DATETIMEUNIT.NPY_FR_GENERIC: # i.e. we never encountered anything non-NaT, default to "s". This # ensures that insert and concat-like operations with NaT @@ -499,7 +553,7 @@ def array_strptime( # a second pass. abbrev = npy_unit_to_abbrev(state.creso) result = iresult.base.view(f"M8[{abbrev}]") - return result, result_timezone.base + return result, tz_out cdef tzinfo _parse_with_format( @@ -737,6 +791,157 @@ cdef tzinfo _parse_with_format( return tz +def _array_strptime_object_fallback( + ndarray[object] values, + str fmt, + bint exact=True, + errors="raise", + bint utc=False, +): + + cdef: + Py_ssize_t i, n = len(values) + npy_datetimestruct dts + int64_t iresult + object val + tzinfo tz + bint is_raise = errors=="raise" + bint is_ignore = errors=="ignore" + bint is_coerce = errors=="coerce" + bint iso_format = format_is_iso(fmt) + NPY_DATETIMEUNIT creso, out_bestunit, item_reso + int out_local = 0, out_tzoffset = 0 + bint string_to_dts_succeeded = 0 + + assert is_raise or is_ignore or is_coerce + + item_reso = NPY_DATETIMEUNIT.NPY_FR_GENERIC + format_regex, locale_time = _get_format_regex(fmt) + + result = np.empty(n, dtype=object) + + dts.us = dts.ps = dts.as = 0 + + for i in range(n): + val = values[i] + try: + if isinstance(val, str): + if len(val) == 0 or val in nat_strings: + result[i] = NaT + continue + elif checknull_with_nat_and_na(val): + result[i] = NaT + continue + elif PyDateTime_Check(val): + result[i] = Timestamp(val) + continue + elif PyDate_Check(val): + result[i] = Timestamp(val) + continue + elif cnp.is_datetime64_object(val): + result[i] = Timestamp(val) + continue + elif ( + (is_integer_object(val) or is_float_object(val)) + and (val != val or val == NPY_NAT) + ): + result[i] = NaT + continue + else: + val = str(val) + + if fmt == "ISO8601": + string_to_dts_succeeded = not string_to_dts( + val, &dts, &out_bestunit, &out_local, + &out_tzoffset, False, None, False + ) + elif iso_format: + string_to_dts_succeeded = not string_to_dts( + val, &dts, &out_bestunit, &out_local, + &out_tzoffset, False, fmt, exact + ) + if string_to_dts_succeeded: + # No error reported by string_to_dts, pick back up + # where we left off + creso = get_supported_reso(out_bestunit) + try: + value = npy_datetimestruct_to_datetime(creso, &dts) + except OverflowError as err: + raise OutOfBoundsDatetime( + f"Out of bounds nanosecond timestamp: {val}" + ) from err + if out_local == 1: + tz = timezone(timedelta(minutes=out_tzoffset)) + value = tz_localize_to_utc_single( + value, tz, ambiguous="raise", nonexistent=None, creso=creso + ) + else: + tz = None + ts = Timestamp._from_value_and_reso(value, creso, tz) + result[i] = ts + continue + + if parse_today_now(val, &iresult, utc, NPY_FR_ns): + result[i] = Timestamp(val) + continue + + # Some ISO formats can't be parsed by string_to_dts + # For example, 6-digit YYYYMD. So, if there's an error, and a format + # was specified, then try the string-matching code below. If the format + # specified was 'ISO8601', then we need to error, because + # only string_to_dts handles mixed ISO8601 formats. + if not string_to_dts_succeeded and fmt == "ISO8601": + raise ValueError(f"Time data {val} is not ISO8601 format") + + tz = _parse_with_format( + val, fmt, exact, format_regex, locale_time, &dts, &item_reso + ) + try: + iresult = npy_datetimestruct_to_datetime(item_reso, &dts) + except OverflowError as err: + raise OutOfBoundsDatetime( + f"Out of bounds nanosecond timestamp: {val}" + ) from err + if tz is not None: + iresult = tz_localize_to_utc_single( + iresult, tz, ambiguous="raise", nonexistent=None, creso=item_reso + ) + ts = Timestamp._from_value_and_reso(iresult, item_reso, tz) + result[i] = ts + + except (ValueError, OutOfBoundsDatetime) as ex: + ex.args = ( + f"{str(ex)}, at position {i}. You might want to try:\n" + " - passing `format` if your strings have a consistent format;\n" + " - passing `format='ISO8601'` if your strings are " + "all ISO8601 but not necessarily in exactly the same format;\n" + " - passing `format='mixed'`, and the format will be " + "inferred for each element individually. " + "You might want to use `dayfirst` alongside this.", + ) + if is_coerce: + result[i] = NaT + continue + elif is_raise: + raise + return values + + import warnings + + from pandas.util._exceptions import find_stack_level + warnings.warn( + "In a future version of pandas, parsing datetimes with mixed time " + "zones will raise an error unless `utc=True`. Please specify `utc=True` " + "to opt in to the new behaviour and silence this warning. " + "To create a `Series` with mixed offsets and `object` dtype, " + "please use `apply` and `datetime.datetime.strptime`", + FutureWarning, + stacklevel=find_stack_level(), + ) + + return result + + class TimeRE(_TimeRE): """ Handle conversion from format directives to regexes. diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 863fb414a75f2..2947f818165c5 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -312,56 +312,6 @@ def _convert_and_box_cache( return _box_as_indexlike(result._values, utc=False, name=name) -def _return_parsed_timezone_results( - result: np.ndarray, timezones, utc: bool, name: str -) -> Index: - """ - Return results from array_strptime if a %z or %Z directive was passed. - - Parameters - ---------- - result : ndarray[int64] - int64 date representations of the dates - timezones : ndarray - pytz timezone objects - utc : bool - Whether to convert/localize timestamps to UTC. - name : string, default None - Name for a DatetimeIndex - - Returns - ------- - tz_result : Index-like of parsed dates with timezone - """ - tz_results = np.empty(len(result), dtype=object) - non_na_timezones = set() - for zone in unique(timezones): - # GH#50168 looping over unique timezones is faster than - # operating pointwise. - mask = timezones == zone - dta = DatetimeArray(result[mask]).tz_localize(zone) - if utc: - if dta.tzinfo is None: - dta = dta.tz_localize("utc") - else: - dta = dta.tz_convert("utc") - else: - if not dta.isna().all(): - non_na_timezones.add(zone) - tz_results[mask] = dta - if len(non_na_timezones) > 1: - warnings.warn( - "In a future version of pandas, parsing datetimes with mixed time " - "zones will raise an error unless `utc=True`. Please specify `utc=True` " - "to opt in to the new behaviour and silence this warning. " - "To create a `Series` with mixed offsets and `object` dtype, " - "please use `apply` and `datetime.datetime.strptime`", - FutureWarning, - stacklevel=find_stack_level(), - ) - return Index(tz_results, name=name) - - def _convert_listlike_datetimes( arg, format: str | None, @@ -514,11 +464,17 @@ def _array_strptime_with_fallback( """ Call array_strptime, with fallback behavior depending on 'errors'. """ - result, timezones = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc) - if any(tz is not None for tz in timezones): - return _return_parsed_timezone_results(result, timezones, utc, name) - - return _box_as_indexlike(result, utc=utc, name=name) + result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc) + if tz_out is not None: + dtype = DatetimeTZDtype(tz=tz_out) + dta = DatetimeArray._simple_new(result, dtype=dtype) + if utc: + dta = dta.tz_convert("UTC") + return Index(dta, name=name) + elif result.dtype != object and utc: + res = Index(result, dtype="M8[ns, UTC]", name=name) + return res + return Index(result, dtype=result.dtype, name=name) def _to_datetime_with_unit(arg, unit, name, utc: bool, errors: str) -> Index:
array_strptime is conceptually similar to array_to_datetime but stores local values instead of UTC values, then we pass the result through a localization pass that goes through object dtype. The upside of doing it the current way is that array_strptime does not need a fallback path for when mixed tzs/awareness is detected. The downside is everything else. This changes array_strptime to store UTC values and follow the same pattern used by array_to_datetime (hopefully we can move toward sharing more code, though some of that will have to wait until deprecations are enforced in 3.0). It introduces a fallback _array_strptime_object_fallback that mirrors _array_to_datetime_object that we'll be able to get rid of once the mixed-tz deprecation is enforced in 3.0. ``` vals = np.array(["2016-01-01 02:03:04.567"] * 10**4, dtype=object) vals2 = np.array([pd.Timestamp(x) for x in vals], dtype=object) vals3 = np.array([x + "-01:00" for x in vals], dtype=object) fmt = "%Y-%m-%d %H:%M:%S.%f" %timeit pd.to_datetime(vals, format=fmt, cache=False) 2.39 ms ± 28.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # <- main 2.11 ms ± 45.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # <- PR %timeit pd.to_datetime(vals2, format=fmt, cache=False) 23.9 ms ± 680 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- main 10.7 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) # <- PR %timeit pd.to_datetime(vals3, format=fmt+"%z", cache=False) 99.7 ms ± 1.43 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- main 63.1 ms ± 1.65 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) # <- PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/55898
2023-11-09T20:30:36Z
2023-11-26T05:03:19Z
2023-11-26T05:03:19Z
2023-11-26T16:42:45Z
Backport PR #55427 on branch 2.1.x (DOC: Remove outdated docs about NumPy's broadcasting)
diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst index 2e299da5e5794..d3c9d83b943ce 100644 --- a/doc/source/user_guide/basics.rst +++ b/doc/source/user_guide/basics.rst @@ -408,20 +408,6 @@ raise a ValueError: pd.Series(['foo', 'bar', 'baz']) == pd.Series(['foo']) -Note that this is different from the NumPy behavior where a comparison can -be broadcast: - -.. ipython:: python - - np.array([1, 2, 3]) == np.array([2]) - -or it can return False if broadcasting can not be done: - -.. ipython:: python - :okwarning: - - np.array([1, 2, 3]) == np.array([1, 2]) - Combining overlapping data sets ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Backport PR #55427: DOC: Remove outdated docs about NumPy's broadcasting
https://api.github.com/repos/pandas-dev/pandas/pulls/55896
2023-11-09T16:32:13Z
2023-11-09T17:02:19Z
2023-11-09T17:02:19Z
2023-11-09T17:02:19Z
DEPR: kind keyword in resample
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index f155fb27d0de5..7f81f040e92d4 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -395,6 +395,7 @@ Other Deprecations - Deprecated strings ``T``, ``S``, ``L``, ``U``, and ``N`` denoting frequencies in :class:`Minute`, :class:`Second`, :class:`Milli`, :class:`Micro`, :class:`Nano` (:issue:`52536`) - Deprecated the ``errors="ignore"`` option in :func:`to_datetime`, :func:`to_timedelta`, and :func:`to_numeric`; explicitly catch exceptions instead (:issue:`54467`) - Deprecated the ``fastpath`` keyword in the :class:`Series` constructor (:issue:`20110`) +- Deprecated the ``kind`` keyword in :meth:`Series.resample` and :meth:`DataFrame.resample`, explicitly cast the object's ``index`` instead (:issue:`55895`) - Deprecated the ``ordinal`` keyword in :class:`PeriodIndex`, use :meth:`PeriodIndex.from_ordinals` instead (:issue:`55960`) - Deprecated the extension test classes ``BaseNoReduceTests``, ``BaseBooleanReduceTests``, and ``BaseNumericReduceTests``, use ``BaseReduceTests`` instead (:issue:`54663`) - Deprecated the option ``mode.data_manager`` and the ``ArrayManager``; only the ``BlockManager`` will be available in future versions (:issue:`55043`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0d95d197815d3..c4b333c8a22ca 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9217,7 +9217,7 @@ def resample( closed: Literal["right", "left"] | None = None, label: Literal["right", "left"] | None = None, convention: Literal["start", "end", "s", "e"] = "start", - kind: Literal["timestamp", "period"] | None = None, + kind: Literal["timestamp", "period"] | None | lib.NoDefault = lib.no_default, on: Level | None = None, level: Level | None = None, origin: str | TimestampConvertibleTypes = "start_day", @@ -9259,6 +9259,9 @@ def resample( `DateTimeIndex` or 'period' to convert it to a `PeriodIndex`. By default the input representation is retained. + .. deprecated:: 2.2.0 + Convert index to desired type explicitly instead. + on : str, optional For a DataFrame, column to use instead of index for resampling. Column must be datetime-like. @@ -9616,6 +9619,18 @@ def resample( else: axis = 0 + if kind is not lib.no_default: + # GH#55895 + warnings.warn( + f"The 'kind' keyword in {type(self).__name__}.resample is " + "deprecated and will be removed in a future version. " + "Explicitly cast the index to the desired type instead", + FutureWarning, + stacklevel=find_stack_level(), + ) + else: + kind = None + return get_resampler( cast("Series | DataFrame", self), freq=rule, diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 22cd0621fd4c4..bf56f054812e0 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -767,7 +767,9 @@ def test_to_excel_timedelta(self, path): tm.assert_frame_equal(expected, recons) def test_to_excel_periodindex(self, path): - xp = tm.makeTimeDataFrame()[:5].resample("ME", kind="period").mean() + # xp has a PeriodIndex + df = tm.makeTimeDataFrame()[:5] + xp = df.resample("ME").mean().to_period("M") xp.to_excel(path, sheet_name="sht1") diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 98cd7d7ae22f6..865c02798c648 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -455,7 +455,9 @@ def test_resample_frame_basic_M_A(freq, unit): def test_resample_frame_basic_kind(freq, unit): df = tm.makeTimeDataFrame() df.index = df.index.as_unit(unit) - df.resample(freq, kind="period").mean() + msg = "The 'kind' keyword in DataFrame.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + df.resample(freq, kind="period").mean() def test_resample_upsample(unit): @@ -687,7 +689,9 @@ def test_resample_timestamp_to_period( ts = simple_date_range_series("1/1/1990", "1/1/2000") ts.index = ts.index.as_unit(unit) - result = ts.resample(freq, kind="period").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample(freq, kind="period").mean() expected = ts.resample(freq).mean() expected.index = period_range(**expected_kwargs) tm.assert_series_equal(result, expected) @@ -1020,7 +1024,9 @@ def test_resample_to_period_monthly_buglet(unit): rng = date_range("1/1/2000", "12/31/2000").as_unit(unit) ts = Series(np.random.default_rng(2).standard_normal(len(rng)), index=rng) - result = ts.resample("ME", kind="period").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample("ME", kind="period").mean() exp_index = period_range("Jan-2000", "Dec-2000", freq="M") tm.assert_index_equal(result.index, exp_index) @@ -1139,14 +1145,18 @@ def test_resample_anchored_intraday(unit): df = DataFrame(rng.month, index=rng) result = df.resample("ME").mean() - expected = df.resample("ME", kind="period").mean().to_timestamp(how="end") + msg = "The 'kind' keyword in DataFrame.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.resample("ME", kind="period").mean().to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index = expected.index.as_unit(unit)._with_freq("infer") assert expected.index.freq == "ME" tm.assert_frame_equal(result, expected) result = df.resample("ME", closed="left").mean() - exp = df.shift(1, freq="D").resample("ME", kind="period").mean() + msg = "The 'kind' keyword in DataFrame.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + exp = df.shift(1, freq="D").resample("ME", kind="period").mean() exp = exp.to_timestamp(how="end") exp.index = exp.index + Timedelta(1, "ns") - Timedelta(1, "D") @@ -1160,7 +1170,9 @@ def test_resample_anchored_intraday2(unit): df = DataFrame(rng.month, index=rng) result = df.resample("QE").mean() - expected = df.resample("QE", kind="period").mean().to_timestamp(how="end") + msg = "The 'kind' keyword in DataFrame.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = df.resample("QE", kind="period").mean().to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index._data.freq = "QE" expected.index._freq = lib.no_default @@ -1168,7 +1180,11 @@ def test_resample_anchored_intraday2(unit): tm.assert_frame_equal(result, expected) result = df.resample("QE", closed="left").mean() - expected = df.shift(1, freq="D").resample("QE", kind="period", closed="left").mean() + msg = "The 'kind' keyword in DataFrame.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + expected = ( + df.shift(1, freq="D").resample("QE", kind="period", closed="left").mean() + ) expected = expected.to_timestamp(how="end") expected.index += Timedelta(1, "ns") - Timedelta(1, "D") expected.index._data.freq = "QE" @@ -1225,7 +1241,9 @@ def test_corner_cases_date(simple_date_range_series, unit): # resample to periods ts = simple_date_range_series("2000-04-28", "2000-04-30 11:00", freq="h") ts.index = ts.index.as_unit(unit) - result = ts.resample("ME", kind="period").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample("ME", kind="period").mean() assert len(result) == 1 assert result.index[0] == Period("2000-04", freq="M") diff --git a/pandas/tests/resample/test_period_index.py b/pandas/tests/resample/test_period_index.py index 5d233a940de2f..b66c2ff02a35d 100644 --- a/pandas/tests/resample/test_period_index.py +++ b/pandas/tests/resample/test_period_index.py @@ -77,7 +77,9 @@ def test_asfreq(self, series_and_frame, freq, kind): end = (obj.index[-1] + obj.index.freq).to_timestamp(how="start") new_index = date_range(start=start, end=end, freq=freq, inclusive="left") expected = obj.to_timestamp().reindex(new_index).to_period(freq) - result = obj.resample(freq, kind=kind).asfreq() + msg = "The 'kind' keyword in (Series|DataFrame).resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = obj.resample(freq, kind=kind).asfreq() tm.assert_almost_equal(result, expected) def test_asfreq_fill_value(self, series): @@ -90,7 +92,9 @@ def test_asfreq_fill_value(self, series): freq="1h", ) expected = s.to_timestamp().reindex(new_index, fill_value=4.0) - result = s.resample("1h", kind="timestamp").asfreq(fill_value=4.0) + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.resample("1h", kind="timestamp").asfreq(fill_value=4.0) tm.assert_series_equal(result, expected) frame = s.to_frame("value") @@ -100,7 +104,9 @@ def test_asfreq_fill_value(self, series): freq="1h", ) expected = frame.to_timestamp().reindex(new_index, fill_value=3.0) - result = frame.resample("1h", kind="timestamp").asfreq(fill_value=3.0) + msg = "The 'kind' keyword in DataFrame.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = frame.resample("1h", kind="timestamp").asfreq(fill_value=3.0) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("freq", ["h", "12h", "2D", "W"]) @@ -119,8 +125,10 @@ def test_selection(self, index, freq, kind, kwargs): r"not currently supported, use \.set_index\(\.\.\.\) to " "explicitly set index" ) + depr_msg = "The 'kind' keyword in DataFrame.resample is deprecated" with pytest.raises(NotImplementedError, match=msg): - df.resample(freq, kind=kind, **kwargs) + with tm.assert_produces_warning(FutureWarning, match=depr_msg): + df.resample(freq, kind=kind, **kwargs) @pytest.mark.parametrize("month", MONTHS) @pytest.mark.parametrize("meth", ["ffill", "bfill"]) @@ -250,9 +258,12 @@ def test_resample_basic(self): name="idx", ) expected = Series([34.5, 79.5], index=index) - result = s.to_period().resample("min", kind="period").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.to_period().resample("min", kind="period").mean() tm.assert_series_equal(result, expected) - result2 = s.resample("min", kind="period").mean() + with tm.assert_produces_warning(FutureWarning, match=msg): + result2 = s.resample("min", kind="period").mean() tm.assert_series_equal(result2, expected) @pytest.mark.parametrize( @@ -307,7 +318,9 @@ def test_with_local_timezone(self, tz): series = Series(1, index=index) series = series.tz_convert(local_timezone) - result = series.resample("D", kind="period").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = series.resample("D", kind="period").mean() # Create the expected series # Index is moved back a day with the timezone conversion from UTC to @@ -406,7 +419,9 @@ def test_weekly_upsample(self, day, target, convention, simple_period_range_seri def test_resample_to_timestamps(self, simple_period_range_series): ts = simple_period_range_series("1/1/1990", "12/31/1995", freq="M") - result = ts.resample("Y-DEC", kind="timestamp").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample("Y-DEC", kind="timestamp").mean() expected = ts.to_timestamp(how="start").resample("YE-DEC").mean() tm.assert_series_equal(result, expected) @@ -466,7 +481,9 @@ def test_resample_5minute(self, freq, kind): expected = ts.to_timestamp().resample(freq).mean() if kind != "timestamp": expected = expected.to_period(freq) - result = ts.resample(freq, kind=kind).mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ts.resample(freq, kind=kind).mean() tm.assert_series_equal(result, expected) def test_upsample_daily_business_daily(self, simple_period_range_series): @@ -540,7 +557,9 @@ def test_resample_tz_localized2(self): tm.assert_series_equal(result, expected) # for good measure - result = s.resample("D", kind="period").mean() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.resample("D", kind="period").mean() ex_index = period_range("2001-09-20", periods=1, freq="D") expected = Series([1.5], index=ex_index) tm.assert_series_equal(result, expected) @@ -785,7 +804,9 @@ def test_upsampling_ohlc(self, freq, period_mult, kind): # of the last original period, so extend accordingly: new_index = period_range(start="2000", freq=freq, periods=period_mult * len(pi)) expected = expected.reindex(new_index) - result = s.resample(freq, kind=kind).ohlc() + msg = "The 'kind' keyword in Series.resample is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = s.resample(freq, kind=kind).ohlc() tm.assert_frame_equal(result, expected) @pytest.mark.parametrize(
- [x] closes #55946 (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/55895
2023-11-09T15:15:53Z
2023-11-30T17:25:06Z
2023-11-30T17:25:06Z
2023-11-30T21:59:35Z
Parquet/Feather IO: disable PyExtensionType autoload
diff --git a/doc/source/whatsnew/v2.1.3.rst b/doc/source/whatsnew/v2.1.3.rst index 31ab01f171b4a..ac70623bdcd11 100644 --- a/doc/source/whatsnew/v2.1.3.rst +++ b/doc/source/whatsnew/v2.1.3.rst @@ -23,6 +23,7 @@ Bug fixes ~~~~~~~~~ - Bug in :meth:`DatetimeIndex.diff` raising ``TypeError`` (:issue:`55080`) - Bug in :meth:`Index.isin` raising for Arrow backed string and ``None`` value (:issue:`55821`) +- Fix :func:`read_parquet` and :func:`read_feather` for `CVE-2023-47248 <https://www.cve.org/CVERecord?id=CVE-2023-47248>`__ (:issue:`55894`) .. --------------------------------------------------------------------------- .. _whatsnew_213.other: diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index ea8cfb7cc144b..738442fab8c70 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -29,6 +29,7 @@ pa_version_under11p0, pa_version_under13p0, pa_version_under14p0, + pa_version_under14p1, ) if TYPE_CHECKING: @@ -184,6 +185,7 @@ def get_bz2_file() -> type[pandas.compat.compressors.BZ2File]: "pa_version_under11p0", "pa_version_under13p0", "pa_version_under14p0", + "pa_version_under14p1", "IS64", "ISMUSL", "PY310", diff --git a/pandas/compat/pyarrow.py b/pandas/compat/pyarrow.py index d125904ba83f8..8dcb2669aa663 100644 --- a/pandas/compat/pyarrow.py +++ b/pandas/compat/pyarrow.py @@ -13,9 +13,11 @@ pa_version_under12p0 = _palv < Version("12.0.0") pa_version_under13p0 = _palv < Version("13.0.0") pa_version_under14p0 = _palv < Version("14.0.0") + pa_version_under14p1 = _palv < Version("14.0.1") except ImportError: pa_version_under10p1 = True pa_version_under11p0 = True pa_version_under12p0 = True pa_version_under13p0 = True pa_version_under14p0 = True + pa_version_under14p1 = True diff --git a/pandas/core/arrays/arrow/extension_types.py b/pandas/core/arrays/arrow/extension_types.py index 7814a77a1cdc5..72bfd6f2212f8 100644 --- a/pandas/core/arrays/arrow/extension_types.py +++ b/pandas/core/arrays/arrow/extension_types.py @@ -5,6 +5,8 @@ import pyarrow +from pandas.compat import pa_version_under14p1 + from pandas.core.dtypes.dtypes import ( IntervalDtype, PeriodDtype, @@ -112,3 +114,61 @@ def to_pandas_dtype(self) -> IntervalDtype: # register the type with a dummy instance _interval_type = ArrowIntervalType(pyarrow.int64(), "left") pyarrow.register_extension_type(_interval_type) + + +_ERROR_MSG = """\ +Disallowed deserialization of 'arrow.py_extension_type': +storage_type = {storage_type} +serialized = {serialized} +pickle disassembly:\n{pickle_disassembly} + +Reading of untrusted Parquet or Feather files with a PyExtensionType column +allows arbitrary code execution. +If you trust this file, you can enable reading the extension type by one of: + +- upgrading to pyarrow >= 14.0.1, and call `pa.PyExtensionType.set_auto_load(True)` +- install pyarrow-hotfix (`pip install pyarrow-hotfix`) and disable it by running + `import pyarrow_hotfix; pyarrow_hotfix.uninstall()` + +We strongly recommend updating your Parquet/Feather files to use extension types +derived from `pyarrow.ExtensionType` instead, and register this type explicitly. +""" + + +def patch_pyarrow(): + # starting from pyarrow 14.0.1, it has its own mechanism + if not pa_version_under14p1: + return + + # if https://github.com/pitrou/pyarrow-hotfix was installed and enabled + if getattr(pyarrow, "_hotfix_installed", False): + return + + class ForbiddenExtensionType(pyarrow.ExtensionType): + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + import io + import pickletools + + out = io.StringIO() + pickletools.dis(serialized, out) + raise RuntimeError( + _ERROR_MSG.format( + storage_type=storage_type, + serialized=serialized, + pickle_disassembly=out.getvalue(), + ) + ) + + pyarrow.unregister_extension_type("arrow.py_extension_type") + pyarrow.register_extension_type( + ForbiddenExtensionType(pyarrow.null(), "arrow.py_extension_type") + ) + + pyarrow._hotfix_installed = True + + +patch_pyarrow() diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index c463f6e4d2759..c451cd6c139ed 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -117,6 +117,9 @@ def read_feather( import_optional_dependency("pyarrow") from pyarrow import feather + # import utils to register the pyarrow extension types + import pandas.core.arrays.arrow.extension_types # pyright: ignore[reportUnusedImport] # noqa: F401 + check_dtype_backend(dtype_backend) with get_handle(
Similar to https://github.com/apache/arrow/pull/38608, but doing it on our side as well for people that use latest pandas with older pyarrow. (using a similar approach as https://github.com/pitrou/pyarrow-hotfix, without adding a required dependency on that package)
https://api.github.com/repos/pandas-dev/pandas/pulls/55894
2023-11-09T14:33:21Z
2023-11-09T21:22:05Z
2023-11-09T21:22:05Z
2023-11-09T21:36:05Z
Backport PR #55764 on branch 2.1.x (REGR: fix return class in _constructor_from_mgr for simple subclasses)
diff --git a/doc/source/whatsnew/v2.1.3.rst b/doc/source/whatsnew/v2.1.3.rst index 3b1cd1c152baa..264cd440907fd 100644 --- a/doc/source/whatsnew/v2.1.3.rst +++ b/doc/source/whatsnew/v2.1.3.rst @@ -13,7 +13,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Fixed infinite recursion from operations that return a new object on some DataFrame subclasses (:issue:`55763`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c109070ce461d..605cf49856e16 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -641,7 +641,7 @@ def _constructor(self) -> Callable[..., DataFrame]: def _constructor_from_mgr(self, mgr, axes): if self._constructor is DataFrame: # we are pandas.DataFrame (or a subclass that doesn't override _constructor) - return self._from_mgr(mgr, axes=axes) + return DataFrame._from_mgr(mgr, axes=axes) else: assert axes is mgr.axes return self._constructor(mgr) diff --git a/pandas/core/series.py b/pandas/core/series.py index 8ad049e173507..7b22d89bfe22d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -581,7 +581,7 @@ def _constructor(self) -> Callable[..., Series]: def _constructor_from_mgr(self, mgr, axes): if self._constructor is Series: # we are pandas.Series (or a subclass that doesn't override _constructor) - ser = self._from_mgr(mgr, axes=axes) + ser = Series._from_mgr(mgr, axes=axes) ser._name = None # caller is responsible for setting real name return ser else: diff --git a/pandas/tests/frame/test_subclass.py b/pandas/tests/frame/test_subclass.py index 8e657f197ca1e..ef78ae62cb4d6 100644 --- a/pandas/tests/frame/test_subclass.py +++ b/pandas/tests/frame/test_subclass.py @@ -771,3 +771,44 @@ def test_constructor_with_metadata(): ) subset = df[["A", "B"]] assert isinstance(subset, MySubclassWithMetadata) + + +class SimpleDataFrameSubClass(DataFrame): + """A subclass of DataFrame that does not define a constructor.""" + + +class SimpleSeriesSubClass(Series): + """A subclass of Series that does not define a constructor.""" + + +class TestSubclassWithoutConstructor: + def test_copy_df(self): + expected = DataFrame({"a": [1, 2, 3]}) + result = SimpleDataFrameSubClass(expected).copy() + + assert ( + type(result) is DataFrame + ) # assert_frame_equal only checks isinstance(lhs, type(rhs)) + tm.assert_frame_equal(result, expected) + + def test_copy_series(self): + expected = Series([1, 2, 3]) + result = SimpleSeriesSubClass(expected).copy() + + tm.assert_series_equal(result, expected) + + def test_series_to_frame(self): + orig = Series([1, 2, 3]) + expected = orig.to_frame() + result = SimpleSeriesSubClass(orig).to_frame() + + assert ( + type(result) is DataFrame + ) # assert_frame_equal only checks isinstance(lhs, type(rhs)) + tm.assert_frame_equal(result, expected) + + def test_groupby(self): + df = SimpleDataFrameSubClass(DataFrame({"a": [1, 2, 3]})) + + for _, v in df.groupby("a"): + assert type(v) is DataFrame
Backport PR #55764: REGR: fix return class in _constructor_from_mgr for simple subclasses
https://api.github.com/repos/pandas-dev/pandas/pulls/55892
2023-11-09T07:56:03Z
2023-11-09T20:23:57Z
2023-11-09T20:23:57Z
2023-11-09T20:23:57Z
ENH: warn when silently ignoring log keywords in PiePlot
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index d4796b335003a..3bb6af92578b2 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -159,6 +159,14 @@ def __init__( layout=None, include_bool: bool = False, column: IndexLabel | None = None, + *, + logx: bool | None | Literal["sym"] = False, + logy: bool | None | Literal["sym"] = False, + loglog: bool | None | Literal["sym"] = False, + mark_right: bool = True, + stacked: bool = False, + label: Hashable | None = None, + style=None, **kwds, ) -> None: import matplotlib.pyplot as plt @@ -230,13 +238,13 @@ def __init__( self.legend_handles: list[Artist] = [] self.legend_labels: list[Hashable] = [] - self.logx = kwds.pop("logx", False) - self.logy = kwds.pop("logy", False) - self.loglog = kwds.pop("loglog", False) - self.label = kwds.pop("label", None) - self.style = kwds.pop("style", None) - self.mark_right = kwds.pop("mark_right", True) - self.stacked = kwds.pop("stacked", False) + self.logx = type(self)._validate_log_kwd("logx", logx) + self.logy = type(self)._validate_log_kwd("logy", logy) + self.loglog = type(self)._validate_log_kwd("loglog", loglog) + self.label = label + self.style = style + self.mark_right = mark_right + self.stacked = stacked # ax may be an Axes object or (if self.subplots) an ndarray of # Axes objects @@ -289,6 +297,22 @@ def _validate_sharex(sharex: bool | None, ax, by) -> bool: raise TypeError("sharex must be a bool or None") return bool(sharex) + @classmethod + def _validate_log_kwd( + cls, + kwd: str, + value: bool | None | Literal["sym"], + ) -> bool | None | Literal["sym"]: + if ( + value is None + or isinstance(value, bool) + or (isinstance(value, str) and value == "sym") + ): + return value + raise ValueError( + f"keyword '{kwd}' should be bool, None, or 'sym', not '{value}'" + ) + @final @staticmethod def _validate_subplots_kwarg( @@ -555,14 +579,6 @@ def _axes_and_fig(self) -> tuple[Sequence[Axes], Figure]: axes = flatten_axes(axes) - valid_log = {False, True, "sym", None} - input_log = {self.logx, self.logy, self.loglog} - if input_log - valid_log: - invalid_log = next(iter(input_log - valid_log)) - raise ValueError( - f"Boolean, None and 'sym' are valid options, '{invalid_log}' is given." - ) - if self.logx is True or self.loglog is True: [a.set_xscale("log") for a in axes] elif self.logx == "sym" or self.loglog == "sym": @@ -1330,7 +1346,12 @@ def _make_plot(self, fig: Figure): cbar.ax.set_yticklabels(self.data[c].cat.categories) if label is not None: - self._append_legend_handles_labels(scatter, label) + self._append_legend_handles_labels( + # error: Argument 2 to "_append_legend_handles_labels" of + # "MPLPlot" has incompatible type "Hashable"; expected "str" + scatter, + label, # type: ignore[arg-type] # pyright: ignore[reportGeneralTypeIssues] + ) errors_x = self._get_errorbars(label=x, index=0, yerr=False) errors_y = self._get_errorbars(label=y, index=0, xerr=False) @@ -1993,10 +2014,21 @@ def __init__(self, data, kind=None, **kwargs) -> None: if (data < 0).any().any(): raise ValueError(f"{self._kind} plot doesn't allow negative values") MPLPlot.__init__(self, data, kind=kind, **kwargs) - self.grid = False - self.logy = False - self.logx = False - self.loglog = False + + @classmethod + def _validate_log_kwd( + cls, + kwd: str, + value: bool | None | Literal["sym"], + ) -> bool | None | Literal["sym"]: + super()._validate_log_kwd(kwd=kwd, value=value) + if value is not False: + warnings.warn( + f"PiePlot ignores the '{kwd}' keyword", + UserWarning, + stacklevel=find_stack_level(), + ) + return False def _validate_color_args(self) -> None: pass diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index f002d7a6e66ab..f1fc1174416ca 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -333,10 +333,14 @@ def test_invalid_logscale(self, input_param): # GH: 24867 df = DataFrame({"a": np.arange(100)}, index=np.arange(100)) - msg = "Boolean, None and 'sym' are valid options, 'sm' is given." + msg = f"keyword '{input_param}' should be bool, None, or 'sym', not 'sm'" with pytest.raises(ValueError, match=msg): df.plot(**{input_param: "sm"}) + msg = f"PiePlot ignores the '{input_param}' keyword" + with tm.assert_produces_warning(UserWarning, match=msg): + df.plot.pie(subplots=True, **{input_param: True}) + def test_xcompat(self): df = tm.makeTimeDataFrame() ax = df.plot(x_compat=True)
- [ ] 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/55890
2023-11-09T02:36:59Z
2023-11-13T21:01:35Z
2023-11-13T21:01:35Z
2023-11-13T21:02:28Z
REF: Mess with data less outside of MPLPlot.__init__
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 05cf151992c96..d59220a1f97f8 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -89,11 +89,15 @@ from pandas._typing import ( IndexLabel, + NDFrameT, PlottingOrientation, npt, ) - from pandas import Series + from pandas import ( + PeriodIndex, + Series, + ) def _color_in_style(style: str) -> bool: @@ -161,8 +165,6 @@ def __init__( ) -> None: import matplotlib.pyplot as plt - self.data = data - # if users assign an empty list or tuple, raise `ValueError` # similar to current `df.box` and `df.hist` APIs. if by in ([], ()): @@ -193,9 +195,11 @@ def __init__( self.kind = kind - self.subplots = self._validate_subplots_kwarg(subplots) + self.subplots = type(self)._validate_subplots_kwarg( + subplots, data, kind=self._kind + ) - self.sharex = self._validate_sharex(sharex, ax, by) + self.sharex = type(self)._validate_sharex(sharex, ax, by) self.sharey = sharey self.figsize = figsize self.layout = layout @@ -245,10 +249,11 @@ def __init__( # parse errorbar input if given xerr = kwds.pop("xerr", None) yerr = kwds.pop("yerr", None) - self.errors = { - kw: self._parse_errorbars(kw, err) - for kw, err in zip(["xerr", "yerr"], [xerr, yerr]) - } + nseries = self._get_nseries(data) + xerr, data = type(self)._parse_errorbars("xerr", xerr, data, nseries) + yerr, data = type(self)._parse_errorbars("yerr", yerr, data, nseries) + self.errors = {"xerr": xerr, "yerr": yerr} + self.data = data if not isinstance(secondary_y, (bool, tuple, list, np.ndarray, ABCIndex)): secondary_y = [secondary_y] @@ -271,7 +276,8 @@ def __init__( self._validate_color_args() @final - def _validate_sharex(self, sharex: bool | None, ax, by) -> bool: + @staticmethod + def _validate_sharex(sharex: bool | None, ax, by) -> bool: if sharex is None: # if by is defined, subplots are used and sharex should be False if ax is None and by is None: # pylint: disable=simplifiable-if-statement @@ -285,8 +291,9 @@ def _validate_sharex(self, sharex: bool | None, ax, by) -> bool: return bool(sharex) @final + @staticmethod def _validate_subplots_kwarg( - self, subplots: bool | Sequence[Sequence[str]] + subplots: bool | Sequence[Sequence[str]], data: Series | DataFrame, kind: str ) -> bool | list[tuple[int, ...]]: """ Validate the subplots parameter @@ -323,18 +330,18 @@ def _validate_subplots_kwarg( "area", "pie", ) - if self._kind not in supported_kinds: + if kind not in supported_kinds: raise ValueError( "When subplots is an iterable, kind must be " - f"one of {', '.join(supported_kinds)}. Got {self._kind}." + f"one of {', '.join(supported_kinds)}. Got {kind}." ) - if isinstance(self.data, ABCSeries): + if isinstance(data, ABCSeries): raise NotImplementedError( "An iterable subplots for a Series is not supported." ) - columns = self.data.columns + columns = data.columns if isinstance(columns, ABCMultiIndex): raise NotImplementedError( "An iterable subplots for a DataFrame with a MultiIndex column " @@ -442,18 +449,22 @@ def _iter_data( # typing. yield col, np.asarray(values.values) - @property - def nseries(self) -> int: + def _get_nseries(self, data: Series | DataFrame) -> 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: + if data.ndim == 1: return 1 elif self.by is not None and self._kind == "hist": return len(self._grouped) elif self.by is not None and self._kind == "box": return len(self.columns) else: - return self.data.shape[1] + return data.shape[1] + + @final + @property + def nseries(self) -> int: + return self._get_nseries(self.data) @final def draw(self) -> None: @@ -880,10 +891,12 @@ def _get_xticks(self, convert_period: bool = False): index = self.data.index is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time") + x: list[int] | np.ndarray if self.use_index: if convert_period and isinstance(index, ABCPeriodIndex): self.data = self.data.reindex(index=index.sort_values()) - x = self.data.index.to_timestamp()._mpl_repr() + index = cast("PeriodIndex", self.data.index) + x = index.to_timestamp()._mpl_repr() elif is_any_real_numeric_dtype(index.dtype): # Matplotlib supports numeric values or datetime objects as # xaxis values. Taking LBYL approach here, by the time @@ -1050,8 +1063,12 @@ def _get_colors( color=self.kwds.get(color_kwds), ) + # TODO: tighter typing for first return? @final - def _parse_errorbars(self, label: str, err): + @staticmethod + def _parse_errorbars( + label: str, err, data: NDFrameT, nseries: int + ) -> tuple[Any, NDFrameT]: """ Look for error keyword arguments and return the actual errorbar data or return the error DataFrame/dict @@ -1071,7 +1088,7 @@ def _parse_errorbars(self, label: str, err): should be in a ``Mx2xN`` array. """ if err is None: - return None + return None, data def match_labels(data, e): e = e.reindex(data.index) @@ -1079,7 +1096,7 @@ def match_labels(data, e): # key-matched DataFrame if isinstance(err, ABCDataFrame): - err = match_labels(self.data, err) + err = match_labels(data, err) # key-matched dict elif isinstance(err, dict): pass @@ -1087,16 +1104,16 @@ def match_labels(data, e): # Series of error values elif isinstance(err, ABCSeries): # broadcast error series across data - err = match_labels(self.data, err) + err = match_labels(data, err) err = np.atleast_2d(err) - err = np.tile(err, (self.nseries, 1)) + err = np.tile(err, (nseries, 1)) # errors are a column in the dataframe elif isinstance(err, str): - evalues = self.data[err].values - self.data = self.data[self.data.columns.drop(err)] + evalues = data[err].values + data = data[data.columns.drop(err)] err = np.atleast_2d(evalues) - err = np.tile(err, (self.nseries, 1)) + err = np.tile(err, (nseries, 1)) elif is_list_like(err): if is_iterator(err): @@ -1108,40 +1125,40 @@ def match_labels(data, e): err_shape = err.shape # asymmetrical error bars - if isinstance(self.data, ABCSeries) and err_shape[0] == 2: + if isinstance(data, ABCSeries) and err_shape[0] == 2: err = np.expand_dims(err, 0) err_shape = err.shape - if err_shape[2] != len(self.data): + if err_shape[2] != len(data): raise ValueError( "Asymmetrical error bars should be provided " - f"with the shape (2, {len(self.data)})" + f"with the shape (2, {len(data)})" ) - elif isinstance(self.data, ABCDataFrame) and err.ndim == 3: + elif isinstance(data, ABCDataFrame) and err.ndim == 3: if ( - (err_shape[0] != self.nseries) + (err_shape[0] != nseries) or (err_shape[1] != 2) - or (err_shape[2] != len(self.data)) + or (err_shape[2] != len(data)) ): raise ValueError( "Asymmetrical error bars should be provided " - f"with the shape ({self.nseries}, 2, {len(self.data)})" + f"with the shape ({nseries}, 2, {len(data)})" ) # broadcast errors to each data series if len(err) == 1: - err = np.tile(err, (self.nseries, 1)) + err = np.tile(err, (nseries, 1)) elif is_number(err): err = np.tile( [err], # pyright: ignore[reportGeneralTypeIssues] - (self.nseries, len(self.data)), + (nseries, len(data)), ) else: msg = f"No valid {label} detected" raise ValueError(msg) - return err + return err, data # pyright: ignore[reportGeneralTypeIssues] @final def _get_errorbars( @@ -1215,8 +1232,7 @@ def __init__(self, data, x, y, **kwargs) -> None: self.y = y @final - @property - def nseries(self) -> int: + def _get_nseries(self, data: Series | DataFrame) -> int: return 1 @final diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index ed93dc740e1b4..e42914a9802dd 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -45,7 +45,10 @@ from pandas._typing import PlottingOrientation - from pandas import DataFrame + from pandas import ( + DataFrame, + Series, + ) class HistPlot(LinePlot): @@ -87,7 +90,7 @@ def _adjust_bins(self, bins: int | np.ndarray | list[np.ndarray]): bins = self._calculate_bins(self.data, bins) return bins - def _calculate_bins(self, data: DataFrame, bins) -> np.ndarray: + def _calculate_bins(self, data: Series | DataFrame, bins) -> np.ndarray: """Calculate bins given data""" nd_values = data.infer_objects(copy=False)._get_numeric_data() values = np.ravel(nd_values)
- [ ] 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/55889
2023-11-09T00:32:33Z
2023-11-09T18:20:06Z
2023-11-09T18:20:06Z
2023-11-09T19:38:34Z
REF: Ensure MPLPlot.data is a DataFrame after __init__
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 37ebd940f3646..fa45e6b21fbef 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -204,7 +204,10 @@ def _make_plot(self, fig: Figure) -> None: else self.data ) - for i, (label, y) in enumerate(self._iter_data(data=data)): + # error: Argument "data" to "_iter_data" of "MPLPlot" has + # incompatible type "object"; expected "DataFrame | + # dict[Hashable, Series | DataFrame]" + for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type] ax = self._get_ax(i) kwds = self.kwds.copy() @@ -216,9 +219,9 @@ def _make_plot(self, fig: Figure) -> None: # When `by` is assigned, the ticklabels will become unique grouped # values, instead of label which is used as subtitle in this case. - ticklabels = [ - pprint_thing(col) for col in self.data.columns.levels[0] - ] + # error: "Index" has no attribute "levels"; maybe "nlevels"? + levels = self.data.columns.levels # type: ignore[attr-defined] + ticklabels = [pprint_thing(col) for col in levels[0]] else: ticklabels = [pprint_thing(label)] diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index d59220a1f97f8..76cb4ee101dc5 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -132,6 +132,8 @@ def _kind(self) -> str: def orientation(self) -> str | None: return None + data: DataFrame + def __init__( self, data, @@ -274,6 +276,7 @@ def __init__( self.kwds = kwds self._validate_color_args() + self.data = self._ensure_frame(self.data) @final @staticmethod @@ -623,9 +626,7 @@ def _convert_to_ndarray(data): return data @final - def _compute_plot_data(self): - data = self.data - + def _ensure_frame(self, data) -> DataFrame: if isinstance(data, ABCSeries): label = self.label if label is None and data.name is None: @@ -638,6 +639,11 @@ def _compute_plot_data(self): elif self._kind in ("hist", "box"): cols = self.columns if self.by is None else self.columns + self.by data = data.loc[:, cols] + return data + + @final + def _compute_plot_data(self): + data = self.data # GH15079 reconstruct data if by is defined if self.by is not None: @@ -891,6 +897,7 @@ def _get_xticks(self, convert_period: bool = False): index = self.data.index is_datetype = index.inferred_type in ("datetime", "date", "datetime64", "time") + # TODO: be stricter about x? x: list[int] | np.ndarray if self.use_index: if convert_period and isinstance(index, ABCPeriodIndex): @@ -1439,7 +1446,10 @@ def _make_plot(self, fig: Figure) -> None: # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") plotf = self._plot # type: ignore[assignment] - it = self._iter_data(data=self.data) + # error: Incompatible types in assignment (expression has type + # "Iterator[tuple[Hashable, ndarray[Any, Any]]]", variable has + # type "Iterable[tuple[Hashable, Series]]") + it = self._iter_data(data=self.data) # type: ignore[assignment] stacking_id = self._get_stacking_id() is_errorbar = com.any_not_none(*self.errors.values()) @@ -1452,7 +1462,9 @@ def _make_plot(self, fig: Figure) -> None: colors, kwds, i, - label, # pyright: ignore[reportGeneralTypeIssues] + # error: Argument 4 to "_apply_style_colors" of "MPLPlot" has + # incompatible type "Hashable"; expected "str" + label, # type: ignore[arg-type] # pyright: ignore[reportGeneralTypeIssues] ) errors = self._get_errorbars(label=label, index=i) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index e42914a9802dd..cdb0c4da203e9 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -134,7 +134,9 @@ def _make_plot(self, fig: Figure) -> None: else self.data ) - for i, (label, y) in enumerate(self._iter_data(data=data)): + # error: Argument "data" to "_iter_data" of "MPLPlot" has incompatible + # type "object"; expected "DataFrame | dict[Hashable, Series | DataFrame]" + for i, (label, y) in enumerate(self._iter_data(data=data)): # type: ignore[arg-type] ax = self._get_ax(i) kwds = self.kwds.copy()
- [ ] 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/55888
2023-11-09T00:20:59Z
2023-11-10T22:54:01Z
2023-11-10T22:54:01Z
2023-11-11T00:44:07Z
TYP: plotting
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 3b60e95b9dceb..a017787f2dc2d 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -37,11 +37,15 @@ from pandas._typing import IndexLabel - from pandas import DataFrame + from pandas import ( + DataFrame, + Series, + ) + from pandas.core.groupby.generic import DataFrameGroupBy def hist_series( - self, + self: Series, by=None, ax=None, grid: bool = True, @@ -512,7 +516,7 @@ def boxplot( @Substitution(data="", backend=_backend_doc) @Appender(_boxplot_doc) def boxplot_frame( - self, + self: DataFrame, column=None, by=None, ax=None, @@ -542,7 +546,7 @@ def boxplot_frame( def boxplot_frame_groupby( - grouped, + grouped: DataFrameGroupBy, subplots: bool = True, column=None, fontsize: int | None = None, @@ -843,11 +847,11 @@ class PlotAccessor(PandasObject): _kind_aliases = {"density": "kde"} _all_kinds = _common_kinds + _series_kinds + _dataframe_kinds - def __init__(self, data) -> None: + def __init__(self, data: Series | DataFrame) -> None: self._parent = data @staticmethod - def _get_call_args(backend_name: str, data, args, kwargs): + def _get_call_args(backend_name: str, data: Series | DataFrame, args, kwargs): """ This function makes calls to this accessor `__call__` method compatible with the previous `SeriesPlotMethods.__call__` and diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index e6481aab50f6e..37ebd940f3646 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -93,17 +93,18 @@ def __init__(self, data, return_type: str = "axes", **kwargs) -> None: # error: Signature of "_plot" incompatible with supertype "MPLPlot" @classmethod def _plot( # type: ignore[override] - cls, ax: Axes, y, column_num=None, return_type: str = "axes", **kwds + cls, ax: Axes, y: np.ndarray, column_num=None, return_type: str = "axes", **kwds ): + ys: np.ndarray | list[np.ndarray] if y.ndim == 2: - y = [remove_na_arraylike(v) for v in y] + ys = [remove_na_arraylike(v) for v in y] # Boxplot fails with empty arrays, so need to add a NaN # if any cols are empty # GH 8181 - y = [v if v.size > 0 else np.array([np.nan]) for v in y] + ys = [v if v.size > 0 else np.array([np.nan]) for v in ys] else: - y = remove_na_arraylike(y) - bp = ax.boxplot(y, **kwds) + ys = remove_na_arraylike(y) + bp = ax.boxplot(ys, **kwds) if return_type == "dict": return bp, bp @@ -240,8 +241,7 @@ def _make_plot(self, fig: Figure) -> None: self.maybe_color_bp(bp) self._return_obj = ret - labels = [left for left, _ in self._iter_data()] - labels = [pprint_thing(left) for left in labels] + labels = [pprint_thing(left) for left in self.data.columns] if not self.use_index: labels = [pprint_thing(key) for key in range(len(labels))] _set_ticklabels( @@ -251,7 +251,7 @@ def _make_plot(self, fig: Figure) -> None: def _make_legend(self) -> None: pass - def _post_plot_logic(self, ax, data) -> None: + def _post_plot_logic(self, ax: Axes, data) -> None: # GH 45465: make sure that the boxplot doesn't ignore xlabel/ylabel if self.xlabel: ax.set_xlabel(pprint_thing(self.xlabel)) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index b67a8186c8c2b..c2b0f43d83e60 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -7,6 +7,7 @@ from collections.abc import ( Hashable, Iterable, + Iterator, Sequence, ) from typing import ( @@ -431,17 +432,15 @@ def _validate_color_args(self): ) @final - def _iter_data(self, data=None, keep_index: bool = False, fillna=None): - if data is None: - data = self.data - if fillna is not None: - data = data.fillna(fillna) - + @staticmethod + def _iter_data( + data: DataFrame | dict[Hashable, Series | DataFrame] + ) -> Iterator[tuple[Hashable, np.ndarray]]: for col, values in data.items(): - if keep_index is True: - yield col, values - else: - yield col, values.values + # This was originally written to use values.values before EAs + # were implemented; adding np.asarray(...) to keep consistent + # typing. + yield col, np.asarray(values.values) @property def nseries(self) -> int: @@ -480,7 +479,7 @@ def _has_plotted_object(ax: Axes) -> bool: return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0 @final - def _maybe_right_yaxis(self, ax: Axes, axes_num: int): + def _maybe_right_yaxis(self, ax: Axes, axes_num: int) -> Axes: if not self.on_right(axes_num): # secondary axes may be passed via ax kw return self._get_ax_layer(ax) @@ -643,11 +642,7 @@ def _compute_plot_data(self): numeric_data = data.select_dtypes(include=include_type, exclude=exclude_type) - try: - is_empty = numeric_data.columns.empty - except AttributeError: - is_empty = not len(numeric_data) - + is_empty = numeric_data.shape[-1] == 0 # no non-numeric frames or series allowed if is_empty: raise TypeError("no numeric data to plot") @@ -669,7 +664,7 @@ def _add_table(self) -> None: tools.table(ax, data) @final - def _post_plot_logic_common(self, ax, data): + def _post_plot_logic_common(self, ax: Axes, data) -> None: """Common post process for each axes""" if self.orientation == "vertical" or self.orientation is None: self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize) @@ -688,7 +683,7 @@ def _post_plot_logic_common(self, ax, data): raise ValueError @abstractmethod - def _post_plot_logic(self, ax, data) -> None: + def _post_plot_logic(self, ax: Axes, data) -> None: """Post process for each axes. Overridden in child classes""" @final @@ -1042,7 +1037,7 @@ def _get_colors( ) @final - def _parse_errorbars(self, label, err): + def _parse_errorbars(self, label: str, err): """ Look for error keyword arguments and return the actual errorbar data or return the error DataFrame/dict @@ -1123,7 +1118,10 @@ def match_labels(data, e): err = np.tile(err, (self.nseries, 1)) elif is_number(err): - err = np.tile([err], (self.nseries, len(self.data))) + err = np.tile( + [err], # pyright: ignore[reportGeneralTypeIssues] + (self.nseries, len(self.data)), + ) else: msg = f"No valid {label} detected" @@ -1404,14 +1402,14 @@ def _make_plot(self, fig: Figure) -> None: x = data.index # dummy, not used plotf = self._ts_plot - it = self._iter_data(data=data, keep_index=True) + it = data.items() else: x = self._get_xticks(convert_period=True) # error: Incompatible types in assignment (expression has type # "Callable[[Any, Any, Any, Any, Any, Any, KwArg(Any)], Any]", variable has # type "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") plotf = self._plot # type: ignore[assignment] - it = self._iter_data() + it = self._iter_data(data=self.data) stacking_id = self._get_stacking_id() is_errorbar = com.any_not_none(*self.errors.values()) @@ -1420,7 +1418,12 @@ def _make_plot(self, fig: Figure) -> None: for i, (label, y) in enumerate(it): ax = self._get_ax(i) kwds = self.kwds.copy() - style, kwds = self._apply_style_colors(colors, kwds, i, label) + style, kwds = self._apply_style_colors( + colors, + kwds, + i, + label, # pyright: ignore[reportGeneralTypeIssues] + ) errors = self._get_errorbars(label=label, index=i) kwds = dict(kwds, **errors) @@ -1432,7 +1435,7 @@ def _make_plot(self, fig: Figure) -> None: newlines = plotf( ax, x, - y, + y, # pyright: ignore[reportGeneralTypeIssues] style=style, column_num=i, stacking_id=stacking_id, @@ -1451,7 +1454,14 @@ def _make_plot(self, fig: Figure) -> None: # error: Signature of "_plot" incompatible with supertype "MPLPlot" @classmethod def _plot( # type: ignore[override] - cls, ax: Axes, x, y, style=None, column_num=None, stacking_id=None, **kwds + cls, + ax: Axes, + x, + y: np.ndarray, + style=None, + column_num=None, + stacking_id=None, + **kwds, ): # column_num is used to get the target column from plotf in line and # area plots @@ -1478,7 +1488,7 @@ def _ts_plot(self, ax: Axes, x, data: Series, style=None, **kwds): decorate_axes(ax.right_ax, freq, kwds) ax._plot_data.append((data, self._kind, kwds)) - lines = self._plot(ax, data.index, data.values, style=style, **kwds) + lines = self._plot(ax, data.index, np.asarray(data.values), style=style, **kwds) # set date formatter, locators and rescale limits # error: Argument 3 to "format_dateaxis" has incompatible type "Index"; # expected "DatetimeIndex | PeriodIndex" @@ -1506,7 +1516,9 @@ def _initialize_stacker(cls, ax: Axes, stacking_id, n: int) -> None: @final @classmethod - def _get_stacked_values(cls, ax: Axes, stacking_id, values, label): + def _get_stacked_values( + cls, ax: Axes, stacking_id: int | None, values: np.ndarray, label + ) -> np.ndarray: if stacking_id is None: return values if not hasattr(ax, "_stacker_pos_prior"): @@ -1526,7 +1538,7 @@ def _get_stacked_values(cls, ax: Axes, stacking_id, values, label): @final @classmethod - def _update_stacker(cls, ax: Axes, stacking_id, values) -> None: + def _update_stacker(cls, ax: Axes, stacking_id: int | None, values) -> None: if stacking_id is None: return if (values >= 0).all(): @@ -1604,7 +1616,7 @@ def _plot( # type: ignore[override] cls, ax: Axes, x, - y, + y: np.ndarray, style=None, column_num=None, stacking_id=None, @@ -1730,7 +1742,7 @@ def _plot( # type: ignore[override] cls, ax: Axes, x, - y, + y: np.ndarray, w, start: int | npt.NDArray[np.intp] = 0, log: bool = False, @@ -1749,7 +1761,8 @@ def _make_plot(self, fig: Figure) -> None: pos_prior = neg_prior = np.zeros(len(self.data)) K = self.nseries - for i, (label, y) in enumerate(self._iter_data(fillna=0)): + data = self.data.fillna(0) + for i, (label, y) in enumerate(self._iter_data(data=data)): ax = self._get_ax(i) kwds = self.kwds.copy() if self._is_series: @@ -1828,7 +1841,14 @@ def _post_plot_logic(self, ax: Axes, data) -> None: self._decorate_ticks(ax, self._get_index_name(), str_index, s_edge, e_edge) - def _decorate_ticks(self, ax: Axes, name, ticklabels, start_edge, end_edge) -> None: + def _decorate_ticks( + self, + ax: Axes, + name: str | None, + ticklabels: list[str], + start_edge: float, + end_edge: float, + ) -> None: ax.set_xlim((start_edge, end_edge)) if self.xticks is not None: @@ -1862,7 +1882,7 @@ def _plot( # type: ignore[override] cls, ax: Axes, x, - y, + y: np.ndarray, w, start: int | npt.NDArray[np.intp] = 0, log: bool = False, @@ -1873,7 +1893,14 @@ def _plot( # type: ignore[override] def _get_custom_index_name(self): return self.ylabel - def _decorate_ticks(self, ax: Axes, name, ticklabels, start_edge, end_edge) -> None: + def _decorate_ticks( + self, + ax: Axes, + name: str | None, + ticklabels: list[str], + start_edge: float, + end_edge: float, + ) -> None: # horizontal bars ax.set_ylim((start_edge, end_edge)) ax.set_yticks(self.tick_pos) @@ -1907,7 +1934,7 @@ def _make_plot(self, fig: Figure) -> None: colors = self._get_colors(num_colors=len(self.data), color_kwds="colors") self.kwds.setdefault("colors", colors) - for i, (label, y) in enumerate(self._iter_data()): + for i, (label, y) in enumerate(self._iter_data(data=self.data)): ax = self._get_ax(i) if label is not None: label = pprint_thing(label) diff --git a/pandas/plotting/_matplotlib/groupby.py b/pandas/plotting/_matplotlib/groupby.py index 00c3c4114d377..d32741a1d1803 100644 --- a/pandas/plotting/_matplotlib/groupby.py +++ b/pandas/plotting/_matplotlib/groupby.py @@ -16,12 +16,14 @@ from pandas.plotting._matplotlib.misc import unpack_single_str_list if TYPE_CHECKING: + from collections.abc import Hashable + from pandas._typing import IndexLabel def create_iter_data_given_by( data: DataFrame, kind: str = "hist" -) -> dict[str, DataFrame | Series]: +) -> dict[Hashable, DataFrame | Series]: """ Create data for iteration given `by` is assigned or not, and it is only used in both hist and boxplot. @@ -126,9 +128,7 @@ def reconstruct_data_with_by( return data -def reformat_hist_y_given_by( - y: Series | np.ndarray, by: IndexLabel | None -) -> Series | np.ndarray: +def reformat_hist_y_given_by(y: np.ndarray, by: IndexLabel | None) -> np.ndarray: """Internal function to reformat y given `by` is applied or not for hist plot. If by is None, input y is 1-d with NaN removed; and if by is not None, groupby diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index fd0dde40c0ab3..ed93dc740e1b4 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -101,7 +101,7 @@ def _calculate_bins(self, data: DataFrame, bins) -> np.ndarray: def _plot( # type: ignore[override] cls, ax: Axes, - y, + y: np.ndarray, style=None, bottom: int | np.ndarray = 0, column_num: int = 0, @@ -166,7 +166,7 @@ def _make_plot(self, fig: Figure) -> None: self._append_legend_handles_labels(artists[0], label) - def _make_plot_keywords(self, kwds: dict[str, Any], y) -> None: + def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None: """merge BoxPlot/KdePlot properties to passed kwds""" # y is required for KdePlot kwds["bottom"] = self.bottom @@ -225,7 +225,7 @@ def __init__( self.weights = weights @staticmethod - def _get_ind(y, ind): + def _get_ind(y: np.ndarray, ind): if ind is None: # np.nanmax() and np.nanmin() ignores the missing values sample_range = np.nanmax(y) - np.nanmin(y) @@ -248,12 +248,12 @@ def _get_ind(y, ind): def _plot( # type: ignore[override] cls, ax: Axes, - y, + y: np.ndarray, style=None, bw_method=None, ind=None, column_num=None, - stacking_id=None, + stacking_id: int | None = None, **kwds, ): from scipy.stats import gaussian_kde @@ -265,11 +265,11 @@ def _plot( # type: ignore[override] lines = MPLPlot._plot(ax, ind, y, style=style, **kwds) return lines - def _make_plot_keywords(self, kwds: dict[str, Any], y) -> None: + def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None: kwds["bw_method"] = self.bw_method kwds["ind"] = self._get_ind(y, ind=self.ind) - def _post_plot_logic(self, ax, data) -> None: + def _post_plot_logic(self, ax: Axes, data) -> None: ax.set_ylabel("Density") diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index e3e02c69a26db..714ee9d162a25 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -5,6 +5,7 @@ import functools from typing import ( TYPE_CHECKING, + Any, cast, ) import warnings @@ -44,6 +45,8 @@ from matplotlib.axes import Axes + from pandas._typing import NDFrameT + from pandas import ( DataFrame, DatetimeIndex, @@ -56,7 +59,7 @@ # Plotting functions and monkey patches -def maybe_resample(series: Series, ax: Axes, kwargs): +def maybe_resample(series: Series, ax: Axes, kwargs: dict[str, Any]): # resample against axes freq if necessary freq, ax_freq = _get_freq(ax, series) @@ -99,7 +102,7 @@ def _is_sup(f1: str, f2: str) -> bool: ) -def _upsample_others(ax: Axes, freq, kwargs) -> None: +def _upsample_others(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None: legend = ax.get_legend() lines, labels = _replot_ax(ax, freq, kwargs) _replot_ax(ax, freq, kwargs) @@ -122,7 +125,7 @@ def _upsample_others(ax: Axes, freq, kwargs) -> None: ax.legend(lines, labels, loc="best", title=title) -def _replot_ax(ax: Axes, freq, kwargs): +def _replot_ax(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]): data = getattr(ax, "_plot_data", None) # clear current axes and data @@ -152,7 +155,7 @@ def _replot_ax(ax: Axes, freq, kwargs): return lines, labels -def decorate_axes(ax: Axes, freq, kwargs) -> None: +def decorate_axes(ax: Axes, freq: BaseOffset, kwargs: dict[str, Any]) -> None: """Initialize axes for time-series plotting""" if not hasattr(ax, "_plot_data"): ax._plot_data = [] @@ -264,7 +267,7 @@ def _get_index_freq(index: Index) -> BaseOffset | None: return freq -def maybe_convert_index(ax: Axes, data): +def maybe_convert_index(ax: Axes, data: NDFrameT) -> NDFrameT: # tsplot converts automatically, but don't want to convert index # over and over for DataFrames if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)):
started in _iter_data and worked from there
https://api.github.com/repos/pandas-dev/pandas/pulls/55887
2023-11-08T23:46:05Z
2023-11-09T15:43:11Z
2023-11-09T15:43:11Z
2023-11-09T15:43:55Z
REF: make plotting less stateful (6)
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index b67a8186c8c2b..848c6d45c494d 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -13,6 +13,7 @@ TYPE_CHECKING, Any, Literal, + cast, final, ) import warnings @@ -126,8 +127,6 @@ def _kind(self) -> str: def orientation(self) -> str | None: return None - axes: np.ndarray # of Axes objects - def __init__( self, data, @@ -236,10 +235,11 @@ def __init__( self.mark_right = kwds.pop("mark_right", True) self.stacked = kwds.pop("stacked", False) + # ax may be an Axes object or (if self.subplots) an ndarray of + # Axes objects self.ax = ax # TODO: deprecate fig keyword as it is ignored, not passed in tests # as of 2023-11-05 - self.axes = np.array([], dtype=object) # "real" version get set in `generate` # parse errorbar input if given xerr = kwds.pop("xerr", None) @@ -463,7 +463,7 @@ def draw(self) -> None: @final def generate(self) -> None: self._compute_plot_data() - fig = self._setup_subplots() + fig = self.fig self._make_plot(fig) self._add_table() self._make_legend() @@ -509,7 +509,19 @@ def _maybe_right_yaxis(self, ax: Axes, axes_num: int): return new_ax @final - def _setup_subplots(self) -> Figure: + @cache_readonly + def fig(self) -> Figure: + return self._axes_and_fig[1] + + @final + @cache_readonly + # TODO: can we annotate this as both a Sequence[Axes] and ndarray[object]? + def axes(self) -> Sequence[Axes]: + return self._axes_and_fig[0] + + @final + @cache_readonly + def _axes_and_fig(self) -> tuple[Sequence[Axes], Figure]: if self.subplots: naxes = ( self.nseries if isinstance(self.subplots, bool) else len(self.subplots) @@ -552,8 +564,8 @@ def _setup_subplots(self) -> Figure: elif self.logy == "sym" or self.loglog == "sym": [a.set_yscale("symlog") for a in axes] - self.axes = axes - return fig + axes_seq = cast(Sequence["Axes"], axes) + return axes_seq, fig @property def result(self): @@ -562,7 +574,8 @@ def result(self): """ if self.subplots: if self.layout is not None and not is_list_like(self.ax): - return self.axes.reshape(*self.layout) + # error: "Sequence[Any]" has no attribute "reshape" + return self.axes.reshape(*self.layout) # type: ignore[attr-defined] else: return self.axes else: @@ -972,7 +985,8 @@ def _get_ax(self, i: int): i = self._col_idx_to_axis_idx(i) ax = self.axes[i] ax = self._maybe_right_yaxis(ax, i) - self.axes[i] = ax + # error: Unsupported target for indexed assignment ("Sequence[Any]") + self.axes[i] = ax # type: ignore[index] else: ax = self.axes[0] ax = self._maybe_right_yaxis(ax, i)
- [ ] 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/55886
2023-11-08T23:00:56Z
2023-11-09T15:39:22Z
2023-11-09T15:39:22Z
2023-11-09T15:41:55Z
DOC: Update pydata-sphinx-theme to 0.14
diff --git a/doc/source/conf.py b/doc/source/conf.py index e7ce8511b76a1..be6150d4e54ba 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -230,11 +230,13 @@ # further. For a list of options available for each theme, see the # documentation. -switcher_version = version if ".dev" in version: switcher_version = "dev" elif "rc" in version: switcher_version = version.split("rc", maxsplit=1)[0] + " (rc)" +else: + # only keep major.minor version number to match versions.json + switcher_version = ".".join(version.split(".")[:2]) html_theme_options = { "external_links": [], @@ -246,11 +248,13 @@ "plausible_analytics_url": "https://views.scientific-python.org/js/script.js", }, "logo": {"image_dark": "https://pandas.pydata.org/static/img/pandas_white.svg"}, + "navbar_align": "left", "navbar_end": ["version-switcher", "theme-switcher", "navbar-icon-links"], "switcher": { "json_url": "https://pandas.pydata.org/versions.json", "version_match": switcher_version, }, + "show_version_warning_banner": True, "icon_links": [ { "name": "Mastodon", diff --git a/environment.yml b/environment.yml index 5fad8b5031b0a..74317d47e2e53 100644 --- a/environment.yml +++ b/environment.yml @@ -86,7 +86,7 @@ dependencies: - google-auth - natsort # DataFrame.sort_values doctest - numpydoc - - pydata-sphinx-theme=0.13 + - pydata-sphinx-theme=0.14 - pytest-cython # doctest - sphinx - sphinx-design diff --git a/requirements-dev.txt b/requirements-dev.txt index 76f4de2d8f0c4..cbfb6336b2e16 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -61,7 +61,7 @@ gitdb google-auth natsort numpydoc -pydata-sphinx-theme==0.13 +pydata-sphinx-theme==0.14 pytest-cython sphinx sphinx-design diff --git a/web/pandas/versions.json b/web/pandas/versions.json index 43efaf8ebe259..e355005c7c937 100644 --- a/web/pandas/versions.json +++ b/web/pandas/versions.json @@ -7,7 +7,8 @@ { "name": "2.1 (stable)", "version": "2.1", - "url": "https://pandas.pydata.org/docs/" + "url": "https://pandas.pydata.org/docs/", + "preferred": true }, { "name": "2.0",
- [x] closes #55164 (Replace xxxx with the GitHub issue number) <img width="1417" alt="Screen Shot 2023-11-08 at 2 08 28 PM" src="https://github.com/pandas-dev/pandas/assets/10647082/c76e6e39-7caa-4ef8-a96e-2f00539164f3"> Also uses a code block for an numpy operation that will change/fail with a newer version of numpy
https://api.github.com/repos/pandas-dev/pandas/pulls/55885
2023-11-08T22:09:25Z
2023-12-22T15:34:40Z
2023-12-22T15:34:40Z
2023-12-23T00:52:57Z
REF: make BarPlot attributes cache_readonlys
diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 57caa05048a60..ed2bec76f6ebd 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -1663,17 +1663,26 @@ def _kind(self) -> Literal["bar", "barh"]: def orientation(self) -> PlottingOrientation: return "vertical" - def __init__(self, data, **kwargs) -> None: + def __init__( + self, + data, + *, + align="center", + bottom=0, + left=0, + width=0.5, + position=0.5, + log=False, + **kwargs, + ) -> None: # we have to treat a series differently than a # 1-column DataFrame w.r.t. color handling self._is_series = isinstance(data, ABCSeries) - self.bar_width = kwargs.pop("width", 0.5) - pos = kwargs.pop("position", 0.5) - kwargs.setdefault("align", "center") + self.bar_width = width + self._align = align + self._position = position self.tick_pos = np.arange(len(data)) - bottom = kwargs.pop("bottom", 0) - left = kwargs.pop("left", 0) if is_list_like(bottom): bottom = np.array(bottom) if is_list_like(left): @@ -1681,24 +1690,36 @@ def __init__(self, data, **kwargs) -> None: self.bottom = bottom self.left = left - self.log = kwargs.pop("log", False) + self.log = log + MPLPlot.__init__(self, data, **kwargs) + @cache_readonly + def ax_pos(self) -> np.ndarray: + return self.tick_pos - self.tickoffset + + @cache_readonly + def tickoffset(self): if self.stacked or self.subplots: - self.tickoffset = self.bar_width * pos - if kwargs["align"] == "edge": - self.lim_offset = self.bar_width / 2 - else: - self.lim_offset = 0 - elif kwargs["align"] == "edge": + return self.bar_width * self._position + elif self._align == "edge": w = self.bar_width / self.nseries - self.tickoffset = self.bar_width * (pos - 0.5) + w * 0.5 - self.lim_offset = w * 0.5 + return self.bar_width * (self._position - 0.5) + w * 0.5 else: - self.tickoffset = self.bar_width * pos - self.lim_offset = 0 + return self.bar_width * self._position - self.ax_pos = self.tick_pos - self.tickoffset + @cache_readonly + def lim_offset(self): + if self.stacked or self.subplots: + if self._align == "edge": + return self.bar_width / 2 + else: + return 0 + elif self._align == "edge": + w = self.bar_width / self.nseries + return w * 0.5 + else: + return 0 # error: Signature of "_plot" incompatible with supertype "MPLPlot" @classmethod @@ -1749,6 +1770,7 @@ def _make_plot(self, fig: Figure) -> None: start = 1 start = start + self._start_base + kwds["align"] = self._align if self.subplots: w = self.bar_width / 2 rect = self._plot(
part of the "be less stateful" push
https://api.github.com/repos/pandas-dev/pandas/pulls/55878
2023-11-08T02:58:20Z
2023-11-08T19:20:29Z
2023-11-08T19:20:29Z
2023-11-08T20:21:32Z
TYP: plotting, make weights kwd explicit
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 9fd3bd3a01be0..e6481aab50f6e 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -93,7 +93,7 @@ def __init__(self, data, return_type: str = "axes", **kwargs) -> None: # error: Signature of "_plot" incompatible with supertype "MPLPlot" @classmethod def _plot( # type: ignore[override] - cls, ax, y, column_num=None, return_type: str = "axes", **kwds + cls, ax: Axes, y, column_num=None, return_type: str = "axes", **kwds ): if y.ndim == 2: y = [remove_na_arraylike(v) for v in y] diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 57caa05048a60..f2dc671b80b35 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -11,6 +11,7 @@ ) from typing import ( TYPE_CHECKING, + Any, Literal, final, ) @@ -998,7 +999,9 @@ def on_right(self, i: int): return self.data.columns[i] in self.secondary_y @final - def _apply_style_colors(self, colors, kwds, col_num, label: str): + def _apply_style_colors( + self, colors, kwds: dict[str, Any], col_num: int, label: str + ): """ Manage style and color based on column number and its label. Returns tuple of appropriate style and kwds which "color" may be added. diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index 904624fb83b40..fd0dde40c0ab3 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -2,7 +2,9 @@ from typing import ( TYPE_CHECKING, + Any, Literal, + final, ) import numpy as np @@ -58,6 +60,7 @@ def __init__( bottom: int | np.ndarray = 0, *, range=None, + weights=None, **kwargs, ) -> None: if is_list_like(bottom): @@ -65,6 +68,7 @@ def __init__( self.bottom = bottom self._bin_range = range + self.weights = weights self.xlabel = kwargs.get("xlabel") self.ylabel = kwargs.get("ylabel") @@ -96,7 +100,7 @@ def _calculate_bins(self, data: DataFrame, bins) -> np.ndarray: @classmethod def _plot( # type: ignore[override] cls, - ax, + ax: Axes, y, style=None, bottom: int | np.ndarray = 0, @@ -140,7 +144,7 @@ def _make_plot(self, fig: Figure) -> None: if style is not None: kwds["style"] = style - kwds = self._make_plot_keywords(kwds, y) + self._make_plot_keywords(kwds, y) # the bins is multi-dimension array now and each plot need only 1-d and # when by is applied, label should be columns that are grouped @@ -149,21 +153,8 @@ def _make_plot(self, fig: Figure) -> None: kwds["label"] = self.columns kwds.pop("color") - # We allow weights to be a multi-dimensional array, e.g. a (10, 2) array, - # and each sub-array (10,) will be called in each iteration. If users only - # provide 1D array, we assume the same weights is used for all iterations - weights = kwds.get("weights", None) - if weights is not None: - if np.ndim(weights) != 1 and np.shape(weights)[-1] != 1: - try: - weights = weights[:, i] - except IndexError as err: - raise ValueError( - "weights must have the same shape as data, " - "or be a single column" - ) from err - weights = weights[~isna(y)] - kwds["weights"] = weights + if self.weights is not None: + kwds["weights"] = self._get_column_weights(self.weights, i, y) y = reformat_hist_y_given_by(y, self.by) @@ -175,12 +166,29 @@ def _make_plot(self, fig: Figure) -> None: self._append_legend_handles_labels(artists[0], label) - def _make_plot_keywords(self, kwds, y): + def _make_plot_keywords(self, kwds: dict[str, Any], y) -> None: """merge BoxPlot/KdePlot properties to passed kwds""" # y is required for KdePlot kwds["bottom"] = self.bottom kwds["bins"] = self.bins - return kwds + + @final + @staticmethod + def _get_column_weights(weights, i: int, y): + # We allow weights to be a multi-dimensional array, e.g. a (10, 2) array, + # and each sub-array (10,) will be called in each iteration. If users only + # provide 1D array, we assume the same weights is used for all iterations + if weights is not None: + if np.ndim(weights) != 1 and np.shape(weights)[-1] != 1: + try: + weights = weights[:, i] + except IndexError as err: + raise ValueError( + "weights must have the same shape as data, " + "or be a single column" + ) from err + weights = weights[~isna(y)] + return weights def _post_plot_logic(self, ax: Axes, data) -> None: if self.orientation == "horizontal": @@ -207,11 +215,14 @@ def _kind(self) -> Literal["kde"]: def orientation(self) -> Literal["vertical"]: return "vertical" - def __init__(self, data, bw_method=None, ind=None, **kwargs) -> None: + def __init__( + self, data, bw_method=None, ind=None, *, weights=None, **kwargs + ) -> None: # Do not call LinePlot.__init__ which may fill nan MPLPlot.__init__(self, data, **kwargs) # pylint: disable=non-parent-init-called self.bw_method = bw_method self.ind = ind + self.weights = weights @staticmethod def _get_ind(y, ind): @@ -233,9 +244,10 @@ def _get_ind(y, ind): return ind @classmethod - def _plot( + # error: Signature of "_plot" incompatible with supertype "MPLPlot" + def _plot( # type: ignore[override] cls, - ax, + ax: Axes, y, style=None, bw_method=None, @@ -253,10 +265,9 @@ def _plot( lines = MPLPlot._plot(ax, ind, y, style=style, **kwds) return lines - def _make_plot_keywords(self, kwds, y): + def _make_plot_keywords(self, kwds: dict[str, Any], y) -> None: kwds["bw_method"] = self.bw_method kwds["ind"] = self._get_ind(y, ind=self.ind) - return kwds def _post_plot_logic(self, ax, data) -> None: ax.set_ylabel("Density")
- [ ] 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/55877
2023-11-08T01:36:46Z
2023-11-08T21:02:36Z
2023-11-08T21:02:36Z
2023-11-08T22:51:56Z
TST: Add dedicated test for plt.savefig
diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index e51dd06881c4f..fd5a66049bd24 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -535,9 +535,6 @@ def _check_plot_works(f, default_axes=False, **kwargs): for ret in gen_plots(f, fig, **kwargs): tm.assert_is_valid_plot_return_object(ret) - with tm.ensure_clean(return_filelike=True) as path: - plt.savefig(path) - finally: plt.close(fig) diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 42f1a30983414..28bd5fe4c4e5e 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1645,9 +1645,6 @@ def _check_plot_works(f, freq=None, series=None, *args, **kwargs): ret = f(*args, **kwargs) assert ret is not None # TODO: do something more intelligent - with tm.ensure_clean(return_filelike=True) as path: - plt.savefig(path) - # GH18439, GH#24088, statsmodels#4772 with tm.ensure_clean(return_filelike=True) as path: pickle.dump(fig, path) diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index f0d3d66eff462..5b06cd1ab296a 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -1,4 +1,5 @@ """ Test cases for misc plot functions """ +import os import numpy as np import pytest @@ -10,7 +11,9 @@ Index, Series, Timestamp, + date_range, interval_range, + period_range, plotting, ) import pandas._testing as tm @@ -23,6 +26,7 @@ ) mpl = pytest.importorskip("matplotlib") +plt = pytest.importorskip("matplotlib.pyplot") cm = pytest.importorskip("matplotlib.cm") @@ -69,6 +73,30 @@ def test_get_accessor_args(): assert len(kwargs) == 24 +@pytest.mark.parametrize("kind", plotting.PlotAccessor._all_kinds) +@pytest.mark.parametrize( + "data", [DataFrame(np.arange(15).reshape(5, 3)), Series(range(5))] +) +@pytest.mark.parametrize( + "index", + [ + Index(range(5)), + date_range("2020-01-01", periods=5), + period_range("2020-01-01", periods=5), + ], +) +def test_savefig(kind, data, index): + fig, ax = plt.subplots() + data.index = index + kwargs = {} + if kind in ["hexbin", "scatter", "pie"]: + if isinstance(data, Series): + pytest.skip(f"{kind} not supported with Series") + kwargs = {"x": 0, "y": 1} + data.plot(kind=kind, ax=ax, **kwargs) + fig.savefig(os.devnull) + + class TestSeriesPlots: def test_autocorrelation_plot(self): from pandas.plotting import autocorrelation_plot
I'm observing that testing `plt.savefig` seems to appear redundant over certain plotting types and not necessarily comprehensive over all the supported plotting types. Additionally, by isolating `plt.savefig` testing, I'm seeing a 20 second time save when testing `pandas/tests/plotting`
https://api.github.com/repos/pandas-dev/pandas/pulls/55876
2023-11-07T22:35:39Z
2023-11-09T15:37:52Z
2023-11-09T15:37:52Z
2023-11-09T15:37:56Z
REF: make plotting less stateful (4)
diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 8e2b6377a0fb2..9fd3bd3a01be0 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -10,6 +10,7 @@ from matplotlib.artist import setp import numpy as np +from pandas.util._decorators import cache_readonly from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import is_dict_like @@ -132,15 +133,29 @@ def _validate_color_args(self): else: self.color = None + @cache_readonly + def _color_attrs(self): # get standard colors for default - colors = get_standard_colors(num_colors=3, colormap=self.colormap, color=None) # use 2 colors by default, for box/whisker and median # flier colors isn't needed here # because it can be specified by ``sym`` kw - self._boxes_c = colors[0] - self._whiskers_c = colors[0] - self._medians_c = colors[2] - self._caps_c = colors[0] + return get_standard_colors(num_colors=3, colormap=self.colormap, color=None) + + @cache_readonly + def _boxes_c(self): + return self._color_attrs[0] + + @cache_readonly + def _whiskers_c(self): + return self._color_attrs[0] + + @cache_readonly + def _medians_c(self): + return self._color_attrs[2] + + @cache_readonly + def _caps_c(self): + return self._color_attrs[0] def _get_colors( self, diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 23af2b4a3027c..57caa05048a60 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -90,6 +90,8 @@ npt, ) + from pandas import Series + def _color_in_style(style: str) -> bool: """ @@ -471,7 +473,8 @@ def generate(self) -> None: self._post_plot_logic(ax, self.data) @final - def _has_plotted_object(self, ax: Axes) -> bool: + @staticmethod + def _has_plotted_object(ax: Axes) -> bool: """check whether ax has data""" return len(ax.lines) != 0 or len(ax.artists) != 0 or len(ax.containers) != 0 @@ -576,7 +579,8 @@ def result(self): return self.axes[0] @final - def _convert_to_ndarray(self, data): + @staticmethod + def _convert_to_ndarray(data): # GH31357: categorical columns are processed separately if isinstance(data.dtype, CategoricalDtype): return data @@ -767,6 +771,7 @@ def _apply_axis_properties( if fontsize is not None: label.set_fontsize(fontsize) + @final @property def legend_title(self) -> str | None: if not isinstance(self.data.columns, ABCMultiIndex): @@ -836,7 +841,8 @@ def _make_legend(self) -> None: ax.legend(loc="best") @final - def _get_ax_legend(self, ax: Axes): + @staticmethod + def _get_ax_legend(ax: Axes): """ Take in axes and return ax and legend under different scenarios """ @@ -1454,7 +1460,7 @@ def _plot( # type: ignore[override] return lines @final - def _ts_plot(self, ax: Axes, x, data, style=None, **kwds): + def _ts_plot(self, ax: Axes, x, data: Series, style=None, **kwds): # accept x to be consistent with normal plot func, # x is not passed to tsplot as it uses data.index as x coordinate # column_num must be in kwds for stacking purpose @@ -1471,11 +1477,13 @@ def _ts_plot(self, ax: Axes, x, data, style=None, **kwds): lines = self._plot(ax, data.index, data.values, style=style, **kwds) # set date formatter, locators and rescale limits - format_dateaxis(ax, ax.freq, data.index) + # error: Argument 3 to "format_dateaxis" has incompatible type "Index"; + # expected "DatetimeIndex | PeriodIndex" + format_dateaxis(ax, ax.freq, data.index) # type: ignore[arg-type] return lines @final - def _get_stacking_id(self): + def _get_stacking_id(self) -> int | None: if self.stacked: return id(self.data) else: diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index 2279905c053a4..904624fb83b40 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -56,12 +56,16 @@ def __init__( data, bins: int | np.ndarray | list[np.ndarray] = 10, bottom: int | np.ndarray = 0, + *, + range=None, **kwargs, ) -> None: if is_list_like(bottom): bottom = np.array(bottom) self.bottom = bottom + self._bin_range = range + self.xlabel = kwargs.get("xlabel") self.ylabel = kwargs.get("ylabel") # Do not call LinePlot.__init__ which may fill nan @@ -85,7 +89,7 @@ def _calculate_bins(self, data: DataFrame, bins) -> np.ndarray: values = np.ravel(nd_values) values = values[~isna(values)] - hist, bins = np.histogram(values, bins=bins, range=self.kwds.get("range", None)) + hist, bins = np.histogram(values, bins=bins, range=self._bin_range) return bins # error: Signature of "_plot" incompatible with supertype "LinePlot" @@ -209,8 +213,9 @@ def __init__(self, data, bw_method=None, ind=None, **kwargs) -> None: self.bw_method = bw_method self.ind = ind - def _get_ind(self, y): - if self.ind is None: + @staticmethod + def _get_ind(y, ind): + if ind is None: # np.nanmax() and np.nanmin() ignores the missing values sample_range = np.nanmax(y) - np.nanmin(y) ind = np.linspace( @@ -218,15 +223,13 @@ def _get_ind(self, y): np.nanmax(y) + 0.5 * sample_range, 1000, ) - elif is_integer(self.ind): + elif is_integer(ind): sample_range = np.nanmax(y) - np.nanmin(y) ind = np.linspace( np.nanmin(y) - 0.5 * sample_range, np.nanmax(y) + 0.5 * sample_range, - self.ind, + ind, ) - else: - ind = self.ind return ind @classmethod @@ -252,7 +255,7 @@ def _plot( def _make_plot_keywords(self, kwds, y): kwds["bw_method"] = self.bw_method - kwds["ind"] = self._get_ind(y) + kwds["ind"] = self._get_ind(y, ind=self.ind) return kwds def _post_plot_logic(self, ax, data) -> None: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index d3cddc81d3cc4..e3e02c69a26db 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -48,6 +48,7 @@ DataFrame, DatetimeIndex, Index, + PeriodIndex, Series, ) @@ -300,8 +301,7 @@ def maybe_convert_index(ax: Axes, data): return data -# Patch methods for subplot. Only format_dateaxis is currently used. -# Do we need the rest for convenience? +# Patch methods for subplot. def _format_coord(freq, t, y) -> str: @@ -309,7 +309,9 @@ def _format_coord(freq, t, y) -> str: return f"t = {time_period} y = {y:8f}" -def format_dateaxis(subplot, freq, index) -> None: +def format_dateaxis( + subplot, freq: BaseOffset, index: DatetimeIndex | PeriodIndex +) -> None: """ Pretty-formats the date axis (x-axis).
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/55872
2023-11-07T20:24:00Z
2023-11-07T22:36:58Z
2023-11-07T22:36:58Z
2023-11-07T22:44:12Z
TST: Simplify tests, remove unnecessary minversions
diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py index f11ec5f8a36a0..13efc0f60ecef 100644 --- a/pandas/tests/arrays/masked/test_arrow_compat.py +++ b/pandas/tests/arrays/masked/test_arrow_compat.py @@ -4,7 +4,7 @@ import pandas as pd import pandas._testing as tm -pa = pytest.importorskip("pyarrow", minversion="1.0.1") +pa = pytest.importorskip("pyarrow") from pandas.core.arrays.arrow._arrow_utils import pyarrow_array_to_numpy_and_mask diff --git a/pandas/tests/arrays/string_/test_string_arrow.py b/pandas/tests/arrays/string_/test_string_arrow.py index b3bc2c7166130..a801a845bc7be 100644 --- a/pandas/tests/arrays/string_/test_string_arrow.py +++ b/pandas/tests/arrays/string_/test_string_arrow.py @@ -95,7 +95,7 @@ def test_constructor_valid_string_type_value_dictionary(chunked): def test_constructor_from_list(): # GH#27673 - pytest.importorskip("pyarrow", minversion="1.0.0") + pytest.importorskip("pyarrow") result = pd.Series(["E"], dtype=StringDtype(storage="pyarrow")) assert isinstance(result.dtype, StringDtype) assert result.dtype.storage == "pyarrow" diff --git a/pandas/tests/extension/test_arrow.py b/pandas/tests/extension/test_arrow.py index cb44453f55e5e..adbc4a1bb729b 100644 --- a/pandas/tests/extension/test_arrow.py +++ b/pandas/tests/extension/test_arrow.py @@ -60,7 +60,7 @@ ) from pandas.tests.extension import base -pa = pytest.importorskip("pyarrow", minversion="10.0.1") +pa = pytest.importorskip("pyarrow") from pandas.core.arrays.arrow.array import ArrowExtensionArray from pandas.core.arrays.arrow.extension_types import ArrowPeriodType diff --git a/pandas/tests/groupby/test_filters.py b/pandas/tests/groupby/test_filters.py index 0bb7ad4fd274d..309c4b7b57e84 100644 --- a/pandas/tests/groupby/test_filters.py +++ b/pandas/tests/groupby/test_filters.py @@ -190,9 +190,9 @@ def test_filter_pdna_is_false(): tm.assert_series_equal(res, ser[[]]) -def test_filter_against_workaround(): +def test_filter_against_workaround_ints(): # Series of ints - s = Series(np.random.default_rng(2).integers(0, 100, 1000)) + s = Series(np.random.default_rng(2).integers(0, 100, 100)) grouper = s.apply(lambda x: np.round(x, -1)) grouped = s.groupby(grouper) f = lambda x: x.mean() > 10 @@ -201,8 +201,10 @@ def test_filter_against_workaround(): new_way = grouped.filter(f) tm.assert_series_equal(new_way.sort_values(), old_way.sort_values()) + +def test_filter_against_workaround_floats(): # Series of floats - s = 100 * Series(np.random.default_rng(2).random(1000)) + s = 100 * Series(np.random.default_rng(2).random(100)) grouper = s.apply(lambda x: np.round(x, -1)) grouped = s.groupby(grouper) f = lambda x: x.mean() > 10 @@ -210,9 +212,11 @@ def test_filter_against_workaround(): new_way = grouped.filter(f) tm.assert_series_equal(new_way.sort_values(), old_way.sort_values()) + +def test_filter_against_workaround_dataframe(): # Set up DataFrame of ints, floats, strings. letters = np.array(list(ascii_lowercase)) - N = 1000 + N = 100 random_letters = letters.take( np.random.default_rng(2).integers(0, 26, N, dtype=int) ) diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index c4e23154b7ffc..0ebb88afb6c86 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -9,6 +9,7 @@ DataFrame, DatetimeIndex, Index, + MultiIndex, Series, Timedelta, Timestamp, @@ -360,10 +361,12 @@ def test_partial_slicing_with_multiindex(self): def test_partial_slicing_with_multiindex_series(self): # GH 4294 # partial slice on a series mi - ser = DataFrame( - np.random.default_rng(2).random((1000, 1000)), - index=date_range("2000-1-1", periods=1000), - ).stack(future_stack=True) + ser = Series( + range(250), + index=MultiIndex.from_product( + [date_range("2000-1-1", periods=50), range(5)] + ), + ) s2 = ser[:-1].copy() expected = s2["2000-1-4"] diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py index 26ef732635d1c..d956747cbc859 100644 --- a/pandas/tests/indexes/multi/test_integrity.py +++ b/pandas/tests/indexes/multi/test_integrity.py @@ -125,18 +125,20 @@ def test_consistency(): @pytest.mark.slow -def test_hash_collisions(): +def test_hash_collisions(monkeypatch): # non-smoke test that we don't get hash collisions + size_cutoff = 50 + with monkeypatch.context() as m: + m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + index = MultiIndex.from_product( + [np.arange(8), np.arange(8)], names=["one", "two"] + ) + result = index.get_indexer(index.values) + tm.assert_numpy_array_equal(result, np.arange(len(index), dtype="intp")) - index = MultiIndex.from_product( - [np.arange(1000), np.arange(1000)], names=["one", "two"] - ) - result = index.get_indexer(index.values) - tm.assert_numpy_array_equal(result, np.arange(len(index), dtype="intp")) - - for i in [0, 1, len(index) - 2, len(index) - 1]: - result = index.get_loc(index[i]) - assert result == i + for i in [0, 1, len(index) - 2, len(index) - 1]: + result = index.get_loc(index[i]) + assert result == i def test_dims(): @@ -170,22 +172,29 @@ def test_isna_behavior(idx): pd.isna(idx) -def test_large_multiindex_error(): +def test_large_multiindex_error(monkeypatch): # GH12527 - df_below_1000000 = pd.DataFrame( - 1, index=MultiIndex.from_product([[1, 2], range(499999)]), columns=["dest"] - ) - with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): - df_below_1000000.loc[(-1, 0), "dest"] - with pytest.raises(KeyError, match=r"^\(3, 0\)$"): - df_below_1000000.loc[(3, 0), "dest"] - df_above_1000000 = pd.DataFrame( - 1, index=MultiIndex.from_product([[1, 2], range(500001)]), columns=["dest"] - ) - with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): - df_above_1000000.loc[(-1, 0), "dest"] - with pytest.raises(KeyError, match=r"^\(3, 0\)$"): - df_above_1000000.loc[(3, 0), "dest"] + size_cutoff = 50 + with monkeypatch.context() as m: + m.setattr(libindex, "_SIZE_CUTOFF", size_cutoff) + df_below_cutoff = pd.DataFrame( + 1, + index=MultiIndex.from_product([[1, 2], range(size_cutoff - 1)]), + columns=["dest"], + ) + with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): + df_below_cutoff.loc[(-1, 0), "dest"] + with pytest.raises(KeyError, match=r"^\(3, 0\)$"): + df_below_cutoff.loc[(3, 0), "dest"] + df_above_cutoff = pd.DataFrame( + 1, + index=MultiIndex.from_product([[1, 2], range(size_cutoff + 1)]), + columns=["dest"], + ) + with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): + df_above_cutoff.loc[(-1, 0), "dest"] + with pytest.raises(KeyError, match=r"^\(3, 0\)$"): + df_above_cutoff.loc[(3, 0), "dest"] def test_mi_hashtable_populated_attribute_error(monkeypatch): diff --git a/pandas/tests/indexes/test_old_base.py b/pandas/tests/indexes/test_old_base.py index 32adbc693390b..30e3f5cee05b4 100644 --- a/pandas/tests/indexes/test_old_base.py +++ b/pandas/tests/indexes/test_old_base.py @@ -1,7 +1,7 @@ from __future__ import annotations from datetime import datetime -import gc +import weakref import numpy as np import pytest @@ -744,10 +744,11 @@ def test_is_unique(self, simple_index): @pytest.mark.arm_slow def test_engine_reference_cycle(self, simple_index): # GH27585 - index = simple_index - nrefs_pre = len(gc.get_referrers(index)) + index = simple_index.copy() + ref = weakref.ref(index) index._engine - assert len(gc.get_referrers(index)) == nrefs_pre + del index + assert ref() is None def test_getitem_2d_deprecated(self, simple_index): # GH#30588, GH#31479 diff --git a/pandas/tests/io/conftest.py b/pandas/tests/io/conftest.py index 701bfe3767db4..d3552ab5d39f5 100644 --- a/pandas/tests/io/conftest.py +++ b/pandas/tests/io/conftest.py @@ -96,7 +96,7 @@ def s3_base(worker_id, monkeysession): yield "http://localhost:5000" else: requests = pytest.importorskip("requests") - pytest.importorskip("moto", minversion="1.3.14") + pytest.importorskip("moto") pytest.importorskip("flask") # server mode needs flask too # Launching moto in server mode, i.e., as a separate process diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index c029acf0c8938..f5d78fbd44812 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -95,7 +95,7 @@ def test_left_join_multi_index(self, sort): def bind_cols(df): iord = lambda a: 0 if a != a else ord(a) f = lambda ts: ts.map(iord) - ord("a") - return f(df["1st"]) + f(df["3rd"]) * 1e2 + df["2nd"].fillna(0) * 1e4 + return f(df["1st"]) + f(df["3rd"]) * 1e2 + df["2nd"].fillna(0) * 10 def run_asserts(left, right, sort): res = left.join(right, on=icols, how="left", sort=sort) @@ -119,13 +119,13 @@ def run_asserts(left, right, sort): lc = list(map(chr, np.arange(ord("a"), ord("z") + 1))) left = DataFrame( - np.random.default_rng(2).choice(lc, (5000, 2)), columns=["1st", "3rd"] + np.random.default_rng(2).choice(lc, (50, 2)), columns=["1st", "3rd"] ) # Explicit cast to float to avoid implicit cast when setting nan left.insert( 1, "2nd", - np.random.default_rng(2).integers(0, 1000, len(left)).astype("float"), + np.random.default_rng(2).integers(0, 10, len(left)).astype("float"), ) i = np.random.default_rng(2).permutation(len(left)) @@ -138,9 +138,9 @@ def run_asserts(left, right, sort): run_asserts(left, right, sort) # inject some nulls - left.loc[1::23, "1st"] = np.nan - left.loc[2::37, "2nd"] = np.nan - left.loc[3::43, "3rd"] = np.nan + left.loc[1::4, "1st"] = np.nan + left.loc[2::5, "2nd"] = np.nan + left.loc[3::6, "3rd"] = np.nan left["4th"] = bind_cols(left) i = np.random.default_rng(2).permutation(len(left)) diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index 08a1c8e3aebb2..5903255118d40 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -100,7 +100,7 @@ def test_xarray(df): def test_xarray_cftimeindex_nearest(): # https://github.com/pydata/xarray/issues/3751 cftime = pytest.importorskip("cftime") - xarray = pytest.importorskip("xarray", minversion="0.21.0") + xarray = pytest.importorskip("xarray") times = xarray.cftime_range("0001", periods=2) key = cftime.DatetimeGregorian(2000, 1, 1)
null
https://api.github.com/repos/pandas-dev/pandas/pulls/55871
2023-11-07T20:10:58Z
2023-11-08T17:57:49Z
2023-11-08T17:57:49Z
2023-11-08T17:57:53Z
REF: misplaced tests, parametrize, simplify
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 15381afbd3c6d..be52ef2fe9c9b 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1421,8 +1421,9 @@ def test_dt64arr_add_sub_relativedelta_offsets(self, box_with_array, unit): @pytest.mark.parametrize("normalize", [True, False]) @pytest.mark.parametrize("n", [0, 5]) @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) + @pytest.mark.parametrize("tz", [None, "US/Central"]) def test_dt64arr_add_sub_DateOffsets( - self, box_with_array, n, normalize, cls_and_kwargs, unit + self, box_with_array, n, normalize, cls_and_kwargs, unit, tz ): # GH#10699 # assert vectorized operation matches pointwise operations @@ -1444,33 +1445,33 @@ def test_dt64arr_add_sub_DateOffsets( # passing n = 0 is invalid for these offset classes return - vec = DatetimeIndex( - [ - Timestamp("2000-01-05 00:15:00"), - Timestamp("2000-01-31 00:23:00"), - Timestamp("2000-01-01"), - Timestamp("2000-03-31"), - Timestamp("2000-02-29"), - Timestamp("2000-12-31"), - Timestamp("2000-05-15"), - Timestamp("2001-06-15"), - ] - ).as_unit(unit) + vec = ( + DatetimeIndex( + [ + Timestamp("2000-01-05 00:15:00"), + Timestamp("2000-01-31 00:23:00"), + Timestamp("2000-01-01"), + Timestamp("2000-03-31"), + Timestamp("2000-02-29"), + Timestamp("2000-12-31"), + Timestamp("2000-05-15"), + Timestamp("2001-06-15"), + ] + ) + .as_unit(unit) + .tz_localize(tz) + ) vec = tm.box_expected(vec, box_with_array) vec_items = vec.iloc[0] if box_with_array is pd.DataFrame else vec offset_cls = getattr(pd.offsets, cls_name) - - # pandas.errors.PerformanceWarning: Non-vectorized DateOffset being - # applied to Series or DatetimeIndex - # we aren't testing that here, so ignore. - offset = offset_cls(n, normalize=normalize, **kwargs) # TODO(GH#55564): as_unit will be unnecessary expected = DatetimeIndex([x + offset for x in vec_items]).as_unit(unit) expected = tm.box_expected(expected, box_with_array) tm.assert_equal(expected, vec + offset) + tm.assert_equal(expected, offset + vec) expected = DatetimeIndex([x - offset for x in vec_items]).as_unit(unit) expected = tm.box_expected(expected, box_with_array) @@ -1483,64 +1484,6 @@ def test_dt64arr_add_sub_DateOffsets( with pytest.raises(TypeError, match=msg): offset - vec - def test_dt64arr_add_sub_DateOffset(self, box_with_array): - # GH#10699 - s = date_range("2000-01-01", "2000-01-31", name="a") - s = tm.box_expected(s, box_with_array) - result = s + DateOffset(years=1) - result2 = DateOffset(years=1) + s - exp = date_range("2001-01-01", "2001-01-31", name="a")._with_freq(None) - exp = tm.box_expected(exp, box_with_array) - tm.assert_equal(result, exp) - tm.assert_equal(result2, exp) - - result = s - DateOffset(years=1) - exp = date_range("1999-01-01", "1999-01-31", name="a")._with_freq(None) - exp = tm.box_expected(exp, box_with_array) - tm.assert_equal(result, exp) - - s = DatetimeIndex( - [ - Timestamp("2000-01-15 00:15:00", tz="US/Central"), - Timestamp("2000-02-15", tz="US/Central"), - ], - name="a", - ) - s = tm.box_expected(s, box_with_array) - result = s + pd.offsets.Day() - result2 = pd.offsets.Day() + s - exp = DatetimeIndex( - [ - Timestamp("2000-01-16 00:15:00", tz="US/Central"), - Timestamp("2000-02-16", tz="US/Central"), - ], - name="a", - ) - exp = tm.box_expected(exp, box_with_array) - tm.assert_equal(result, exp) - tm.assert_equal(result2, exp) - - s = DatetimeIndex( - [ - Timestamp("2000-01-15 00:15:00", tz="US/Central"), - Timestamp("2000-02-15", tz="US/Central"), - ], - name="a", - ) - s = tm.box_expected(s, box_with_array) - result = s + pd.offsets.MonthEnd() - result2 = pd.offsets.MonthEnd() + s - exp = DatetimeIndex( - [ - Timestamp("2000-01-31 00:15:00", tz="US/Central"), - Timestamp("2000-02-29", tz="US/Central"), - ], - name="a", - ) - exp = tm.box_expected(exp, box_with_array) - tm.assert_equal(result, exp) - tm.assert_equal(result2, exp) - @pytest.mark.parametrize( "other", [ diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index c93a03ad0f479..8d49171cc43f3 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -1393,6 +1393,18 @@ def test_addsub_arithmetic(self, dtype, delta): tm.assert_index_equal(index - index, 0 * index) assert not (index - index).empty + def test_pow_nan_with_zero(self, box_with_array): + left = Index([np.nan, np.nan, np.nan]) + right = Index([0, 0, 0]) + expected = Index([1.0, 1.0, 1.0]) + + left = tm.box_expected(left, box_with_array) + right = tm.box_expected(right, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = left**right + tm.assert_equal(result, expected) + def test_fill_value_inf_masking(): # GH #27464 make sure we mask 0/1 with Inf and not NaN diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py index f50b4cfd0b520..fd38a8df7fa22 100644 --- a/pandas/tests/arrays/integer/test_dtypes.py +++ b/pandas/tests/arrays/integer/test_dtypes.py @@ -23,7 +23,6 @@ def test_dtypes(dtype): @pytest.mark.parametrize("op", ["sum", "min", "max", "prod"]) def test_preserve_dtypes(op): - # TODO(#22346): preserve Int64 dtype # for ops that enable (mean would actually work here # but generally it is a float return value) df = pd.DataFrame( diff --git a/pandas/tests/arrays/interval/test_formats.py b/pandas/tests/arrays/interval/test_formats.py new file mode 100644 index 0000000000000..535efee519374 --- /dev/null +++ b/pandas/tests/arrays/interval/test_formats.py @@ -0,0 +1,13 @@ +from pandas.core.arrays import IntervalArray + + +def test_repr(): + # GH#25022 + arr = IntervalArray.from_tuples([(0, 1), (1, 2)]) + result = repr(arr) + expected = ( + "<IntervalArray>\n" + "[(0, 1], (1, 2]]\n" + "Length: 2, dtype: interval[int64, right]" + ) + assert result == expected diff --git a/pandas/tests/arrays/interval/test_interval.py b/pandas/tests/arrays/interval/test_interval.py index 678ff13d99a5f..e772e4fba6c01 100644 --- a/pandas/tests/arrays/interval/test_interval.py +++ b/pandas/tests/arrays/interval/test_interval.py @@ -166,18 +166,6 @@ def test_setitem_mismatched_closed(self): tm.assert_interval_array_equal(arr, orig) -def test_repr(): - # GH 25022 - arr = IntervalArray.from_tuples([(0, 1), (1, 2)]) - result = repr(arr) - expected = ( - "<IntervalArray>\n" - "[(0, 1], (1, 2]]\n" - "Length: 2, dtype: interval[int64, right]" - ) - assert result == expected - - class TestReductions: def test_min_max_invalid_axis(self, left_right_dtypes): left, right = left_right_dtypes diff --git a/pandas/tests/arrays/interval/test_ops.py b/pandas/tests/arrays/interval/test_overlaps.py similarity index 100% rename from pandas/tests/arrays/interval/test_ops.py rename to pandas/tests/arrays/interval/test_overlaps.py diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 37a0d589cb3b7..377128ee12ee6 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -82,7 +82,8 @@ def test_reset_index_tz(self, tz_aware_fixture): }, columns=["idx", "a", "b"], ) - tm.assert_frame_equal(df.reset_index(), expected) + result = df.reset_index() + tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) def test_frame_reset_index_tzaware_index(self, tz): @@ -487,23 +488,20 @@ def test_reset_index_datetime(self, tz_naive_fixture): expected = DataFrame( { - "idx1": [ - datetime(2011, 1, 1), - datetime(2011, 1, 2), - datetime(2011, 1, 3), - datetime(2011, 1, 4), - datetime(2011, 1, 5), - ], + "idx1": idx1, "idx2": np.arange(5, dtype="int64"), "a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"], }, columns=["idx1", "idx2", "a", "b"], ) - expected["idx1"] = expected["idx1"].apply(lambda d: Timestamp(d, tz=tz)) tm.assert_frame_equal(df.reset_index(), expected) + def test_reset_index_datetime2(self, tz_naive_fixture): + tz = tz_naive_fixture + idx1 = date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1") + idx2 = Index(range(5), name="idx2", dtype="int64") idx3 = date_range( "1/1/2012", periods=5, freq="MS", tz="Europe/Paris", name="idx3" ) @@ -515,36 +513,22 @@ def test_reset_index_datetime(self, tz_naive_fixture): expected = DataFrame( { - "idx1": [ - datetime(2011, 1, 1), - datetime(2011, 1, 2), - datetime(2011, 1, 3), - datetime(2011, 1, 4), - datetime(2011, 1, 5), - ], + "idx1": idx1, "idx2": np.arange(5, dtype="int64"), - "idx3": [ - datetime(2012, 1, 1), - datetime(2012, 2, 1), - datetime(2012, 3, 1), - datetime(2012, 4, 1), - datetime(2012, 5, 1), - ], + "idx3": idx3, "a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"], }, columns=["idx1", "idx2", "idx3", "a", "b"], ) - expected["idx1"] = expected["idx1"].apply(lambda d: Timestamp(d, tz=tz)) - expected["idx3"] = expected["idx3"].apply( - lambda d: Timestamp(d, tz="Europe/Paris") - ) - tm.assert_frame_equal(df.reset_index(), expected) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + def test_reset_index_datetime3(self, tz_naive_fixture): # GH#7793 - idx = MultiIndex.from_product( - [["a", "b"], date_range("20130101", periods=3, tz=tz)] - ) + tz = tz_naive_fixture + dti = date_range("20130101", periods=3, tz=tz) + idx = MultiIndex.from_product([["a", "b"], dti]) df = DataFrame( np.arange(6, dtype="int64").reshape(6, 1), columns=["a"], index=idx ) @@ -552,17 +536,11 @@ def test_reset_index_datetime(self, tz_naive_fixture): expected = DataFrame( { "level_0": "a a a b b b".split(), - "level_1": [ - datetime(2013, 1, 1), - datetime(2013, 1, 2), - datetime(2013, 1, 3), - ] - * 2, + "level_1": dti.append(dti), "a": np.arange(6, dtype="int64"), }, columns=["level_0", "level_1", "a"], ) - expected["level_1"] = expected["level_1"].apply(lambda d: Timestamp(d, tz=tz)) result = df.reset_index() tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index da5a2c21023b7..8b37d8fc2327b 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1904,20 +1904,6 @@ def test_pow_with_realignment(): tm.assert_frame_equal(result, expected) -# TODO: move to tests.arithmetic and parametrize -def test_pow_nan_with_zero(): - left = DataFrame({"A": [np.nan, np.nan, np.nan]}) - right = DataFrame({"A": [0, 0, 0]}) - - expected = DataFrame({"A": [1.0, 1.0, 1.0]}) - - result = left**right - tm.assert_frame_equal(result, expected) - - result = left["A"] ** right["A"] - tm.assert_series_equal(result, expected["A"]) - - def test_dataframe_series_extension_dtypes(): # https://github.com/pandas-dev/pandas/issues/34311 df = DataFrame( diff --git a/pandas/tests/groupby/methods/test_nth.py b/pandas/tests/groupby/methods/test_nth.py index 1cf4a90e25f1b..b21060e7f1247 100644 --- a/pandas/tests/groupby/methods/test_nth.py +++ b/pandas/tests/groupby/methods/test_nth.py @@ -143,12 +143,14 @@ def test_first_last_nth_dtypes(df_mixed_floats): expected = df.iloc[[2, 3]] tm.assert_frame_equal(nth, expected) + +def test_first_last_nth_dtypes2(): # GH 2763, first/last shifting dtypes idx = list(range(10)) idx.append(9) - s = Series(data=range(11), index=idx, name="IntCol") - assert s.dtype == "int64" - f = s.groupby(level=0).first() + ser = Series(data=range(11), index=idx, name="IntCol") + assert ser.dtype == "int64" + f = ser.groupby(level=0).first() assert f.dtype == "int64" @@ -187,24 +189,26 @@ def test_first_strings_timestamps(): def test_nth(): df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) - g = df.groupby("A") + gb = df.groupby("A") + + tm.assert_frame_equal(gb.nth(0), df.iloc[[0, 2]]) + tm.assert_frame_equal(gb.nth(1), df.iloc[[1]]) + tm.assert_frame_equal(gb.nth(2), df.loc[[]]) + tm.assert_frame_equal(gb.nth(-1), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(-2), df.iloc[[0]]) + tm.assert_frame_equal(gb.nth(-3), df.loc[[]]) + tm.assert_series_equal(gb.B.nth(0), df.B.iloc[[0, 2]]) + tm.assert_series_equal(gb.B.nth(1), df.B.iloc[[1]]) + tm.assert_frame_equal(gb[["B"]].nth(0), df[["B"]].iloc[[0, 2]]) - tm.assert_frame_equal(g.nth(0), df.iloc[[0, 2]]) - tm.assert_frame_equal(g.nth(1), df.iloc[[1]]) - tm.assert_frame_equal(g.nth(2), df.loc[[]]) - tm.assert_frame_equal(g.nth(-1), df.iloc[[1, 2]]) - tm.assert_frame_equal(g.nth(-2), df.iloc[[0]]) - tm.assert_frame_equal(g.nth(-3), df.loc[[]]) - tm.assert_series_equal(g.B.nth(0), df.B.iloc[[0, 2]]) - tm.assert_series_equal(g.B.nth(1), df.B.iloc[[1]]) - tm.assert_frame_equal(g[["B"]].nth(0), df[["B"]].iloc[[0, 2]]) + tm.assert_frame_equal(gb.nth(0, dropna="any"), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(-1, dropna="any"), df.iloc[[1, 2]]) - tm.assert_frame_equal(g.nth(0, dropna="any"), df.iloc[[1, 2]]) - tm.assert_frame_equal(g.nth(-1, dropna="any"), df.iloc[[1, 2]]) + tm.assert_frame_equal(gb.nth(7, dropna="any"), df.iloc[:0]) + tm.assert_frame_equal(gb.nth(2, dropna="any"), df.iloc[:0]) - tm.assert_frame_equal(g.nth(7, dropna="any"), df.iloc[:0]) - tm.assert_frame_equal(g.nth(2, dropna="any"), df.iloc[:0]) +def test_nth2(): # out of bounds, regression from 0.13.1 # GH 6621 df = DataFrame( @@ -236,45 +240,53 @@ def test_nth(): expected = df.loc[[]] tm.assert_frame_equal(result, expected) + +def test_nth3(): # GH 7559 # from the vbench df = DataFrame(np.random.default_rng(2).integers(1, 10, (100, 2)), dtype="int64") - s = df[1] - g = df[0] - expected = s.groupby(g).first() - expected2 = s.groupby(g).apply(lambda x: x.iloc[0]) + ser = df[1] + gb = df[0] + expected = ser.groupby(gb).first() + expected2 = ser.groupby(gb).apply(lambda x: x.iloc[0]) tm.assert_series_equal(expected2, expected, check_names=False) assert expected.name == 1 assert expected2.name == 1 # validate first - v = s[g == 1].iloc[0] + v = ser[gb == 1].iloc[0] assert expected.iloc[0] == v assert expected2.iloc[0] == v with pytest.raises(ValueError, match="For a DataFrame"): - s.groupby(g, sort=False).nth(0, dropna=True) + ser.groupby(gb, sort=False).nth(0, dropna=True) + +def test_nth4(): # doc example df = DataFrame([[1, np.nan], [1, 4], [5, 6]], columns=["A", "B"]) - g = df.groupby("A") - result = g.B.nth(0, dropna="all") + gb = df.groupby("A") + result = gb.B.nth(0, dropna="all") expected = df.B.iloc[[1, 2]] tm.assert_series_equal(result, expected) + +def test_nth5(): # test multiple nth values df = DataFrame([[1, np.nan], [1, 3], [1, 4], [5, 6], [5, 7]], columns=["A", "B"]) - g = df.groupby("A") + gb = df.groupby("A") + + tm.assert_frame_equal(gb.nth(0), df.iloc[[0, 3]]) + tm.assert_frame_equal(gb.nth([0]), df.iloc[[0, 3]]) + tm.assert_frame_equal(gb.nth([0, 1]), df.iloc[[0, 1, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, -1]), df.iloc[[0, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]]) + tm.assert_frame_equal(gb.nth([2]), df.iloc[[2]]) + tm.assert_frame_equal(gb.nth([3, 4]), df.loc[[]]) - tm.assert_frame_equal(g.nth(0), df.iloc[[0, 3]]) - tm.assert_frame_equal(g.nth([0]), df.iloc[[0, 3]]) - tm.assert_frame_equal(g.nth([0, 1]), df.iloc[[0, 1, 3, 4]]) - tm.assert_frame_equal(g.nth([0, -1]), df.iloc[[0, 2, 3, 4]]) - tm.assert_frame_equal(g.nth([0, 1, 2]), df.iloc[[0, 1, 2, 3, 4]]) - tm.assert_frame_equal(g.nth([0, 1, -1]), df.iloc[[0, 1, 2, 3, 4]]) - tm.assert_frame_equal(g.nth([2]), df.iloc[[2]]) - tm.assert_frame_equal(g.nth([3, 4]), df.loc[[]]) +def test_nth_bdays(): business_dates = pd.date_range(start="4/1/2014", end="6/30/2014", freq="B") df = DataFrame(1, index=business_dates, columns=["a", "b"]) # get the first, fourth and last two business days for each month diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 974ae2f1ad17b..22614c542ed09 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -101,6 +101,8 @@ def test_transform_fast(): result = grp.transform("mean") tm.assert_series_equal(result, expected) + +def test_transform_fast2(): # GH 12737 df = DataFrame( { @@ -130,6 +132,8 @@ def test_transform_fast(): expected = expected[["f", "i"]] tm.assert_frame_equal(result, expected) + +def test_transform_fast3(): # dup columns df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["g", "a", "a"]) result = df.groupby("g").transform("first") diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index f717165d118b6..b5974115e2d76 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -35,7 +35,6 @@ DatetimeArray, period_array, ) -from pandas.tests.indexes.datetimes.test_timezones import FixedOffset class TestDatetimeIndex: @@ -845,14 +844,12 @@ def test_construction_int_rountrip(self, tz_naive_fixture): def test_construction_from_replaced_timestamps_with_dst(self): # GH 18785 index = date_range( - Timestamp(2000, 1, 1), - Timestamp(2005, 1, 1), - freq="MS", + Timestamp(2000, 12, 31), + Timestamp(2005, 12, 31), + freq="Y-DEC", tz="Australia/Melbourne", ) - test = pd.DataFrame({"data": range(len(index))}, index=index) - test = test.resample("Y").mean() - result = DatetimeIndex([x.replace(month=6, day=1) for x in test.index]) + result = DatetimeIndex([x.replace(month=6, day=1) for x in index]) expected = DatetimeIndex( [ "2000-06-01 00:00:00", @@ -994,19 +991,6 @@ def test_dti_constructor_static_tzinfo(self, prefix): index.hour index[0] - def test_dti_constructor_with_fixed_tz(self): - off = FixedOffset(420, "+07:00") - start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off) - end = datetime(2012, 6, 11, 5, 0, 0, tzinfo=off) - rng = date_range(start=start, end=end) - assert off == rng.tz - - rng2 = date_range(start, periods=len(rng), tz=off) - tm.assert_index_equal(rng, rng2) - - rng3 = date_range("3/11/2012 05:00:00+07:00", "6/11/2012 05:00:00+07:00") - assert (rng.values == rng3.values).all() - @pytest.mark.parametrize("tzstr", ["US/Eastern", "dateutil/US/Eastern"]) def test_dti_convert_datetime_list(self, tzstr): dr = date_range("2012-06-02", periods=10, tz=tzstr, name="foo") @@ -1113,29 +1097,6 @@ def test_explicit_none_freq(self): dta = DatetimeArray(rng, freq=None) assert dta.freq is None - def test_dti_constructor_years_only(self, tz_naive_fixture): - tz = tz_naive_fixture - # GH 6961 - rng1 = date_range("2014", "2015", freq="ME", tz=tz) - expected1 = date_range("2014-01-31", "2014-12-31", freq="ME", tz=tz) - - rng2 = date_range("2014", "2015", freq="MS", tz=tz) - expected2 = date_range("2014-01-01", "2015-01-01", freq="MS", tz=tz) - - rng3 = date_range("2014", "2020", freq="Y", tz=tz) - expected3 = date_range("2014-12-31", "2019-12-31", freq="Y", tz=tz) - - rng4 = date_range("2014", "2020", freq="YS", tz=tz) - expected4 = date_range("2014-01-01", "2020-01-01", freq="YS", tz=tz) - - for rng, expected in [ - (rng1, expected1), - (rng2, expected2), - (rng3, expected3), - (rng4, expected4), - ]: - tm.assert_index_equal(rng, expected) - def test_dti_constructor_small_int(self, any_int_numpy_dtype): # see gh-13721 exp = DatetimeIndex( @@ -1153,12 +1114,6 @@ def test_ctor_str_intraday(self): rng = DatetimeIndex(["1-1-2000 00:00:01"]) assert rng[0].second == 1 - def test_is_(self): - dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME") - assert dti.is_(dti) - assert dti.is_(dti.view()) - assert not dti.is_(dti.copy()) - def test_index_cast_datetime64_other_units(self): arr = np.arange(0, 100, 10, dtype=np.int64).view("M8[D]") idx = Index(arr) @@ -1221,32 +1176,6 @@ def test_datetimeindex_constructor_misc(self): for other in [idx2, idx3, idx4]: assert (idx1.values == other.values).all() - sdate = datetime(1999, 12, 25) - edate = datetime(2000, 1, 1) - idx = date_range(start=sdate, freq="1B", periods=20) - assert len(idx) == 20 - assert idx[0] == sdate + 0 * offsets.BDay() - assert idx.freq == "B" - - idx1 = date_range(start=sdate, end=edate, freq="W-SUN") - idx2 = date_range(start=sdate, end=edate, freq=offsets.Week(weekday=6)) - assert len(idx1) == len(idx2) - assert idx1.freq == idx2.freq - - idx1 = date_range(start=sdate, end=edate, freq="QS") - idx2 = date_range( - start=sdate, end=edate, freq=offsets.QuarterBegin(startingMonth=1) - ) - assert len(idx1) == len(idx2) - assert idx1.freq == idx2.freq - - idx1 = date_range(start=sdate, end=edate, freq="BQ") - idx2 = date_range( - start=sdate, end=edate, freq=offsets.BQuarterEnd(startingMonth=12) - ) - assert len(idx1) == len(idx2) - assert idx1.freq == idx2.freq - def test_dti_constructor_object_dtype_dayfirst_yearfirst_with_tz(self): # GH#55813 val = "5/10/16" @@ -1261,12 +1190,3 @@ def test_dti_constructor_object_dtype_dayfirst_yearfirst_with_tz(self): result2 = DatetimeIndex([val], tz="US/Pacific", yearfirst=True) expected2 = DatetimeIndex([yfirst]) tm.assert_index_equal(result2, expected2) - - def test_pass_datetimeindex_to_index(self): - # Bugs in #1396 - rng = date_range("1/1/2000", "3/1/2000") - idx = Index(rng, dtype=object) - - expected = Index(rng.to_pydatetime(), dtype=object) - - tm.assert_numpy_array_equal(idx.values, expected.values) diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index e902c8236894e..7a8f7dc22f49c 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -38,6 +38,10 @@ ) import pandas._testing as tm from pandas.core.arrays.datetimes import _generate_range as generate_range +from pandas.tests.indexes.datetimes.test_timezones import ( + FixedOffset, + fixed_off_no_name, +) START, END = datetime(2009, 1, 1), datetime(2010, 1, 1) @@ -760,11 +764,24 @@ def test_range_closed_boundary(self, inclusive_endpoints_fixture): tm.assert_index_equal(both_boundary, expected_both) tm.assert_index_equal(neither_boundary, expected_neither) - def test_years_only(self): - # GH 6961 - dr = date_range("2014", "2015", freq="ME") - assert dr[0] == datetime(2014, 1, 31) - assert dr[-1] == datetime(2014, 12, 31) + def test_date_range_years_only(self, tz_naive_fixture): + tz = tz_naive_fixture + # GH#6961 + rng1 = date_range("2014", "2015", freq="ME", tz=tz) + expected1 = date_range("2014-01-31", "2014-12-31", freq="ME", tz=tz) + tm.assert_index_equal(rng1, expected1) + + rng2 = date_range("2014", "2015", freq="MS", tz=tz) + expected2 = date_range("2014-01-01", "2015-01-01", freq="MS", tz=tz) + tm.assert_index_equal(rng2, expected2) + + rng3 = date_range("2014", "2020", freq="Y", tz=tz) + expected3 = date_range("2014-12-31", "2019-12-31", freq="Y", tz=tz) + tm.assert_index_equal(rng3, expected3) + + rng4 = date_range("2014", "2020", freq="YS", tz=tz) + expected4 = date_range("2014-01-01", "2020-01-01", freq="YS", tz=tz) + tm.assert_index_equal(rng4, expected4) def test_freq_divides_end_in_nanos(self): # GH 10885 @@ -871,6 +888,33 @@ def test_frequencies_A_T_S_L_U_N_deprecated(self, freq, freq_depr): result = date_range("1/1/2000", periods=2, freq=freq_depr) tm.assert_index_equal(result, expected) + def test_date_range_misc(self): + sdate = datetime(1999, 12, 25) + edate = datetime(2000, 1, 1) + idx = date_range(start=sdate, freq="1B", periods=20) + assert len(idx) == 20 + assert idx[0] == sdate + 0 * offsets.BDay() + assert idx.freq == "B" + + idx1 = date_range(start=sdate, end=edate, freq="W-SUN") + idx2 = date_range(start=sdate, end=edate, freq=offsets.Week(weekday=6)) + assert len(idx1) == len(idx2) + assert idx1.freq == idx2.freq + + idx1 = date_range(start=sdate, end=edate, freq="QS") + idx2 = date_range( + start=sdate, end=edate, freq=offsets.QuarterBegin(startingMonth=1) + ) + assert len(idx1) == len(idx2) + assert idx1.freq == idx2.freq + + idx1 = date_range(start=sdate, end=edate, freq="BQ") + idx2 = date_range( + start=sdate, end=edate, freq=offsets.BQuarterEnd(startingMonth=12) + ) + assert len(idx1) == len(idx2) + assert idx1.freq == idx2.freq + class TestDateRangeTZ: """Tests for date_range with timezones""" @@ -904,9 +948,20 @@ def test_date_range_timezone_str_argument(self, tzstr): tm.assert_index_equal(result, expected) - def test_date_range_with_fixedoffset_noname(self): - from pandas.tests.indexes.datetimes.test_timezones import fixed_off_no_name + def test_date_range_with_fixed_tz(self): + off = FixedOffset(420, "+07:00") + start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off) + end = datetime(2012, 6, 11, 5, 0, 0, tzinfo=off) + rng = date_range(start=start, end=end) + assert off == rng.tz + + rng2 = date_range(start, periods=len(rng), tz=off) + tm.assert_index_equal(rng, rng2) + rng3 = date_range("3/11/2012 05:00:00+07:00", "6/11/2012 05:00:00+07:00") + assert (rng.values == rng3.values).all() + + def test_date_range_with_fixedoffset_noname(self): off = fixed_off_no_name start = datetime(2012, 3, 11, 5, 0, 0, tzinfo=off) end = datetime(2012, 6, 11, 5, 0, 0, tzinfo=off) diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 89c4433db1c7b..a1074a1744c7a 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -20,6 +20,12 @@ class TestDatetimeIndex: + def test_is_(self): + dti = date_range(start="1/1/2005", end="12/1/2005", freq="ME") + assert dti.is_(dti) + assert dti.is_(dti.view()) + assert not dti.is_(dti.copy()) + def test_time_overflow_for_32bit_machines(self): # GH8943. On some machines NumPy defaults to np.int32 (for example, # 32-bit Linux machines). In the function _generate_regular_range diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index acb0f85027da2..bfbffb4c97e3d 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -358,6 +358,15 @@ def test_pass_timedeltaindex_to_index(self): tm.assert_numpy_array_equal(idx.values, expected.values) + def test_pass_datetimeindex_to_index(self): + # GH#1396 + rng = date_range("1/1/2000", "3/1/2000") + idx = Index(rng, dtype=object) + + expected = Index(rng.to_pydatetime(), dtype=object) + + tm.assert_numpy_array_equal(idx.values, expected.values) + class TestIndexConstructorUnwrapping: # Test passing different arraylike values to pd.Index diff --git a/pandas/tests/libs/test_libalgos.py b/pandas/tests/libs/test_libalgos.py new file mode 100644 index 0000000000000..42d09c72aab2b --- /dev/null +++ b/pandas/tests/libs/test_libalgos.py @@ -0,0 +1,162 @@ +from datetime import datetime +from itertools import permutations + +import numpy as np + +from pandas._libs import algos as libalgos + +import pandas._testing as tm + + +def test_ensure_platform_int(): + arr = np.arange(100, dtype=np.intp) + + result = libalgos.ensure_platform_int(arr) + assert result is arr + + +def test_is_lexsorted(): + failure = [ + np.array( + ([3] * 32) + ([2] * 32) + ([1] * 32) + ([0] * 32), + dtype="int64", + ), + np.array( + list(range(31))[::-1] * 4, + dtype="int64", + ), + ] + + assert not libalgos.is_lexsorted(failure) + + +def test_groupsort_indexer(): + a = np.random.default_rng(2).integers(0, 1000, 100).astype(np.intp) + b = np.random.default_rng(2).integers(0, 1000, 100).astype(np.intp) + + result = libalgos.groupsort_indexer(a, 1000)[0] + + # need to use a stable sort + # np.argsort returns int, groupsort_indexer + # always returns intp + expected = np.argsort(a, kind="mergesort") + expected = expected.astype(np.intp) + + tm.assert_numpy_array_equal(result, expected) + + # compare with lexsort + # np.lexsort returns int, groupsort_indexer + # always returns intp + key = a * 1000 + b + result = libalgos.groupsort_indexer(key, 1000000)[0] + expected = np.lexsort((b, a)) + expected = expected.astype(np.intp) + + tm.assert_numpy_array_equal(result, expected) + + +class TestPadBackfill: + def test_backfill(self): + old = np.array([1, 5, 10], dtype=np.int64) + new = np.array(list(range(12)), dtype=np.int64) + + filler = libalgos.backfill["int64_t"](old, new) + + expect_filler = np.array([0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, -1], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + # corner case + old = np.array([1, 4], dtype=np.int64) + new = np.array(list(range(5, 10)), dtype=np.int64) + filler = libalgos.backfill["int64_t"](old, new) + + expect_filler = np.array([-1, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + def test_pad(self): + old = np.array([1, 5, 10], dtype=np.int64) + new = np.array(list(range(12)), dtype=np.int64) + + filler = libalgos.pad["int64_t"](old, new) + + expect_filler = np.array([-1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + # corner case + old = np.array([5, 10], dtype=np.int64) + new = np.arange(5, dtype=np.int64) + filler = libalgos.pad["int64_t"](old, new) + expect_filler = np.array([-1, -1, -1, -1, -1], dtype=np.intp) + tm.assert_numpy_array_equal(filler, expect_filler) + + def test_pad_backfill_object_segfault(self): + old = np.array([], dtype="O") + new = np.array([datetime(2010, 12, 31)], dtype="O") + + result = libalgos.pad["object"](old, new) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = libalgos.pad["object"](new, old) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = libalgos.backfill["object"](old, new) + expected = np.array([-1], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + result = libalgos.backfill["object"](new, old) + expected = np.array([], dtype=np.intp) + tm.assert_numpy_array_equal(result, expected) + + +class TestInfinity: + def test_infinity_sort(self): + # GH#13445 + # numpy's argsort can be unhappy if something is less than + # itself. Instead, let's give our infinities a self-consistent + # ordering, but outside the float extended real line. + + Inf = libalgos.Infinity() + NegInf = libalgos.NegInfinity() + + ref_nums = [NegInf, float("-inf"), -1e100, 0, 1e100, float("inf"), Inf] + + assert all(Inf >= x for x in ref_nums) + assert all(Inf > x or x is Inf for x in ref_nums) + assert Inf >= Inf and Inf == Inf + assert not Inf < Inf and not Inf > Inf + assert libalgos.Infinity() == libalgos.Infinity() + assert not libalgos.Infinity() != libalgos.Infinity() + + assert all(NegInf <= x for x in ref_nums) + assert all(NegInf < x or x is NegInf for x in ref_nums) + assert NegInf <= NegInf and NegInf == NegInf + assert not NegInf < NegInf and not NegInf > NegInf + assert libalgos.NegInfinity() == libalgos.NegInfinity() + assert not libalgos.NegInfinity() != libalgos.NegInfinity() + + for perm in permutations(ref_nums): + assert sorted(perm) == ref_nums + + # smoke tests + np.array([libalgos.Infinity()] * 32).argsort() + np.array([libalgos.NegInfinity()] * 32).argsort() + + def test_infinity_against_nan(self): + Inf = libalgos.Infinity() + NegInf = libalgos.NegInfinity() + + assert not Inf > np.nan + assert not Inf >= np.nan + assert not Inf < np.nan + assert not Inf <= np.nan + assert not Inf == np.nan + assert Inf != np.nan + + assert not NegInf > np.nan + assert not NegInf >= np.nan + assert not NegInf < np.nan + assert not NegInf <= np.nan + assert not NegInf == np.nan + assert NegInf != np.nan diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_formats.py similarity index 100% rename from pandas/tests/series/test_repr.py rename to pandas/tests/series/test_formats.py diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index a6d7bcb47fbb2..e1a78136935db 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -1,5 +1,4 @@ from datetime import datetime -from itertools import permutations import struct import numpy as np @@ -956,14 +955,7 @@ def test_isin_datetimelike_values_numeric_comps(self, dtype, dtype1): # Anything but object and we get all-False shortcut dta = date_range("2013-01-01", periods=3)._values - if dtype1 == "period[D]": - # TODO: fix Series.view to get this on its own - arr = dta.to_period("D") - elif dtype1 == "M8[ns, UTC]": - # TODO: fix Series.view to get this on its own - arr = dta.tz_localize("UTC") - else: - arr = Series(dta.view("i8")).view(dtype1)._values + arr = Series(dta.view("i8")).view(dtype1)._values comps = arr.view("i8").astype(dtype) @@ -1216,17 +1208,22 @@ def test_value_counts_nat(self): msg = "pandas.value_counts is deprecated" - for s in [td, dt]: + for ser in [td, dt]: with tm.assert_produces_warning(FutureWarning, match=msg): - vc = algos.value_counts(s) - vc_with_na = algos.value_counts(s, dropna=False) + vc = algos.value_counts(ser) + vc_with_na = algos.value_counts(ser, dropna=False) assert len(vc) == 1 assert len(vc_with_na) == 2 exp_dt = Series({Timestamp("2014-01-01 00:00:00"): 1}, name="count") with tm.assert_produces_warning(FutureWarning, match=msg): - tm.assert_series_equal(algos.value_counts(dt), exp_dt) - # TODO same for (timedelta) + result_dt = algos.value_counts(dt) + tm.assert_series_equal(result_dt, exp_dt) + + exp_td = Series({np.timedelta64(10000): 1}, name="count") + with tm.assert_produces_warning(FutureWarning, match=msg): + result_td = algos.value_counts(td) + tm.assert_series_equal(result_td, exp_td) def test_value_counts_datetime_outofbounds(self): # GH 13663 @@ -1249,13 +1246,6 @@ def test_value_counts_datetime_outofbounds(self): exp = Series([3, 2, 1], index=exp_index, name="count") tm.assert_series_equal(res, exp) - # GH 12424 # TODO: belongs elsewhere - msg = "errors='ignore' is deprecated" - with tm.assert_produces_warning(FutureWarning, match=msg): - res = to_datetime(Series(["2362-01-01", np.nan]), errors="ignore") - exp = Series(["2362-01-01", np.nan], dtype=object) - tm.assert_series_equal(res, exp) - def test_categorical(self): s = Series(Categorical(list("aaabbc"))) result = s.value_counts() @@ -1787,161 +1777,6 @@ def test_pct_max_many_rows(self): assert result == 1 -def test_pad_backfill_object_segfault(): - old = np.array([], dtype="O") - new = np.array([datetime(2010, 12, 31)], dtype="O") - - result = libalgos.pad["object"](old, new) - expected = np.array([-1], dtype=np.intp) - tm.assert_numpy_array_equal(result, expected) - - result = libalgos.pad["object"](new, old) - expected = np.array([], dtype=np.intp) - tm.assert_numpy_array_equal(result, expected) - - result = libalgos.backfill["object"](old, new) - expected = np.array([-1], dtype=np.intp) - tm.assert_numpy_array_equal(result, expected) - - result = libalgos.backfill["object"](new, old) - expected = np.array([], dtype=np.intp) - tm.assert_numpy_array_equal(result, expected) - - -class TestTseriesUtil: - def test_backfill(self): - old = Index([1, 5, 10]) - new = Index(list(range(12))) - - filler = libalgos.backfill["int64_t"](old.values, new.values) - - expect_filler = np.array([0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, -1], dtype=np.intp) - tm.assert_numpy_array_equal(filler, expect_filler) - - # corner case - old = Index([1, 4]) - new = Index(list(range(5, 10))) - filler = libalgos.backfill["int64_t"](old.values, new.values) - - expect_filler = np.array([-1, -1, -1, -1, -1], dtype=np.intp) - tm.assert_numpy_array_equal(filler, expect_filler) - - def test_pad(self): - old = Index([1, 5, 10]) - new = Index(list(range(12))) - - filler = libalgos.pad["int64_t"](old.values, new.values) - - expect_filler = np.array([-1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2], dtype=np.intp) - tm.assert_numpy_array_equal(filler, expect_filler) - - # corner case - old = Index([5, 10]) - new = Index(np.arange(5, dtype=np.int64)) - filler = libalgos.pad["int64_t"](old.values, new.values) - expect_filler = np.array([-1, -1, -1, -1, -1], dtype=np.intp) - tm.assert_numpy_array_equal(filler, expect_filler) - - -def test_is_lexsorted(): - failure = [ - np.array( - ([3] * 32) + ([2] * 32) + ([1] * 32) + ([0] * 32), - dtype="int64", - ), - np.array( - list(range(31))[::-1] * 4, - dtype="int64", - ), - ] - - assert not libalgos.is_lexsorted(failure) - - -def test_groupsort_indexer(): - a = np.random.default_rng(2).integers(0, 1000, 100).astype(np.intp) - b = np.random.default_rng(2).integers(0, 1000, 100).astype(np.intp) - - result = libalgos.groupsort_indexer(a, 1000)[0] - - # need to use a stable sort - # np.argsort returns int, groupsort_indexer - # always returns intp - expected = np.argsort(a, kind="mergesort") - expected = expected.astype(np.intp) - - tm.assert_numpy_array_equal(result, expected) - - # compare with lexsort - # np.lexsort returns int, groupsort_indexer - # always returns intp - key = a * 1000 + b - result = libalgos.groupsort_indexer(key, 1000000)[0] - expected = np.lexsort((b, a)) - expected = expected.astype(np.intp) - - tm.assert_numpy_array_equal(result, expected) - - -def test_infinity_sort(): - # GH 13445 - # numpy's argsort can be unhappy if something is less than - # itself. Instead, let's give our infinities a self-consistent - # ordering, but outside the float extended real line. - - Inf = libalgos.Infinity() - NegInf = libalgos.NegInfinity() - - ref_nums = [NegInf, float("-inf"), -1e100, 0, 1e100, float("inf"), Inf] - - assert all(Inf >= x for x in ref_nums) - assert all(Inf > x or x is Inf for x in ref_nums) - assert Inf >= Inf and Inf == Inf - assert not Inf < Inf and not Inf > Inf - assert libalgos.Infinity() == libalgos.Infinity() - assert not libalgos.Infinity() != libalgos.Infinity() - - assert all(NegInf <= x for x in ref_nums) - assert all(NegInf < x or x is NegInf for x in ref_nums) - assert NegInf <= NegInf and NegInf == NegInf - assert not NegInf < NegInf and not NegInf > NegInf - assert libalgos.NegInfinity() == libalgos.NegInfinity() - assert not libalgos.NegInfinity() != libalgos.NegInfinity() - - for perm in permutations(ref_nums): - assert sorted(perm) == ref_nums - - # smoke tests - np.array([libalgos.Infinity()] * 32).argsort() - np.array([libalgos.NegInfinity()] * 32).argsort() - - -def test_infinity_against_nan(): - Inf = libalgos.Infinity() - NegInf = libalgos.NegInfinity() - - assert not Inf > np.nan - assert not Inf >= np.nan - assert not Inf < np.nan - assert not Inf <= np.nan - assert not Inf == np.nan - assert Inf != np.nan - - assert not NegInf > np.nan - assert not NegInf >= np.nan - assert not NegInf < np.nan - assert not NegInf <= np.nan - assert not NegInf == np.nan - assert NegInf != np.nan - - -def test_ensure_platform_int(): - arr = np.arange(100, dtype=np.intp) - - result = libalgos.ensure_platform_int(arr) - assert result is arr - - def test_int64_add_overflow(): # see gh-14068 msg = "Overflow in int64 addition" diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index ae07cb00211a2..0ea8da89f2716 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1202,6 +1202,14 @@ def test_out_of_bounds_errors_ignore(self): expected = np.datetime64("9999-01-01") assert result == expected + def test_out_of_bounds_errors_ignore2(self): + # GH#12424 + msg = "errors='ignore' is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = to_datetime(Series(["2362-01-01", np.nan]), errors="ignore") + exp = Series(["2362-01-01", np.nan], dtype=object) + tm.assert_series_equal(res, exp) + def test_to_datetime_tz(self, cache): # xref 8260 # uniform returns a DatetimeIndex @@ -2038,7 +2046,6 @@ def test_to_datetime_errors_ignore_utc_true(self): expected = DatetimeIndex(["1970-01-01 00:00:01"], tz="UTC") tm.assert_index_equal(result, expected) - # TODO: this is moved from tests.series.test_timeseries, may be redundant @pytest.mark.parametrize("dtype", [int, float]) def test_to_datetime_unit(self, dtype): epoch = 1370745748
- [ ] 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/55870
2023-11-07T19:35:05Z
2023-11-07T21:36:58Z
2023-11-07T21:36:58Z
2023-11-07T22:31:02Z