Skip to content

Commit c625ebb

Browse files
committed
Use pandas is_integer_dtype
1 parent acb00db commit c625ebb

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
@@ -27,6 +27,7 @@
2727
is_timedelta64_dtype,
2828
is_categorical,
2929
is_categorical_dtype,
30+
is_integer_dtype,
3031
is_list_like, is_sequence,
3132
is_scalar, is_iterator,
3233
is_dict_like)
@@ -629,10 +630,11 @@ def from_codes(cls, codes, categories, ordered=False):
629630
categorical. If not given, the resulting categorical will be
630631
unordered.
631632
"""
632-
if isna(codes).any():
633-
raise ValueError("nan is not a valid code. Use -1")
633+
codes = np.asarray(codes)
634+
if not is_integer_dtype(codes):
635+
raise ValueError("codes need to be array-like integers")
634636
try:
635-
codes = coerce_indexer_dtype(np.asarray(codes), categories)
637+
codes = coerce_indexer_dtype(codes, categories)
636638
except (ValueError, TypeError):
637639
raise ValueError(
638640
"codes need to be convertible to an arrays of integers")

pandas/tests/arrays/categorical/test_constructors.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -472,8 +472,7 @@ def test_from_codes_with_nan_code(self):
472472
# GH21767
473473
codes = [1, 2, np.nan]
474474
categories = ['a', 'b', 'c']
475-
with pytest.raises(ValueError,
476-
match='nan is not a valid code. Use -1'):
475+
with pytest.raises(ValueError):
477476
Categorical.from_codes(codes, categories)
478477

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

0 commit comments

Comments
 (0)