test_fillna.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import numpy as np
  2. import pytest
  3. from pandas import CategoricalIndex
  4. import pandas._testing as tm
  5. class TestFillNA:
  6. def test_fillna_categorical(self):
  7. # GH#11343
  8. idx = CategoricalIndex([1.0, np.nan, 3.0, 1.0], name="x")
  9. # fill by value in categories
  10. exp = CategoricalIndex([1.0, 1.0, 3.0, 1.0], name="x")
  11. tm.assert_index_equal(idx.fillna(1.0), exp)
  12. cat = idx._data
  13. # fill by value not in categories raises TypeError on EA, casts on CI
  14. msg = "Cannot setitem on a Categorical with a new category"
  15. with pytest.raises(TypeError, match=msg):
  16. cat.fillna(2.0)
  17. result = idx.fillna(2.0)
  18. expected = idx.astype(object).fillna(2.0)
  19. tm.assert_index_equal(result, expected)
  20. def test_fillna_copies_with_no_nas(self):
  21. # Nothing to fill, should still get a copy for the Categorical method,
  22. # but OK to get a view on CategoricalIndex method
  23. ci = CategoricalIndex([0, 1, 1])
  24. result = ci.fillna(0)
  25. assert result is not ci
  26. assert tm.shares_memory(result, ci)
  27. # But at the EA level we always get a copy.
  28. cat = ci._data
  29. result = cat.fillna(0)
  30. assert result._ndarray is not cat._ndarray
  31. assert result._ndarray.base is None
  32. assert not tm.shares_memory(result, cat)
  33. def test_fillna_validates_with_no_nas(self):
  34. # We validate the fill value even if fillna is a no-op
  35. ci = CategoricalIndex([2, 3, 3])
  36. cat = ci._data
  37. msg = "Cannot setitem on a Categorical with a new category"
  38. res = ci.fillna(False)
  39. # nothing to fill, so we dont cast
  40. tm.assert_index_equal(res, ci)
  41. # Same check directly on the Categorical
  42. with pytest.raises(TypeError, match=msg):
  43. cat.fillna(False)