test_unary.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import operator
  2. import numpy as np
  3. import pytest
  4. import pandas as pd
  5. import pandas._testing as tm
  6. from pandas.core.arrays import SparseArray
  7. @pytest.mark.parametrize("fill_value", [0, np.nan])
  8. @pytest.mark.parametrize("op", [operator.pos, operator.neg])
  9. def test_unary_op(op, fill_value):
  10. arr = np.array([0, 1, np.nan, 2])
  11. sparray = SparseArray(arr, fill_value=fill_value)
  12. result = op(sparray)
  13. expected = SparseArray(op(arr), fill_value=op(fill_value))
  14. tm.assert_sp_array_equal(result, expected)
  15. @pytest.mark.parametrize("fill_value", [True, False])
  16. def test_invert(fill_value):
  17. arr = np.array([True, False, False, True])
  18. sparray = SparseArray(arr, fill_value=fill_value)
  19. result = ~sparray
  20. expected = SparseArray(~arr, fill_value=not fill_value)
  21. tm.assert_sp_array_equal(result, expected)
  22. result = ~pd.Series(sparray)
  23. expected = pd.Series(expected)
  24. tm.assert_series_equal(result, expected)
  25. result = ~pd.DataFrame({"A": sparray})
  26. expected = pd.DataFrame({"A": expected})
  27. tm.assert_frame_equal(result, expected)
  28. class TestUnaryMethods:
  29. def test_neg_operator(self):
  30. arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8)
  31. res = -arr
  32. exp = SparseArray([1, 2, np.nan, -3], fill_value=np.nan, dtype=np.int8)
  33. tm.assert_sp_array_equal(exp, res)
  34. arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8)
  35. res = -arr
  36. exp = SparseArray([1, 2, -1, -3], fill_value=1, dtype=np.int8)
  37. tm.assert_sp_array_equal(exp, res)
  38. def test_abs_operator(self):
  39. arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8)
  40. res = abs(arr)
  41. exp = SparseArray([1, 2, np.nan, 3], fill_value=np.nan, dtype=np.int8)
  42. tm.assert_sp_array_equal(exp, res)
  43. arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8)
  44. res = abs(arr)
  45. exp = SparseArray([1, 2, 1, 3], fill_value=1, dtype=np.int8)
  46. tm.assert_sp_array_equal(exp, res)
  47. def test_invert_operator(self):
  48. arr = SparseArray([False, True, False, True], fill_value=False, dtype=np.bool_)
  49. exp = SparseArray(
  50. np.invert([False, True, False, True]), fill_value=True, dtype=np.bool_
  51. )
  52. res = ~arr
  53. tm.assert_sp_array_equal(exp, res)
  54. arr = SparseArray([0, 1, 0, 2, 3, 0], fill_value=0, dtype=np.int32)
  55. res = ~arr
  56. exp = SparseArray([-1, -2, -1, -3, -4, -1], fill_value=-1, dtype=np.int32)
  57. tm.assert_sp_array_equal(exp, res)