Skip to content

Commit 7b42fa4

Browse files
committed
Warn for float dtype
1 parent e88610c commit 7b42fa4

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

pandas/core/arrays/categorical.py

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

pandas/tests/categorical/test_constructors.py

+10
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

@@ -471,6 +472,15 @@ def test_from_codes_with_nan_code(self):
471472
with pytest.raises(ValueError):
472473
Categorical.from_codes(codes, categories)
473474

475+
def test_from_codes_with_float(self):
476+
# GH21767
477+
codes = [1.0, 2.0, 0]
478+
categories = ['a', 'b', 'c']
479+
with warnings.catch_warnings(record=True) as w:
480+
Categorical.from_codes(codes, categories)
481+
482+
assert len(w) == 1
483+
474484
@pytest.mark.parametrize('dtype', [None, 'category'])
475485
def test_from_inferred_categories(self, dtype):
476486
cats = ['a', 'b']

0 commit comments

Comments
 (0)