Skip to content

Commit a95fc1f

Browse files
committed
Add NaN check to Categorical.from_codes
1 parent 3be3254 commit a95fc1f

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
@@ -628,6 +628,8 @@ def from_codes(cls, codes, categories, ordered=False):
628628
categorical. If not given, the resulting categorical will be
629629
unordered.
630630
"""
631+
if isna(codes).any():
632+
raise ValueError("nan is not a valid code. Use -1")
631633
try:
632634
codes = coerce_indexer_dtype(np.asarray(codes), categories)
633635
except (ValueError, TypeError):

pandas/tests/categorical/test_constructors.py

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

467+
def test_from_codes_with_nan_code(self):
468+
# GH21767
469+
codes = [1, 2, np.nan]
470+
categories = ['a', 'b', 'c']
471+
with pytest.raises(ValueError,
472+
match='nan is not a valid code. Use -1'):
473+
Categorical.from_codes(codes, categories)
474+
467475
@pytest.mark.parametrize('dtype', [None, 'category'])
468476
def test_from_inferred_categories(self, dtype):
469477
cats = ['a', 'b']

0 commit comments

Comments
 (0)