test_numpy.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. """
  2. This file contains a minimal set of tests for compliance with the extension
  3. array interface test suite, and should contain no other tests.
  4. The test suite for the full functionality of the array is located in
  5. `pandas/tests/arrays/`.
  6. The tests in this file are inherited from the BaseExtensionTests, and only
  7. minimal tweaks should be applied to get the tests passing (by overwriting a
  8. parent method).
  9. Additional tests should either be added to one of the BaseExtensionTests
  10. classes (if they are relevant for the extension interface for all dtypes), or
  11. be added to the array-specific tests in `pandas/tests/arrays/`.
  12. Note: we do not bother with base.BaseIndexTests because NumpyExtensionArray
  13. will never be held in an Index.
  14. """
  15. import numpy as np
  16. import pytest
  17. from pandas.core.dtypes.dtypes import NumpyEADtype
  18. import pandas as pd
  19. import pandas._testing as tm
  20. from pandas.api.types import is_object_dtype
  21. from pandas.core.arrays.numpy_ import NumpyExtensionArray
  22. from pandas.tests.extension import base
  23. orig_assert_attr_equal = tm.assert_attr_equal
  24. def _assert_attr_equal(attr: str, left, right, obj: str = "Attributes"):
  25. """
  26. patch tm.assert_attr_equal so NumpyEADtype("object") is closed enough to
  27. np.dtype("object")
  28. """
  29. if attr == "dtype":
  30. lattr = getattr(left, "dtype", None)
  31. rattr = getattr(right, "dtype", None)
  32. if isinstance(lattr, NumpyEADtype) and not isinstance(rattr, NumpyEADtype):
  33. left = left.astype(lattr.numpy_dtype)
  34. elif isinstance(rattr, NumpyEADtype) and not isinstance(lattr, NumpyEADtype):
  35. right = right.astype(rattr.numpy_dtype)
  36. orig_assert_attr_equal(attr, left, right, obj)
  37. @pytest.fixture(params=["float", "object"])
  38. def dtype(request):
  39. return NumpyEADtype(np.dtype(request.param))
  40. @pytest.fixture
  41. def allow_in_pandas(monkeypatch):
  42. """
  43. A monkeypatch to tells pandas to let us in.
  44. By default, passing a NumpyExtensionArray to an index / series / frame
  45. constructor will unbox that NumpyExtensionArray to an ndarray, and treat
  46. it as a non-EA column. We don't want people using EAs without
  47. reason.
  48. The mechanism for this is a check against ABCNumpyExtensionArray
  49. in each constructor.
  50. But, for testing, we need to allow them in pandas. So we patch
  51. the _typ of NumpyExtensionArray, so that we evade the ABCNumpyExtensionArray
  52. check.
  53. """
  54. with monkeypatch.context() as m:
  55. m.setattr(NumpyExtensionArray, "_typ", "extension")
  56. m.setattr(tm.asserters, "assert_attr_equal", _assert_attr_equal)
  57. yield
  58. @pytest.fixture
  59. def data(allow_in_pandas, dtype):
  60. if dtype.numpy_dtype == "object":
  61. return pd.Series([(i,) for i in range(100)]).array
  62. return NumpyExtensionArray(np.arange(1, 101, dtype=dtype._dtype))
  63. @pytest.fixture
  64. def data_missing(allow_in_pandas, dtype):
  65. if dtype.numpy_dtype == "object":
  66. return NumpyExtensionArray(np.array([np.nan, (1,)], dtype=object))
  67. return NumpyExtensionArray(np.array([np.nan, 1.0]))
  68. @pytest.fixture
  69. def na_cmp():
  70. def cmp(a, b):
  71. return np.isnan(a) and np.isnan(b)
  72. return cmp
  73. @pytest.fixture
  74. def data_for_sorting(allow_in_pandas, dtype):
  75. """Length-3 array with a known sort order.
  76. This should be three items [B, C, A] with
  77. A < B < C
  78. """
  79. if dtype.numpy_dtype == "object":
  80. # Use an empty tuple for first element, then remove,
  81. # to disable np.array's shape inference.
  82. return NumpyExtensionArray(np.array([(), (2,), (3,), (1,)], dtype=object)[1:])
  83. return NumpyExtensionArray(np.array([1, 2, 0]))
  84. @pytest.fixture
  85. def data_missing_for_sorting(allow_in_pandas, dtype):
  86. """Length-3 array with a known sort order.
  87. This should be three items [B, NA, A] with
  88. A < B and NA missing.
  89. """
  90. if dtype.numpy_dtype == "object":
  91. return NumpyExtensionArray(np.array([(1,), np.nan, (0,)], dtype=object))
  92. return NumpyExtensionArray(np.array([1, np.nan, 0]))
  93. @pytest.fixture
  94. def data_for_grouping(allow_in_pandas, dtype):
  95. """Data for factorization, grouping, and unique tests.
  96. Expected to be like [B, B, NA, NA, A, A, B, C]
  97. Where A < B < C and NA is missing
  98. """
  99. if dtype.numpy_dtype == "object":
  100. a, b, c = (1,), (2,), (3,)
  101. else:
  102. a, b, c = np.arange(3)
  103. return NumpyExtensionArray(
  104. np.array([b, b, np.nan, np.nan, a, a, b, c], dtype=dtype.numpy_dtype)
  105. )
  106. @pytest.fixture
  107. def data_for_twos(dtype):
  108. if dtype.kind == "O":
  109. pytest.skip(f"{dtype} is not a numeric dtype")
  110. arr = np.ones(100) * 2
  111. return NumpyExtensionArray._from_sequence(arr, dtype=dtype)
  112. @pytest.fixture
  113. def skip_numpy_object(dtype, request):
  114. """
  115. Tests for NumpyExtensionArray with nested data. Users typically won't create
  116. these objects via `pd.array`, but they can show up through `.array`
  117. on a Series with nested data. Many of the base tests fail, as they aren't
  118. appropriate for nested data.
  119. This fixture allows these tests to be skipped when used as a usefixtures
  120. marker to either an individual test or a test class.
  121. """
  122. if dtype == "object":
  123. mark = pytest.mark.xfail(reason="Fails for object dtype")
  124. request.applymarker(mark)
  125. skip_nested = pytest.mark.usefixtures("skip_numpy_object")
  126. class TestNumpyExtensionArray(base.ExtensionTests):
  127. @pytest.mark.skip(reason="We don't register our dtype")
  128. # We don't want to register. This test should probably be split in two.
  129. def test_from_dtype(self, data):
  130. pass
  131. @skip_nested
  132. def test_series_constructor_scalar_with_index(self, data, dtype):
  133. # ValueError: Length of passed values is 1, index implies 3.
  134. super().test_series_constructor_scalar_with_index(data, dtype)
  135. def test_check_dtype(self, data, request, using_infer_string):
  136. if data.dtype.numpy_dtype == "object":
  137. request.applymarker(
  138. pytest.mark.xfail(
  139. reason=f"NumpyExtensionArray expectedly clashes with a "
  140. f"NumPy name: {data.dtype.numpy_dtype}"
  141. )
  142. )
  143. super().test_check_dtype(data)
  144. def test_is_not_object_type(self, dtype, request):
  145. if dtype.numpy_dtype == "object":
  146. # Different from BaseDtypeTests.test_is_not_object_type
  147. # because NumpyEADtype(object) is an object type
  148. assert is_object_dtype(dtype)
  149. else:
  150. super().test_is_not_object_type(dtype)
  151. @skip_nested
  152. def test_getitem_scalar(self, data):
  153. # AssertionError
  154. super().test_getitem_scalar(data)
  155. @skip_nested
  156. def test_shift_fill_value(self, data):
  157. # np.array shape inference. Shift implementation fails.
  158. super().test_shift_fill_value(data)
  159. @skip_nested
  160. def test_fillna_copy_frame(self, data_missing):
  161. # The "scalar" for this array isn't a scalar.
  162. super().test_fillna_copy_frame(data_missing)
  163. @skip_nested
  164. def test_fillna_copy_series(self, data_missing):
  165. # The "scalar" for this array isn't a scalar.
  166. super().test_fillna_copy_series(data_missing)
  167. @skip_nested
  168. def test_searchsorted(self, data_for_sorting, as_series):
  169. # TODO: NumpyExtensionArray.searchsorted calls ndarray.searchsorted which
  170. # isn't quite what we want in nested data cases. Instead we need to
  171. # adapt something like libindex._bin_search.
  172. super().test_searchsorted(data_for_sorting, as_series)
  173. @pytest.mark.xfail(reason="NumpyExtensionArray.diff may fail on dtype")
  174. def test_diff(self, data, periods):
  175. return super().test_diff(data, periods)
  176. def test_insert(self, data, request):
  177. if data.dtype.numpy_dtype == object:
  178. mark = pytest.mark.xfail(reason="Dimension mismatch in np.concatenate")
  179. request.applymarker(mark)
  180. super().test_insert(data)
  181. @skip_nested
  182. def test_insert_invalid(self, data, invalid_scalar):
  183. # NumpyExtensionArray[object] can hold anything, so skip
  184. super().test_insert_invalid(data, invalid_scalar)
  185. divmod_exc = None
  186. series_scalar_exc = None
  187. frame_scalar_exc = None
  188. series_array_exc = None
  189. def test_divmod(self, data):
  190. divmod_exc = None
  191. if data.dtype.kind == "O":
  192. divmod_exc = TypeError
  193. self.divmod_exc = divmod_exc
  194. super().test_divmod(data)
  195. def test_divmod_series_array(self, data):
  196. ser = pd.Series(data)
  197. exc = None
  198. if data.dtype.kind == "O":
  199. exc = TypeError
  200. self.divmod_exc = exc
  201. self._check_divmod_op(ser, divmod, data)
  202. def test_arith_series_with_scalar(self, data, all_arithmetic_operators, request):
  203. opname = all_arithmetic_operators
  204. series_scalar_exc = None
  205. if data.dtype.numpy_dtype == object:
  206. if opname in ["__mul__", "__rmul__"]:
  207. mark = pytest.mark.xfail(
  208. reason="the Series.combine step raises but not the Series method."
  209. )
  210. request.node.add_marker(mark)
  211. series_scalar_exc = TypeError
  212. self.series_scalar_exc = series_scalar_exc
  213. super().test_arith_series_with_scalar(data, all_arithmetic_operators)
  214. def test_arith_series_with_array(self, data, all_arithmetic_operators):
  215. opname = all_arithmetic_operators
  216. series_array_exc = None
  217. if data.dtype.numpy_dtype == object and opname not in ["__add__", "__radd__"]:
  218. series_array_exc = TypeError
  219. self.series_array_exc = series_array_exc
  220. super().test_arith_series_with_array(data, all_arithmetic_operators)
  221. def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):
  222. opname = all_arithmetic_operators
  223. frame_scalar_exc = None
  224. if data.dtype.numpy_dtype == object:
  225. if opname in ["__mul__", "__rmul__"]:
  226. mark = pytest.mark.xfail(
  227. reason="the Series.combine step raises but not the Series method."
  228. )
  229. request.node.add_marker(mark)
  230. frame_scalar_exc = TypeError
  231. self.frame_scalar_exc = frame_scalar_exc
  232. super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
  233. def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool:
  234. if ser.dtype.kind == "O":
  235. return op_name in ["sum", "min", "max", "any", "all"]
  236. return True
  237. def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
  238. res_op = getattr(ser, op_name)
  239. # avoid coercing int -> float. Just cast to the actual numpy type.
  240. # error: Item "ExtensionDtype" of "dtype[Any] | ExtensionDtype" has
  241. # no attribute "numpy_dtype"
  242. cmp_dtype = ser.dtype.numpy_dtype # type: ignore[union-attr]
  243. alt = ser.astype(cmp_dtype)
  244. exp_op = getattr(alt, op_name)
  245. if op_name == "count":
  246. result = res_op()
  247. expected = exp_op()
  248. else:
  249. result = res_op(skipna=skipna)
  250. expected = exp_op(skipna=skipna)
  251. tm.assert_almost_equal(result, expected)
  252. @pytest.mark.skip("TODO: tests not written yet")
  253. @pytest.mark.parametrize("skipna", [True, False])
  254. def test_reduce_frame(self, data, all_numeric_reductions, skipna):
  255. pass
  256. @skip_nested
  257. def test_fillna_series(self, data_missing):
  258. # Non-scalar "scalar" values.
  259. super().test_fillna_series(data_missing)
  260. @skip_nested
  261. def test_fillna_frame(self, data_missing):
  262. # Non-scalar "scalar" values.
  263. super().test_fillna_frame(data_missing)
  264. @skip_nested
  265. def test_setitem_invalid(self, data, invalid_scalar):
  266. # object dtype can hold anything, so doesn't raise
  267. super().test_setitem_invalid(data, invalid_scalar)
  268. @skip_nested
  269. def test_setitem_sequence_broadcasts(self, data, box_in_series):
  270. # ValueError: cannot set using a list-like indexer with a different
  271. # length than the value
  272. super().test_setitem_sequence_broadcasts(data, box_in_series)
  273. @skip_nested
  274. @pytest.mark.parametrize("setter", ["loc", None])
  275. def test_setitem_mask_broadcast(self, data, setter):
  276. # ValueError: cannot set using a list-like indexer with a different
  277. # length than the value
  278. super().test_setitem_mask_broadcast(data, setter)
  279. @skip_nested
  280. def test_setitem_scalar_key_sequence_raise(self, data):
  281. # Failed: DID NOT RAISE <class 'ValueError'>
  282. super().test_setitem_scalar_key_sequence_raise(data)
  283. # TODO: there is some issue with NumpyExtensionArray, therefore,
  284. # skip the setitem test for now, and fix it later (GH 31446)
  285. @skip_nested
  286. @pytest.mark.parametrize(
  287. "mask",
  288. [
  289. np.array([True, True, True, False, False]),
  290. pd.array([True, True, True, False, False], dtype="boolean"),
  291. ],
  292. ids=["numpy-array", "boolean-array"],
  293. )
  294. def test_setitem_mask(self, data, mask, box_in_series):
  295. super().test_setitem_mask(data, mask, box_in_series)
  296. @skip_nested
  297. @pytest.mark.parametrize(
  298. "idx",
  299. [[0, 1, 2], pd.array([0, 1, 2], dtype="Int64"), np.array([0, 1, 2])],
  300. ids=["list", "integer-array", "numpy-array"],
  301. )
  302. def test_setitem_integer_array(self, data, idx, box_in_series):
  303. super().test_setitem_integer_array(data, idx, box_in_series)
  304. @pytest.mark.parametrize(
  305. "idx, box_in_series",
  306. [
  307. ([0, 1, 2, pd.NA], False),
  308. pytest.param([0, 1, 2, pd.NA], True, marks=pytest.mark.xfail),
  309. (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
  310. (pd.array([0, 1, 2, pd.NA], dtype="Int64"), False),
  311. ],
  312. ids=["list-False", "list-True", "integer-array-False", "integer-array-True"],
  313. )
  314. def test_setitem_integer_with_missing_raises(self, data, idx, box_in_series):
  315. super().test_setitem_integer_with_missing_raises(data, idx, box_in_series)
  316. @skip_nested
  317. def test_setitem_slice(self, data, box_in_series):
  318. super().test_setitem_slice(data, box_in_series)
  319. @skip_nested
  320. def test_setitem_loc_iloc_slice(self, data):
  321. super().test_setitem_loc_iloc_slice(data)
  322. def test_setitem_with_expansion_dataframe_column(self, data, full_indexer):
  323. # https://github.com/pandas-dev/pandas/issues/32395
  324. df = expected = pd.DataFrame({"data": pd.Series(data)})
  325. result = pd.DataFrame(index=df.index)
  326. # because result has object dtype, the attempt to do setting inplace
  327. # is successful, and object dtype is retained
  328. key = full_indexer(df)
  329. result.loc[key, "data"] = df["data"]
  330. # base class method has expected = df; NumpyExtensionArray behaves oddly because
  331. # we patch _typ for these tests.
  332. if data.dtype.numpy_dtype != object:
  333. if not isinstance(key, slice) or key != slice(None):
  334. expected = pd.DataFrame({"data": data.to_numpy()})
  335. tm.assert_frame_equal(result, expected, check_column_type=False)
  336. @pytest.mark.xfail(reason="NumpyEADtype is unpacked")
  337. def test_index_from_listlike_with_dtype(self, data):
  338. super().test_index_from_listlike_with_dtype(data)
  339. @skip_nested
  340. @pytest.mark.parametrize("engine", ["c", "python"])
  341. def test_EA_types(self, engine, data, request):
  342. super().test_EA_types(engine, data, request)
  343. class Test2DCompat(base.NDArrayBacked2DTests):
  344. pass