Skip to content

Commit d419be4

Browse files
economyjreback
authored andcommitted
BUG: fixed wrong order of ordered labels in pd.cut()
closes #16459 Author: economy <[email protected]> This patch had conflicts when merged, resolved by Committer: Jeff Reback <[email protected]> Closes #16466 from economy/fix_cut and squashes the following commits: 29128b3 [economy] comments and whatsnew edits 3898b72 [economy] BUG: fixed wrong order of ordered labels in pd.cut()
1 parent e3ee186 commit d419be4

File tree

3 files changed

+10
-4
lines changed

3 files changed

+10
-4
lines changed

doc/source/whatsnew/v0.20.2.txt

+1-3
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,9 @@ Bug Fixes
4646
- Passing an invalid engine to :func:`read_csv` now raises an informative
4747
``ValueError`` rather than ``UnboundLocalError``. (:issue:`16511`)
4848
- Bug in :func:`unique` on an array of tuples (:issue:`16519`)
49-
50-
49+
- Bug in :func:`cut`` when ``labels`` are set, resulting in incorrect label ordering (:issue:`16459`)
5150
- Fixed a compatibility issue with IPython 6.0's tab completion showing deprecation warnings on Categoricals (:issue:`16409`)
5251

53-
5452
Conversion
5553
^^^^^^^^^^
5654

pandas/core/reshape/tile.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ def _bins_to_cuts(x, bins, right=True, labels=None,
254254
raise ValueError('Bin labels must be one fewer than '
255255
'the number of bin edges')
256256
if not is_categorical_dtype(labels):
257-
labels = Categorical(labels, ordered=True)
257+
labels = Categorical(labels, categories=labels, ordered=True)
258258

259259
np.putmask(ids, na_mask, 0)
260260
result = algos.take_nd(labels, ids - 1)

pandas/tests/reshape/test_tile.py

+8
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,7 @@ def test_cut_pass_labels(self):
211211

212212
result = cut(arr, bins, labels=labels)
213213
exp = Categorical(['Medium'] + 4 * ['Small'] + ['Medium', 'Large'],
214+
categories=labels,
214215
ordered=True)
215216
tm.assert_categorical_equal(result, exp)
216217

@@ -219,6 +220,13 @@ def test_cut_pass_labels(self):
219220
exp = Categorical.from_codes([1] + 4 * [0] + [1, 2], labels)
220221
tm.assert_categorical_equal(result, exp)
221222

223+
# issue 16459
224+
labels = ['Good', 'Medium', 'Bad']
225+
result = cut(arr, 3, labels=labels)
226+
exp = cut(arr, 3, labels=Categorical(labels, categories=labels,
227+
ordered=True))
228+
tm.assert_categorical_equal(result, exp)
229+
222230
def test_qcut_include_lowest(self):
223231
values = np.arange(10)
224232

0 commit comments

Comments
 (0)