Skip to content

Commit 355ffd7

Browse files
committed
Add NaN check to Categorical.from_codes
1 parent 26b3e7d commit 355ffd7

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

pandas/core/arrays/categorical.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -629,6 +629,8 @@ def from_codes(cls, codes, categories, ordered=False):
629629
categorical. If not given, the resulting categorical will be
630630
unordered.
631631
"""
632+
if isna(codes).any():
633+
raise ValueError("nan is not a valid code. Use -1")
632634
try:
633635
codes = coerce_indexer_dtype(np.asarray(codes), categories)
634636
except (ValueError, TypeError):

pandas/tests/arrays/categorical/test_constructors.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,14 @@ def test_from_codes_with_categorical_categories(self):
468468
with pytest.raises(ValueError):
469469
Categorical.from_codes([0, 1], Categorical(['a', 'b', 'a']))
470470

471+
def test_from_codes_with_nan_code(self):
472+
# GH21767
473+
codes = [1, 2, np.nan]
474+
categories = ['a', 'b', 'c']
475+
with pytest.raises(ValueError,
476+
match='nan is not a valid code. Use -1'):
477+
Categorical.from_codes(codes, categories)
478+
471479
@pytest.mark.parametrize('dtype', [None, 'category'])
472480
def test_from_inferred_categories(self, dtype):
473481
cats = ['a', 'b']

0 commit comments

Comments
 (0)