Skip to content

Commit 93659e8

Browse files
committed
Warn for float dtype
1 parent c625ebb commit 93659e8

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pandas/core/arrays/categorical.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
is_timedelta64_dtype,
2828
is_categorical,
2929
is_categorical_dtype,
30+
is_float_dtype,
3031
is_integer_dtype,
3132
is_list_like, is_sequence,
3233
is_scalar, is_iterator,
@@ -632,7 +633,19 @@ def from_codes(cls, codes, categories, ordered=False):
632633
"""
633634
codes = np.asarray(codes)
634635
if not is_integer_dtype(codes):
635-
raise ValueError("codes need to be array-like integers")
636+
err = True
637+
if is_float_dtype(codes):
638+
icodes = codes.astype('i8')
639+
if (icodes == codes).all():
640+
err = False
641+
codes = icodes
642+
warn("float codes will be disallowed in the future",
643+
FutureWarning)
644+
else:
645+
err = True
646+
if err:
647+
raise ValueError("codes need to be array-like integers")
648+
636649
try:
637650
codes = coerce_indexer_dtype(codes, categories)
638651
except (ValueError, TypeError):

pandas/tests/arrays/categorical/test_constructors.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import pytest
44
from datetime import datetime
5+
import warnings
56

67
import numpy as np
78

@@ -475,6 +476,15 @@ def test_from_codes_with_nan_code(self):
475476
with pytest.raises(ValueError):
476477
Categorical.from_codes(codes, categories)
477478

479+
def test_from_codes_with_float(self):
480+
# GH21767
481+
codes = [1.0, 2.0, 0]
482+
categories = ['a', 'b', 'c']
483+
with warnings.catch_warnings(record=True) as w:
484+
Categorical.from_codes(codes, categories)
485+
486+
assert len(w) == 1
487+
478488
@pytest.mark.parametrize('dtype', [None, 'category'])
479489
def test_from_inferred_categories(self, dtype):
480490
cats = ['a', 'b']

0 commit comments

Comments
 (0)