Skip to content

Commit e88610c

Browse files
committed
Use pandas is_integer_dtype
1 parent 58a7c68 commit e88610c

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

pandas/core/arrays/categorical.py

Lines changed: 5 additions & 3 deletions
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_integer_dtype,
2930
is_list_like, is_sequence,
3031
is_scalar, is_iterator,
3132
is_dict_like)
@@ -628,10 +629,11 @@ def from_codes(cls, codes, categories, ordered=False):
628629
categorical. If not given, the resulting categorical will be
629630
unordered.
630631
"""
631-
if isna(codes).any():
632-
raise ValueError("nan is not a valid code. Use -1")
632+
codes = np.asarray(codes)
633+
if not is_integer_dtype(codes):
634+
raise ValueError("codes need to be array-like integers")
633635
try:
634-
codes = coerce_indexer_dtype(np.asarray(codes), categories)
636+
codes = coerce_indexer_dtype(codes, categories)
635637
except (ValueError, TypeError):
636638
raise ValueError(
637639
"codes need to be convertible to an arrays of integers")

pandas/tests/categorical/test_constructors.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -468,8 +468,7 @@ def test_from_codes_with_nan_code(self):
468468
# GH21767
469469
codes = [1, 2, np.nan]
470470
categories = ['a', 'b', 'c']
471-
with pytest.raises(ValueError,
472-
match='nan is not a valid code. Use -1'):
471+
with pytest.raises(ValueError):
473472
Categorical.from_codes(codes, categories)
474473

475474
@pytest.mark.parametrize('dtype', [None, 'category'])

0 commit comments

Comments
 (0)