test_isin.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import numpy as np
  2. import pytest
  3. import pandas as pd
  4. from pandas import (
  5. Series,
  6. date_range,
  7. )
  8. import pandas._testing as tm
  9. from pandas.core.arrays import PeriodArray
  10. class TestSeriesIsIn:
  11. def test_isin(self):
  12. s = Series(["A", "B", "C", "a", "B", "B", "A", "C"])
  13. result = s.isin(["A", "C"])
  14. expected = Series([True, False, True, False, False, False, True, True])
  15. tm.assert_series_equal(result, expected)
  16. # GH#16012
  17. # This specific issue has to have a series over 1e6 in len, but the
  18. # comparison array (in_list) must be large enough so that numpy doesn't
  19. # do a manual masking trick that will avoid this issue altogether
  20. s = Series(list("abcdefghijk" * 10**5))
  21. # If numpy doesn't do the manual comparison/mask, these
  22. # unorderable mixed types are what cause the exception in numpy
  23. in_list = [-1, "a", "b", "G", "Y", "Z", "E", "K", "E", "S", "I", "R", "R"] * 6
  24. assert s.isin(in_list).sum() == 200000
  25. def test_isin_with_string_scalar(self):
  26. # GH#4763
  27. s = Series(["A", "B", "C", "a", "B", "B", "A", "C"])
  28. msg = (
  29. r"only list-like objects are allowed to be passed to isin\(\), "
  30. r"you passed a \[str\]"
  31. )
  32. with pytest.raises(TypeError, match=msg):
  33. s.isin("a")
  34. s = Series(["aaa", "b", "c"])
  35. with pytest.raises(TypeError, match=msg):
  36. s.isin("aaa")
  37. def test_isin_datetimelike_mismatched_reso(self):
  38. expected = Series([True, True, False, False, False])
  39. ser = Series(date_range("jan-01-2013", "jan-05-2013"))
  40. # fails on dtype conversion in the first place
  41. day_values = np.asarray(ser[0:2].values).astype("datetime64[D]")
  42. result = ser.isin(day_values)
  43. tm.assert_series_equal(result, expected)
  44. dta = ser[:2]._values.astype("M8[s]")
  45. result = ser.isin(dta)
  46. tm.assert_series_equal(result, expected)
  47. def test_isin_datetimelike_mismatched_reso_list(self):
  48. expected = Series([True, True, False, False, False])
  49. ser = Series(date_range("jan-01-2013", "jan-05-2013"))
  50. dta = ser[:2]._values.astype("M8[s]")
  51. result = ser.isin(list(dta))
  52. tm.assert_series_equal(result, expected)
  53. def test_isin_with_i8(self):
  54. # GH#5021
  55. expected = Series([True, True, False, False, False])
  56. expected2 = Series([False, True, False, False, False])
  57. # datetime64[ns]
  58. s = Series(date_range("jan-01-2013", "jan-05-2013"))
  59. result = s.isin(s[0:2])
  60. tm.assert_series_equal(result, expected)
  61. result = s.isin(s[0:2].values)
  62. tm.assert_series_equal(result, expected)
  63. result = s.isin([s[1]])
  64. tm.assert_series_equal(result, expected2)
  65. result = s.isin([np.datetime64(s[1])])
  66. tm.assert_series_equal(result, expected2)
  67. result = s.isin(set(s[0:2]))
  68. tm.assert_series_equal(result, expected)
  69. # timedelta64[ns]
  70. s = Series(pd.to_timedelta(range(5), unit="d"))
  71. result = s.isin(s[0:2])
  72. tm.assert_series_equal(result, expected)
  73. @pytest.mark.parametrize("empty", [[], Series(dtype=object), np.array([])])
  74. def test_isin_empty(self, empty):
  75. # see GH#16991
  76. s = Series(["a", "b"])
  77. expected = Series([False, False])
  78. result = s.isin(empty)
  79. tm.assert_series_equal(expected, result)
  80. def test_isin_read_only(self):
  81. # https://github.com/pandas-dev/pandas/issues/37174
  82. arr = np.array([1, 2, 3])
  83. arr.setflags(write=False)
  84. s = Series([1, 2, 3])
  85. result = s.isin(arr)
  86. expected = Series([True, True, True])
  87. tm.assert_series_equal(result, expected)
  88. @pytest.mark.parametrize("dtype", [object, None])
  89. def test_isin_dt64_values_vs_ints(self, dtype):
  90. # GH#36621 dont cast integers to datetimes for isin
  91. dti = date_range("2013-01-01", "2013-01-05")
  92. ser = Series(dti)
  93. comps = np.asarray([1356998400000000000], dtype=dtype)
  94. res = dti.isin(comps)
  95. expected = np.array([False] * len(dti), dtype=bool)
  96. tm.assert_numpy_array_equal(res, expected)
  97. res = ser.isin(comps)
  98. tm.assert_series_equal(res, Series(expected))
  99. res = pd.core.algorithms.isin(ser, comps)
  100. tm.assert_numpy_array_equal(res, expected)
  101. def test_isin_tzawareness_mismatch(self):
  102. dti = date_range("2013-01-01", "2013-01-05")
  103. ser = Series(dti)
  104. other = dti.tz_localize("UTC")
  105. res = dti.isin(other)
  106. expected = np.array([False] * len(dti), dtype=bool)
  107. tm.assert_numpy_array_equal(res, expected)
  108. res = ser.isin(other)
  109. tm.assert_series_equal(res, Series(expected))
  110. res = pd.core.algorithms.isin(ser, other)
  111. tm.assert_numpy_array_equal(res, expected)
  112. def test_isin_period_freq_mismatch(self):
  113. dti = date_range("2013-01-01", "2013-01-05")
  114. pi = dti.to_period("M")
  115. ser = Series(pi)
  116. # We construct another PeriodIndex with the same i8 values
  117. # but different dtype
  118. dtype = dti.to_period("Y").dtype
  119. other = PeriodArray._simple_new(pi.asi8, dtype=dtype)
  120. res = pi.isin(other)
  121. expected = np.array([False] * len(pi), dtype=bool)
  122. tm.assert_numpy_array_equal(res, expected)
  123. res = ser.isin(other)
  124. tm.assert_series_equal(res, Series(expected))
  125. res = pd.core.algorithms.isin(ser, other)
  126. tm.assert_numpy_array_equal(res, expected)
  127. @pytest.mark.parametrize("values", [[-9.0, 0.0], [-9, 0]])
  128. def test_isin_float_in_int_series(self, values):
  129. # GH#19356 GH#21804
  130. ser = Series(values)
  131. result = ser.isin([-9, -0.5])
  132. expected = Series([True, False])
  133. tm.assert_series_equal(result, expected)
  134. @pytest.mark.parametrize("dtype", ["boolean", "Int64", "Float64"])
  135. @pytest.mark.parametrize(
  136. "data,values,expected",
  137. [
  138. ([0, 1, 0], [1], [False, True, False]),
  139. ([0, 1, 0], [1, pd.NA], [False, True, False]),
  140. ([0, pd.NA, 0], [1, 0], [True, False, True]),
  141. ([0, 1, pd.NA], [1, pd.NA], [False, True, True]),
  142. ([0, 1, pd.NA], [1, np.nan], [False, True, False]),
  143. ([0, pd.NA, pd.NA], [np.nan, pd.NaT, None], [False, False, False]),
  144. ],
  145. )
  146. def test_isin_masked_types(self, dtype, data, values, expected):
  147. # GH#42405
  148. ser = Series(data, dtype=dtype)
  149. result = ser.isin(values)
  150. expected = Series(expected, dtype="boolean")
  151. tm.assert_series_equal(result, expected)
  152. @pytest.mark.slow
  153. def test_isin_large_series_mixed_dtypes_and_nan():
  154. # https://github.com/pandas-dev/pandas/issues/37094
  155. # combination of object dtype for the values and > 1_000_000 elements
  156. ser = Series([1, 2, np.nan] * 1_000_000)
  157. result = ser.isin({"foo", "bar"})
  158. expected = Series([False] * 3 * 1_000_000)
  159. tm.assert_series_equal(result, expected)
  160. @pytest.mark.parametrize(
  161. "array,expected",
  162. [
  163. (
  164. [0, 1j, 1j, 1, 1 + 1j, 1 + 2j, 1 + 1j],
  165. Series([False, True, True, False, True, True, True], dtype=bool),
  166. )
  167. ],
  168. )
  169. def test_isin_complex_numbers(array, expected):
  170. # GH 17927
  171. result = Series(array).isin([1j, 1 + 1j, 1 + 2j])
  172. tm.assert_series_equal(result, expected)
  173. @pytest.mark.parametrize(
  174. "data,is_in",
  175. [([1, [2]], [1]), (["simple str", [{"values": 3}]], ["simple str"])],
  176. )
  177. def test_isin_filtering_with_mixed_object_types(data, is_in):
  178. # GH 20883
  179. ser = Series(data)
  180. result = ser.isin(is_in)
  181. expected = Series([True, False])
  182. tm.assert_series_equal(result, expected)
  183. @pytest.mark.parametrize("data", [[1, 2, 3], [1.0, 2.0, 3.0]])
  184. @pytest.mark.parametrize("isin", [[1, 2], [1.0, 2.0]])
  185. def test_isin_filtering_on_iterable(data, isin):
  186. # GH 50234
  187. ser = Series(data)
  188. result = ser.isin(i for i in isin)
  189. expected_result = Series([True, True, False])
  190. tm.assert_series_equal(result, expected_result)