Skip to content

Backport PR #36613 on branch 1.1.x (BUG: Fix unordered cut with Series labels) #36633

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Bug fixes
- Bug in :meth:`DataFrame.stack` raising a ``ValueError`` when stacking :class:`MultiIndex` columns based on position when the levels had duplicate names (:issue:`36353`)
- Bug in :meth:`Series.astype` showing too much precision when casting from ``np.float32`` to string dtype (:issue:`36451`)
- Bug in :meth:`Series.isin` and :meth:`DataFrame.isin` when using ``NaN`` and a row length above 1,000,000 (:issue:`22205`)
- Bug in :func:`cut` raising a ``ValueError`` when passed a :class:`Series` of labels with ``ordered=False`` (:issue:`36603`)

.. ---------------------------------------------------------------------------

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/reshape/tile.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ def _bins_to_cuts(
duplicates: str = "raise",
ordered: bool = True,
):
if not ordered and not labels:
if not ordered and labels is None:
raise ValueError("'labels' must be provided if 'ordered = False'")

if duplicates not in ["raise", "drop"]:
Expand Down
10 changes: 10 additions & 0 deletions pandas/tests/reshape/test_cut.py
Original file line number Diff line number Diff line change
Expand Up @@ -664,3 +664,13 @@ def test_cut_unordered_with_missing_labels_raises_error():
msg = "'labels' must be provided if 'ordered = False'"
with pytest.raises(ValueError, match=msg):
cut([0.5, 3], bins=[0, 1, 2], ordered=False)


def test_cut_unordered_with_series_labels():
# https://github.com/pandas-dev/pandas/issues/36603
s = pd.Series([1, 2, 3, 4, 5])
bins = pd.Series([0, 2, 4, 6])
labels = pd.Series(["a", "b", "c"])
result = pd.cut(s, bins=bins, labels=labels, ordered=False)
expected = pd.Series(["a", "a", "b", "b", "c"], dtype="category")
tm.assert_series_equal(result, expected)