test_string.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. """
  13. import string
  14. import numpy as np
  15. import pytest
  16. from pandas.errors import PerformanceWarning
  17. import pandas as pd
  18. import pandas._testing as tm
  19. from pandas.api.types import is_string_dtype
  20. from pandas.core.arrays import ArrowStringArray
  21. from pandas.core.arrays.string_ import StringDtype
  22. from pandas.tests.extension import base
  23. def split_array(arr):
  24. if arr.dtype.storage != "pyarrow":
  25. pytest.skip("only applicable for pyarrow chunked array n/a")
  26. def _split_array(arr):
  27. import pyarrow as pa
  28. arrow_array = arr._data
  29. split = len(arrow_array) // 2
  30. arrow_array = pa.chunked_array(
  31. [*arrow_array[:split].chunks, *arrow_array[split:].chunks]
  32. )
  33. assert arrow_array.num_chunks == 2
  34. return type(arr)(arrow_array)
  35. return _split_array(arr)
  36. @pytest.fixture(params=[True, False])
  37. def chunked(request):
  38. return request.param
  39. @pytest.fixture
  40. def dtype(string_storage):
  41. return StringDtype(storage=string_storage)
  42. @pytest.fixture
  43. def data(dtype, chunked):
  44. strings = np.random.choice(list(string.ascii_letters), size=100)
  45. while strings[0] == strings[1]:
  46. strings = np.random.choice(list(string.ascii_letters), size=100)
  47. arr = dtype.construct_array_type()._from_sequence(strings)
  48. return split_array(arr) if chunked else arr
  49. @pytest.fixture
  50. def data_missing(dtype, chunked):
  51. """Length 2 array with [NA, Valid]"""
  52. arr = dtype.construct_array_type()._from_sequence([pd.NA, "A"])
  53. return split_array(arr) if chunked else arr
  54. @pytest.fixture
  55. def data_for_sorting(dtype, chunked):
  56. arr = dtype.construct_array_type()._from_sequence(["B", "C", "A"])
  57. return split_array(arr) if chunked else arr
  58. @pytest.fixture
  59. def data_missing_for_sorting(dtype, chunked):
  60. arr = dtype.construct_array_type()._from_sequence(["B", pd.NA, "A"])
  61. return split_array(arr) if chunked else arr
  62. @pytest.fixture
  63. def na_value():
  64. return pd.NA
  65. @pytest.fixture
  66. def data_for_grouping(dtype, chunked):
  67. arr = dtype.construct_array_type()._from_sequence(
  68. ["B", "B", pd.NA, pd.NA, "A", "A", "B", "C"]
  69. )
  70. return split_array(arr) if chunked else arr
  71. class TestDtype(base.BaseDtypeTests):
  72. def test_eq_with_str(self, dtype):
  73. assert dtype == f"string[{dtype.storage}]"
  74. super().test_eq_with_str(dtype)
  75. def test_is_not_string_type(self, dtype):
  76. # Different from BaseDtypeTests.test_is_not_string_type
  77. # because StringDtype is a string type
  78. assert is_string_dtype(dtype)
  79. class TestInterface(base.BaseInterfaceTests):
  80. def test_view(self, data, request):
  81. if data.dtype.storage == "pyarrow":
  82. pytest.skip(reason="2D support not implemented for ArrowStringArray")
  83. super().test_view(data)
  84. class TestConstructors(base.BaseConstructorsTests):
  85. def test_from_dtype(self, data):
  86. # base test uses string representation of dtype
  87. pass
  88. def test_constructor_from_list(self):
  89. # GH 27673
  90. pytest.importorskip("pyarrow", minversion="1.0.0")
  91. result = pd.Series(["E"], dtype=StringDtype(storage="pyarrow"))
  92. assert isinstance(result.dtype, StringDtype)
  93. assert result.dtype.storage == "pyarrow"
  94. class TestReshaping(base.BaseReshapingTests):
  95. def test_transpose(self, data, request):
  96. if data.dtype.storage == "pyarrow":
  97. pytest.skip(reason="2D support not implemented for ArrowStringArray")
  98. super().test_transpose(data)
  99. class TestGetitem(base.BaseGetitemTests):
  100. pass
  101. class TestSetitem(base.BaseSetitemTests):
  102. def test_setitem_preserves_views(self, data, request):
  103. if data.dtype.storage == "pyarrow":
  104. pytest.skip(reason="2D support not implemented for ArrowStringArray")
  105. super().test_setitem_preserves_views(data)
  106. class TestIndex(base.BaseIndexTests):
  107. pass
  108. class TestMissing(base.BaseMissingTests):
  109. def test_dropna_array(self, data_missing):
  110. result = data_missing.dropna()
  111. expected = data_missing[[1]]
  112. self.assert_extension_array_equal(result, expected)
  113. def test_fillna_no_op_returns_copy(self, data):
  114. data = data[~data.isna()]
  115. valid = data[0]
  116. result = data.fillna(valid)
  117. assert result is not data
  118. self.assert_extension_array_equal(result, data)
  119. with tm.maybe_produces_warning(
  120. PerformanceWarning, data.dtype.storage == "pyarrow"
  121. ):
  122. result = data.fillna(method="backfill")
  123. assert result is not data
  124. self.assert_extension_array_equal(result, data)
  125. def test_fillna_series_method(self, data_missing, fillna_method):
  126. with tm.maybe_produces_warning(
  127. PerformanceWarning,
  128. fillna_method is not None and data_missing.dtype.storage == "pyarrow",
  129. check_stacklevel=False,
  130. ):
  131. super().test_fillna_series_method(data_missing, fillna_method)
  132. class TestNoReduce(base.BaseNoReduceTests):
  133. @pytest.mark.parametrize("skipna", [True, False])
  134. def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna):
  135. op_name = all_numeric_reductions
  136. if op_name in ["min", "max"]:
  137. return None
  138. ser = pd.Series(data)
  139. with pytest.raises(TypeError):
  140. getattr(ser, op_name)(skipna=skipna)
  141. class TestMethods(base.BaseMethodsTests):
  142. def test_value_counts_with_normalize(self, data):
  143. data = data[:10].unique()
  144. values = np.array(data[~data.isna()])
  145. ser = pd.Series(data, dtype=data.dtype)
  146. result = ser.value_counts(normalize=True).sort_index()
  147. expected = pd.Series(
  148. [1 / len(values)] * len(values), index=result.index, name="proportion"
  149. )
  150. if getattr(data.dtype, "storage", "") == "pyarrow":
  151. expected = expected.astype("double[pyarrow]")
  152. else:
  153. expected = expected.astype("Float64")
  154. self.assert_series_equal(result, expected)
  155. class TestCasting(base.BaseCastingTests):
  156. pass
  157. class TestComparisonOps(base.BaseComparisonOpsTests):
  158. def _compare_other(self, ser, data, op, other):
  159. op_name = f"__{op.__name__}__"
  160. result = getattr(ser, op_name)(other)
  161. dtype = "boolean[pyarrow]" if ser.dtype.storage == "pyarrow" else "boolean"
  162. expected = getattr(ser.astype(object), op_name)(other).astype(dtype)
  163. self.assert_series_equal(result, expected)
  164. def test_compare_scalar(self, data, comparison_op):
  165. ser = pd.Series(data)
  166. self._compare_other(ser, data, comparison_op, "abc")
  167. class TestParsing(base.BaseParsingTests):
  168. pass
  169. class TestPrinting(base.BasePrintingTests):
  170. pass
  171. class TestGroupBy(base.BaseGroupbyTests):
  172. @pytest.mark.parametrize("as_index", [True, False])
  173. def test_groupby_extension_agg(self, as_index, data_for_grouping):
  174. df = pd.DataFrame({"A": [1, 1, 2, 2, 3, 3, 1, 4], "B": data_for_grouping})
  175. result = df.groupby("B", as_index=as_index).A.mean()
  176. _, uniques = pd.factorize(data_for_grouping, sort=True)
  177. if as_index:
  178. index = pd.Index(uniques, name="B")
  179. expected = pd.Series([3.0, 1.0, 4.0], index=index, name="A")
  180. self.assert_series_equal(result, expected)
  181. else:
  182. expected = pd.DataFrame({"B": uniques, "A": [3.0, 1.0, 4.0]})
  183. self.assert_frame_equal(result, expected)
  184. @pytest.mark.filterwarnings("ignore:Falling back:pandas.errors.PerformanceWarning")
  185. def test_groupby_extension_apply(self, data_for_grouping, groupby_apply_op):
  186. super().test_groupby_extension_apply(data_for_grouping, groupby_apply_op)
  187. class Test2DCompat(base.Dim2CompatTests):
  188. @pytest.fixture(autouse=True)
  189. def arrow_not_supported(self, data, request):
  190. if isinstance(data, ArrowStringArray):
  191. pytest.skip(reason="2D support not implemented for ArrowStringArray")
  192. def test_searchsorted_with_na_raises(data_for_sorting, as_series):
  193. # GH50447
  194. b, c, a = data_for_sorting
  195. arr = data_for_sorting.take([2, 0, 1]) # to get [a, b, c]
  196. arr[-1] = pd.NA
  197. if as_series:
  198. arr = pd.Series(arr)
  199. msg = (
  200. "searchsorted requires array to be sorted, "
  201. "which is impossible with NAs present."
  202. )
  203. with pytest.raises(ValueError, match=msg):
  204. arr.searchsorted(b)