arraysetops.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. """
  2. Set operations for arrays based on sorting.
  3. Notes
  4. -----
  5. For floating point arrays, inaccurate results may appear due to usual round-off
  6. and floating point comparison issues.
  7. Speed could be gained in some operations by an implementation of
  8. `numpy.sort`, that can provide directly the permutation vectors, thus avoiding
  9. calls to `numpy.argsort`.
  10. Original author: Robert Cimrman
  11. """
  12. import functools
  13. import numpy as np
  14. from numpy.core import overrides
  15. array_function_dispatch = functools.partial(
  16. overrides.array_function_dispatch, module='numpy')
  17. __all__ = [
  18. 'ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique',
  19. 'in1d', 'isin'
  20. ]
  21. def _ediff1d_dispatcher(ary, to_end=None, to_begin=None):
  22. return (ary, to_end, to_begin)
  23. @array_function_dispatch(_ediff1d_dispatcher)
  24. def ediff1d(ary, to_end=None, to_begin=None):
  25. """
  26. The differences between consecutive elements of an array.
  27. Parameters
  28. ----------
  29. ary : array_like
  30. If necessary, will be flattened before the differences are taken.
  31. to_end : array_like, optional
  32. Number(s) to append at the end of the returned differences.
  33. to_begin : array_like, optional
  34. Number(s) to prepend at the beginning of the returned differences.
  35. Returns
  36. -------
  37. ediff1d : ndarray
  38. The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``.
  39. See Also
  40. --------
  41. diff, gradient
  42. Notes
  43. -----
  44. When applied to masked arrays, this function drops the mask information
  45. if the `to_begin` and/or `to_end` parameters are used.
  46. Examples
  47. --------
  48. >>> x = np.array([1, 2, 4, 7, 0])
  49. >>> np.ediff1d(x)
  50. array([ 1, 2, 3, -7])
  51. >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
  52. array([-99, 1, 2, ..., -7, 88, 99])
  53. The returned array is always 1D.
  54. >>> y = [[1, 2, 4], [1, 6, 24]]
  55. >>> np.ediff1d(y)
  56. array([ 1, 2, -3, 5, 18])
  57. """
  58. # force a 1d array
  59. ary = np.asanyarray(ary).ravel()
  60. # enforce that the dtype of `ary` is used for the output
  61. dtype_req = ary.dtype
  62. # fast track default case
  63. if to_begin is None and to_end is None:
  64. return ary[1:] - ary[:-1]
  65. if to_begin is None:
  66. l_begin = 0
  67. else:
  68. to_begin = np.asanyarray(to_begin)
  69. if not np.can_cast(to_begin, dtype_req, casting="same_kind"):
  70. raise TypeError("dtype of `to_begin` must be compatible "
  71. "with input `ary` under the `same_kind` rule.")
  72. to_begin = to_begin.ravel()
  73. l_begin = len(to_begin)
  74. if to_end is None:
  75. l_end = 0
  76. else:
  77. to_end = np.asanyarray(to_end)
  78. if not np.can_cast(to_end, dtype_req, casting="same_kind"):
  79. raise TypeError("dtype of `to_end` must be compatible "
  80. "with input `ary` under the `same_kind` rule.")
  81. to_end = to_end.ravel()
  82. l_end = len(to_end)
  83. # do the calculation in place and copy to_begin and to_end
  84. l_diff = max(len(ary) - 1, 0)
  85. result = np.empty(l_diff + l_begin + l_end, dtype=ary.dtype)
  86. result = ary.__array_wrap__(result)
  87. if l_begin > 0:
  88. result[:l_begin] = to_begin
  89. if l_end > 0:
  90. result[l_begin + l_diff:] = to_end
  91. np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff])
  92. return result
  93. def _unpack_tuple(x):
  94. """ Unpacks one-element tuples for use as return values """
  95. if len(x) == 1:
  96. return x[0]
  97. else:
  98. return x
  99. def _unique_dispatcher(ar, return_index=None, return_inverse=None,
  100. return_counts=None, axis=None, *, equal_nan=None):
  101. return (ar,)
  102. @array_function_dispatch(_unique_dispatcher)
  103. def unique(ar, return_index=False, return_inverse=False,
  104. return_counts=False, axis=None, *, equal_nan=True):
  105. """
  106. Find the unique elements of an array.
  107. Returns the sorted unique elements of an array. There are three optional
  108. outputs in addition to the unique elements:
  109. * the indices of the input array that give the unique values
  110. * the indices of the unique array that reconstruct the input array
  111. * the number of times each unique value comes up in the input array
  112. Parameters
  113. ----------
  114. ar : array_like
  115. Input array. Unless `axis` is specified, this will be flattened if it
  116. is not already 1-D.
  117. return_index : bool, optional
  118. If True, also return the indices of `ar` (along the specified axis,
  119. if provided, or in the flattened array) that result in the unique array.
  120. return_inverse : bool, optional
  121. If True, also return the indices of the unique array (for the specified
  122. axis, if provided) that can be used to reconstruct `ar`.
  123. return_counts : bool, optional
  124. If True, also return the number of times each unique item appears
  125. in `ar`.
  126. axis : int or None, optional
  127. The axis to operate on. If None, `ar` will be flattened. If an integer,
  128. the subarrays indexed by the given axis will be flattened and treated
  129. as the elements of a 1-D array with the dimension of the given axis,
  130. see the notes for more details. Object arrays or structured arrays
  131. that contain objects are not supported if the `axis` kwarg is used. The
  132. default is None.
  133. .. versionadded:: 1.13.0
  134. equal_nan : bool, optional
  135. If True, collapses multiple NaN values in the return array into one.
  136. .. versionadded:: 1.24
  137. Returns
  138. -------
  139. unique : ndarray
  140. The sorted unique values.
  141. unique_indices : ndarray, optional
  142. The indices of the first occurrences of the unique values in the
  143. original array. Only provided if `return_index` is True.
  144. unique_inverse : ndarray, optional
  145. The indices to reconstruct the original array from the
  146. unique array. Only provided if `return_inverse` is True.
  147. unique_counts : ndarray, optional
  148. The number of times each of the unique values comes up in the
  149. original array. Only provided if `return_counts` is True.
  150. .. versionadded:: 1.9.0
  151. See Also
  152. --------
  153. numpy.lib.arraysetops : Module with a number of other functions for
  154. performing set operations on arrays.
  155. repeat : Repeat elements of an array.
  156. Notes
  157. -----
  158. When an axis is specified the subarrays indexed by the axis are sorted.
  159. This is done by making the specified axis the first dimension of the array
  160. (move the axis to the first dimension to keep the order of the other axes)
  161. and then flattening the subarrays in C order. The flattened subarrays are
  162. then viewed as a structured type with each element given a label, with the
  163. effect that we end up with a 1-D array of structured types that can be
  164. treated in the same way as any other 1-D array. The result is that the
  165. flattened subarrays are sorted in lexicographic order starting with the
  166. first element.
  167. .. versionchanged: NumPy 1.21
  168. If nan values are in the input array, a single nan is put
  169. to the end of the sorted unique values.
  170. Also for complex arrays all NaN values are considered equivalent
  171. (no matter whether the NaN is in the real or imaginary part).
  172. As the representant for the returned array the smallest one in the
  173. lexicographical order is chosen - see np.sort for how the lexicographical
  174. order is defined for complex arrays.
  175. Examples
  176. --------
  177. >>> np.unique([1, 1, 2, 2, 3, 3])
  178. array([1, 2, 3])
  179. >>> a = np.array([[1, 1], [2, 3]])
  180. >>> np.unique(a)
  181. array([1, 2, 3])
  182. Return the unique rows of a 2D array
  183. >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
  184. >>> np.unique(a, axis=0)
  185. array([[1, 0, 0], [2, 3, 4]])
  186. Return the indices of the original array that give the unique values:
  187. >>> a = np.array(['a', 'b', 'b', 'c', 'a'])
  188. >>> u, indices = np.unique(a, return_index=True)
  189. >>> u
  190. array(['a', 'b', 'c'], dtype='<U1')
  191. >>> indices
  192. array([0, 1, 3])
  193. >>> a[indices]
  194. array(['a', 'b', 'c'], dtype='<U1')
  195. Reconstruct the input array from the unique values and inverse:
  196. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  197. >>> u, indices = np.unique(a, return_inverse=True)
  198. >>> u
  199. array([1, 2, 3, 4, 6])
  200. >>> indices
  201. array([0, 1, 4, 3, 1, 2, 1])
  202. >>> u[indices]
  203. array([1, 2, 6, 4, 2, 3, 2])
  204. Reconstruct the input values from the unique values and counts:
  205. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  206. >>> values, counts = np.unique(a, return_counts=True)
  207. >>> values
  208. array([1, 2, 3, 4, 6])
  209. >>> counts
  210. array([1, 3, 1, 1, 1])
  211. >>> np.repeat(values, counts)
  212. array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
  213. """
  214. ar = np.asanyarray(ar)
  215. if axis is None:
  216. ret = _unique1d(ar, return_index, return_inverse, return_counts,
  217. equal_nan=equal_nan)
  218. return _unpack_tuple(ret)
  219. # axis was specified and not None
  220. try:
  221. ar = np.moveaxis(ar, axis, 0)
  222. except np.AxisError:
  223. # this removes the "axis1" or "axis2" prefix from the error message
  224. raise np.AxisError(axis, ar.ndim) from None
  225. # Must reshape to a contiguous 2D array for this to work...
  226. orig_shape, orig_dtype = ar.shape, ar.dtype
  227. ar = ar.reshape(orig_shape[0], np.prod(orig_shape[1:], dtype=np.intp))
  228. ar = np.ascontiguousarray(ar)
  229. dtype = [('f{i}'.format(i=i), ar.dtype) for i in range(ar.shape[1])]
  230. # At this point, `ar` has shape `(n, m)`, and `dtype` is a structured
  231. # data type with `m` fields where each field has the data type of `ar`.
  232. # In the following, we create the array `consolidated`, which has
  233. # shape `(n,)` with data type `dtype`.
  234. try:
  235. if ar.shape[1] > 0:
  236. consolidated = ar.view(dtype)
  237. else:
  238. # If ar.shape[1] == 0, then dtype will be `np.dtype([])`, which is
  239. # a data type with itemsize 0, and the call `ar.view(dtype)` will
  240. # fail. Instead, we'll use `np.empty` to explicitly create the
  241. # array with shape `(len(ar),)`. Because `dtype` in this case has
  242. # itemsize 0, the total size of the result is still 0 bytes.
  243. consolidated = np.empty(len(ar), dtype=dtype)
  244. except TypeError as e:
  245. # There's no good way to do this for object arrays, etc...
  246. msg = 'The axis argument to unique is not supported for dtype {dt}'
  247. raise TypeError(msg.format(dt=ar.dtype)) from e
  248. def reshape_uniq(uniq):
  249. n = len(uniq)
  250. uniq = uniq.view(orig_dtype)
  251. uniq = uniq.reshape(n, *orig_shape[1:])
  252. uniq = np.moveaxis(uniq, 0, axis)
  253. return uniq
  254. output = _unique1d(consolidated, return_index,
  255. return_inverse, return_counts, equal_nan=equal_nan)
  256. output = (reshape_uniq(output[0]),) + output[1:]
  257. return _unpack_tuple(output)
  258. def _unique1d(ar, return_index=False, return_inverse=False,
  259. return_counts=False, *, equal_nan=True):
  260. """
  261. Find the unique elements of an array, ignoring shape.
  262. """
  263. ar = np.asanyarray(ar).flatten()
  264. optional_indices = return_index or return_inverse
  265. if optional_indices:
  266. perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
  267. aux = ar[perm]
  268. else:
  269. ar.sort()
  270. aux = ar
  271. mask = np.empty(aux.shape, dtype=np.bool_)
  272. mask[:1] = True
  273. if (equal_nan and aux.shape[0] > 0 and aux.dtype.kind in "cfmM" and
  274. np.isnan(aux[-1])):
  275. if aux.dtype.kind == "c": # for complex all NaNs are considered equivalent
  276. aux_firstnan = np.searchsorted(np.isnan(aux), True, side='left')
  277. else:
  278. aux_firstnan = np.searchsorted(aux, aux[-1], side='left')
  279. if aux_firstnan > 0:
  280. mask[1:aux_firstnan] = (
  281. aux[1:aux_firstnan] != aux[:aux_firstnan - 1])
  282. mask[aux_firstnan] = True
  283. mask[aux_firstnan + 1:] = False
  284. else:
  285. mask[1:] = aux[1:] != aux[:-1]
  286. ret = (aux[mask],)
  287. if return_index:
  288. ret += (perm[mask],)
  289. if return_inverse:
  290. imask = np.cumsum(mask) - 1
  291. inv_idx = np.empty(mask.shape, dtype=np.intp)
  292. inv_idx[perm] = imask
  293. ret += (inv_idx,)
  294. if return_counts:
  295. idx = np.concatenate(np.nonzero(mask) + ([mask.size],))
  296. ret += (np.diff(idx),)
  297. return ret
  298. def _intersect1d_dispatcher(
  299. ar1, ar2, assume_unique=None, return_indices=None):
  300. return (ar1, ar2)
  301. @array_function_dispatch(_intersect1d_dispatcher)
  302. def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
  303. """
  304. Find the intersection of two arrays.
  305. Return the sorted, unique values that are in both of the input arrays.
  306. Parameters
  307. ----------
  308. ar1, ar2 : array_like
  309. Input arrays. Will be flattened if not already 1D.
  310. assume_unique : bool
  311. If True, the input arrays are both assumed to be unique, which
  312. can speed up the calculation. If True but ``ar1`` or ``ar2`` are not
  313. unique, incorrect results and out-of-bounds indices could result.
  314. Default is False.
  315. return_indices : bool
  316. If True, the indices which correspond to the intersection of the two
  317. arrays are returned. The first instance of a value is used if there are
  318. multiple. Default is False.
  319. .. versionadded:: 1.15.0
  320. Returns
  321. -------
  322. intersect1d : ndarray
  323. Sorted 1D array of common and unique elements.
  324. comm1 : ndarray
  325. The indices of the first occurrences of the common values in `ar1`.
  326. Only provided if `return_indices` is True.
  327. comm2 : ndarray
  328. The indices of the first occurrences of the common values in `ar2`.
  329. Only provided if `return_indices` is True.
  330. See Also
  331. --------
  332. numpy.lib.arraysetops : Module with a number of other functions for
  333. performing set operations on arrays.
  334. Examples
  335. --------
  336. >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
  337. array([1, 3])
  338. To intersect more than two arrays, use functools.reduce:
  339. >>> from functools import reduce
  340. >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  341. array([3])
  342. To return the indices of the values common to the input arrays
  343. along with the intersected values:
  344. >>> x = np.array([1, 1, 2, 3, 4])
  345. >>> y = np.array([2, 1, 4, 6])
  346. >>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
  347. >>> x_ind, y_ind
  348. (array([0, 2, 4]), array([1, 0, 2]))
  349. >>> xy, x[x_ind], y[y_ind]
  350. (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
  351. """
  352. ar1 = np.asanyarray(ar1)
  353. ar2 = np.asanyarray(ar2)
  354. if not assume_unique:
  355. if return_indices:
  356. ar1, ind1 = unique(ar1, return_index=True)
  357. ar2, ind2 = unique(ar2, return_index=True)
  358. else:
  359. ar1 = unique(ar1)
  360. ar2 = unique(ar2)
  361. else:
  362. ar1 = ar1.ravel()
  363. ar2 = ar2.ravel()
  364. aux = np.concatenate((ar1, ar2))
  365. if return_indices:
  366. aux_sort_indices = np.argsort(aux, kind='mergesort')
  367. aux = aux[aux_sort_indices]
  368. else:
  369. aux.sort()
  370. mask = aux[1:] == aux[:-1]
  371. int1d = aux[:-1][mask]
  372. if return_indices:
  373. ar1_indices = aux_sort_indices[:-1][mask]
  374. ar2_indices = aux_sort_indices[1:][mask] - ar1.size
  375. if not assume_unique:
  376. ar1_indices = ind1[ar1_indices]
  377. ar2_indices = ind2[ar2_indices]
  378. return int1d, ar1_indices, ar2_indices
  379. else:
  380. return int1d
  381. def _setxor1d_dispatcher(ar1, ar2, assume_unique=None):
  382. return (ar1, ar2)
  383. @array_function_dispatch(_setxor1d_dispatcher)
  384. def setxor1d(ar1, ar2, assume_unique=False):
  385. """
  386. Find the set exclusive-or of two arrays.
  387. Return the sorted, unique values that are in only one (not both) of the
  388. input arrays.
  389. Parameters
  390. ----------
  391. ar1, ar2 : array_like
  392. Input arrays.
  393. assume_unique : bool
  394. If True, the input arrays are both assumed to be unique, which
  395. can speed up the calculation. Default is False.
  396. Returns
  397. -------
  398. setxor1d : ndarray
  399. Sorted 1D array of unique values that are in only one of the input
  400. arrays.
  401. Examples
  402. --------
  403. >>> a = np.array([1, 2, 3, 2, 4])
  404. >>> b = np.array([2, 3, 5, 7, 5])
  405. >>> np.setxor1d(a,b)
  406. array([1, 4, 5, 7])
  407. """
  408. if not assume_unique:
  409. ar1 = unique(ar1)
  410. ar2 = unique(ar2)
  411. aux = np.concatenate((ar1, ar2))
  412. if aux.size == 0:
  413. return aux
  414. aux.sort()
  415. flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
  416. return aux[flag[1:] & flag[:-1]]
  417. def _in1d_dispatcher(ar1, ar2, assume_unique=None, invert=None, *,
  418. kind=None):
  419. return (ar1, ar2)
  420. @array_function_dispatch(_in1d_dispatcher)
  421. def in1d(ar1, ar2, assume_unique=False, invert=False, *, kind=None):
  422. """
  423. Test whether each element of a 1-D array is also present in a second array.
  424. Returns a boolean array the same length as `ar1` that is True
  425. where an element of `ar1` is in `ar2` and False otherwise.
  426. We recommend using :func:`isin` instead of `in1d` for new code.
  427. Parameters
  428. ----------
  429. ar1 : (M,) array_like
  430. Input array.
  431. ar2 : array_like
  432. The values against which to test each value of `ar1`.
  433. assume_unique : bool, optional
  434. If True, the input arrays are both assumed to be unique, which
  435. can speed up the calculation. Default is False.
  436. invert : bool, optional
  437. If True, the values in the returned array are inverted (that is,
  438. False where an element of `ar1` is in `ar2` and True otherwise).
  439. Default is False. ``np.in1d(a, b, invert=True)`` is equivalent
  440. to (but is faster than) ``np.invert(in1d(a, b))``.
  441. kind : {None, 'sort', 'table'}, optional
  442. The algorithm to use. This will not affect the final result,
  443. but will affect the speed and memory use. The default, None,
  444. will select automatically based on memory considerations.
  445. * If 'sort', will use a mergesort-based approach. This will have
  446. a memory usage of roughly 6 times the sum of the sizes of
  447. `ar1` and `ar2`, not accounting for size of dtypes.
  448. * If 'table', will use a lookup table approach similar
  449. to a counting sort. This is only available for boolean and
  450. integer arrays. This will have a memory usage of the
  451. size of `ar1` plus the max-min value of `ar2`. `assume_unique`
  452. has no effect when the 'table' option is used.
  453. * If None, will automatically choose 'table' if
  454. the required memory allocation is less than or equal to
  455. 6 times the sum of the sizes of `ar1` and `ar2`,
  456. otherwise will use 'sort'. This is done to not use
  457. a large amount of memory by default, even though
  458. 'table' may be faster in most cases. If 'table' is chosen,
  459. `assume_unique` will have no effect.
  460. .. versionadded:: 1.8.0
  461. Returns
  462. -------
  463. in1d : (M,) ndarray, bool
  464. The values `ar1[in1d]` are in `ar2`.
  465. See Also
  466. --------
  467. isin : Version of this function that preserves the
  468. shape of ar1.
  469. numpy.lib.arraysetops : Module with a number of other functions for
  470. performing set operations on arrays.
  471. Notes
  472. -----
  473. `in1d` can be considered as an element-wise function version of the
  474. python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly
  475. equivalent to ``np.array([item in b for item in a])``.
  476. However, this idea fails if `ar2` is a set, or similar (non-sequence)
  477. container: As ``ar2`` is converted to an array, in those cases
  478. ``asarray(ar2)`` is an object array rather than the expected array of
  479. contained values.
  480. Using ``kind='table'`` tends to be faster than `kind='sort'` if the
  481. following relationship is true:
  482. ``log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927``,
  483. but may use greater memory. The default value for `kind` will
  484. be automatically selected based only on memory usage, so one may
  485. manually set ``kind='table'`` if memory constraints can be relaxed.
  486. .. versionadded:: 1.4.0
  487. Examples
  488. --------
  489. >>> test = np.array([0, 1, 2, 5, 0])
  490. >>> states = [0, 2]
  491. >>> mask = np.in1d(test, states)
  492. >>> mask
  493. array([ True, False, True, False, True])
  494. >>> test[mask]
  495. array([0, 2, 0])
  496. >>> mask = np.in1d(test, states, invert=True)
  497. >>> mask
  498. array([False, True, False, True, False])
  499. >>> test[mask]
  500. array([1, 5])
  501. """
  502. # Ravel both arrays, behavior for the first array could be different
  503. ar1 = np.asarray(ar1).ravel()
  504. ar2 = np.asarray(ar2).ravel()
  505. # Ensure that iteration through object arrays yields size-1 arrays
  506. if ar2.dtype == object:
  507. ar2 = ar2.reshape(-1, 1)
  508. if kind not in {None, 'sort', 'table'}:
  509. raise ValueError(
  510. f"Invalid kind: '{kind}'. Please use None, 'sort' or 'table'.")
  511. # Can use the table method if all arrays are integers or boolean:
  512. is_int_arrays = all(ar.dtype.kind in ("u", "i", "b") for ar in (ar1, ar2))
  513. use_table_method = is_int_arrays and kind in {None, 'table'}
  514. if use_table_method:
  515. if ar2.size == 0:
  516. if invert:
  517. return np.ones_like(ar1, dtype=bool)
  518. else:
  519. return np.zeros_like(ar1, dtype=bool)
  520. # Convert booleans to uint8 so we can use the fast integer algorithm
  521. if ar1.dtype == bool:
  522. ar1 = ar1.astype(np.uint8)
  523. if ar2.dtype == bool:
  524. ar2 = ar2.astype(np.uint8)
  525. ar2_min = np.min(ar2)
  526. ar2_max = np.max(ar2)
  527. ar2_range = int(ar2_max) - int(ar2_min)
  528. # Constraints on whether we can actually use the table method:
  529. # 1. Assert memory usage is not too large
  530. below_memory_constraint = ar2_range <= 6 * (ar1.size + ar2.size)
  531. # 2. Check overflows for (ar2 - ar2_min); dtype=ar2.dtype
  532. range_safe_from_overflow = ar2_range <= np.iinfo(ar2.dtype).max
  533. # 3. Check overflows for (ar1 - ar2_min); dtype=ar1.dtype
  534. if ar1.size > 0:
  535. ar1_min = np.min(ar1)
  536. ar1_max = np.max(ar1)
  537. # After masking, the range of ar1 is guaranteed to be
  538. # within the range of ar2:
  539. ar1_upper = min(int(ar1_max), int(ar2_max))
  540. ar1_lower = max(int(ar1_min), int(ar2_min))
  541. range_safe_from_overflow &= all((
  542. ar1_upper - int(ar2_min) <= np.iinfo(ar1.dtype).max,
  543. ar1_lower - int(ar2_min) >= np.iinfo(ar1.dtype).min
  544. ))
  545. # Optimal performance is for approximately
  546. # log10(size) > (log10(range) - 2.27) / 0.927.
  547. # However, here we set the requirement that by default
  548. # the intermediate array can only be 6x
  549. # the combined memory allocation of the original
  550. # arrays. See discussion on
  551. # https://github.com/numpy/numpy/pull/12065.
  552. if (
  553. range_safe_from_overflow and
  554. (below_memory_constraint or kind == 'table')
  555. ):
  556. if invert:
  557. outgoing_array = np.ones_like(ar1, dtype=bool)
  558. else:
  559. outgoing_array = np.zeros_like(ar1, dtype=bool)
  560. # Make elements 1 where the integer exists in ar2
  561. if invert:
  562. isin_helper_ar = np.ones(ar2_range + 1, dtype=bool)
  563. isin_helper_ar[ar2 - ar2_min] = 0
  564. else:
  565. isin_helper_ar = np.zeros(ar2_range + 1, dtype=bool)
  566. isin_helper_ar[ar2 - ar2_min] = 1
  567. # Mask out elements we know won't work
  568. basic_mask = (ar1 <= ar2_max) & (ar1 >= ar2_min)
  569. outgoing_array[basic_mask] = isin_helper_ar[ar1[basic_mask] -
  570. ar2_min]
  571. return outgoing_array
  572. elif kind == 'table': # not range_safe_from_overflow
  573. raise RuntimeError(
  574. "You have specified kind='table', "
  575. "but the range of values in `ar2` or `ar1` exceed the "
  576. "maximum integer of the datatype. "
  577. "Please set `kind` to None or 'sort'."
  578. )
  579. elif kind == 'table':
  580. raise ValueError(
  581. "The 'table' method is only "
  582. "supported for boolean or integer arrays. "
  583. "Please select 'sort' or None for kind."
  584. )
  585. # Check if one of the arrays may contain arbitrary objects
  586. contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject
  587. # This code is run when
  588. # a) the first condition is true, making the code significantly faster
  589. # b) the second condition is true (i.e. `ar1` or `ar2` may contain
  590. # arbitrary objects), since then sorting is not guaranteed to work
  591. if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:
  592. if invert:
  593. mask = np.ones(len(ar1), dtype=bool)
  594. for a in ar2:
  595. mask &= (ar1 != a)
  596. else:
  597. mask = np.zeros(len(ar1), dtype=bool)
  598. for a in ar2:
  599. mask |= (ar1 == a)
  600. return mask
  601. # Otherwise use sorting
  602. if not assume_unique:
  603. ar1, rev_idx = np.unique(ar1, return_inverse=True)
  604. ar2 = np.unique(ar2)
  605. ar = np.concatenate((ar1, ar2))
  606. # We need this to be a stable sort, so always use 'mergesort'
  607. # here. The values from the first array should always come before
  608. # the values from the second array.
  609. order = ar.argsort(kind='mergesort')
  610. sar = ar[order]
  611. if invert:
  612. bool_ar = (sar[1:] != sar[:-1])
  613. else:
  614. bool_ar = (sar[1:] == sar[:-1])
  615. flag = np.concatenate((bool_ar, [invert]))
  616. ret = np.empty(ar.shape, dtype=bool)
  617. ret[order] = flag
  618. if assume_unique:
  619. return ret[:len(ar1)]
  620. else:
  621. return ret[rev_idx]
  622. def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None,
  623. *, kind=None):
  624. return (element, test_elements)
  625. @array_function_dispatch(_isin_dispatcher)
  626. def isin(element, test_elements, assume_unique=False, invert=False, *,
  627. kind=None):
  628. """
  629. Calculates ``element in test_elements``, broadcasting over `element` only.
  630. Returns a boolean array of the same shape as `element` that is True
  631. where an element of `element` is in `test_elements` and False otherwise.
  632. Parameters
  633. ----------
  634. element : array_like
  635. Input array.
  636. test_elements : array_like
  637. The values against which to test each value of `element`.
  638. This argument is flattened if it is an array or array_like.
  639. See notes for behavior with non-array-like parameters.
  640. assume_unique : bool, optional
  641. If True, the input arrays are both assumed to be unique, which
  642. can speed up the calculation. Default is False.
  643. invert : bool, optional
  644. If True, the values in the returned array are inverted, as if
  645. calculating `element not in test_elements`. Default is False.
  646. ``np.isin(a, b, invert=True)`` is equivalent to (but faster
  647. than) ``np.invert(np.isin(a, b))``.
  648. kind : {None, 'sort', 'table'}, optional
  649. The algorithm to use. This will not affect the final result,
  650. but will affect the speed and memory use. The default, None,
  651. will select automatically based on memory considerations.
  652. * If 'sort', will use a mergesort-based approach. This will have
  653. a memory usage of roughly 6 times the sum of the sizes of
  654. `ar1` and `ar2`, not accounting for size of dtypes.
  655. * If 'table', will use a lookup table approach similar
  656. to a counting sort. This is only available for boolean and
  657. integer arrays. This will have a memory usage of the
  658. size of `ar1` plus the max-min value of `ar2`. `assume_unique`
  659. has no effect when the 'table' option is used.
  660. * If None, will automatically choose 'table' if
  661. the required memory allocation is less than or equal to
  662. 6 times the sum of the sizes of `ar1` and `ar2`,
  663. otherwise will use 'sort'. This is done to not use
  664. a large amount of memory by default, even though
  665. 'table' may be faster in most cases. If 'table' is chosen,
  666. `assume_unique` will have no effect.
  667. Returns
  668. -------
  669. isin : ndarray, bool
  670. Has the same shape as `element`. The values `element[isin]`
  671. are in `test_elements`.
  672. See Also
  673. --------
  674. in1d : Flattened version of this function.
  675. numpy.lib.arraysetops : Module with a number of other functions for
  676. performing set operations on arrays.
  677. Notes
  678. -----
  679. `isin` is an element-wise function version of the python keyword `in`.
  680. ``isin(a, b)`` is roughly equivalent to
  681. ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences.
  682. `element` and `test_elements` are converted to arrays if they are not
  683. already. If `test_elements` is a set (or other non-sequence collection)
  684. it will be converted to an object array with one element, rather than an
  685. array of the values contained in `test_elements`. This is a consequence
  686. of the `array` constructor's way of handling non-sequence collections.
  687. Converting the set to a list usually gives the desired behavior.
  688. Using ``kind='table'`` tends to be faster than `kind='sort'` if the
  689. following relationship is true:
  690. ``log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927``,
  691. but may use greater memory. The default value for `kind` will
  692. be automatically selected based only on memory usage, so one may
  693. manually set ``kind='table'`` if memory constraints can be relaxed.
  694. .. versionadded:: 1.13.0
  695. Examples
  696. --------
  697. >>> element = 2*np.arange(4).reshape((2, 2))
  698. >>> element
  699. array([[0, 2],
  700. [4, 6]])
  701. >>> test_elements = [1, 2, 4, 8]
  702. >>> mask = np.isin(element, test_elements)
  703. >>> mask
  704. array([[False, True],
  705. [ True, False]])
  706. >>> element[mask]
  707. array([2, 4])
  708. The indices of the matched values can be obtained with `nonzero`:
  709. >>> np.nonzero(mask)
  710. (array([0, 1]), array([1, 0]))
  711. The test can also be inverted:
  712. >>> mask = np.isin(element, test_elements, invert=True)
  713. >>> mask
  714. array([[ True, False],
  715. [False, True]])
  716. >>> element[mask]
  717. array([0, 6])
  718. Because of how `array` handles sets, the following does not
  719. work as expected:
  720. >>> test_set = {1, 2, 4, 8}
  721. >>> np.isin(element, test_set)
  722. array([[False, False],
  723. [False, False]])
  724. Casting the set to a list gives the expected result:
  725. >>> np.isin(element, list(test_set))
  726. array([[False, True],
  727. [ True, False]])
  728. """
  729. element = np.asarray(element)
  730. return in1d(element, test_elements, assume_unique=assume_unique,
  731. invert=invert, kind=kind).reshape(element.shape)
  732. def _union1d_dispatcher(ar1, ar2):
  733. return (ar1, ar2)
  734. @array_function_dispatch(_union1d_dispatcher)
  735. def union1d(ar1, ar2):
  736. """
  737. Find the union of two arrays.
  738. Return the unique, sorted array of values that are in either of the two
  739. input arrays.
  740. Parameters
  741. ----------
  742. ar1, ar2 : array_like
  743. Input arrays. They are flattened if they are not already 1D.
  744. Returns
  745. -------
  746. union1d : ndarray
  747. Unique, sorted union of the input arrays.
  748. See Also
  749. --------
  750. numpy.lib.arraysetops : Module with a number of other functions for
  751. performing set operations on arrays.
  752. Examples
  753. --------
  754. >>> np.union1d([-1, 0, 1], [-2, 0, 2])
  755. array([-2, -1, 0, 1, 2])
  756. To find the union of more than two arrays, use functools.reduce:
  757. >>> from functools import reduce
  758. >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  759. array([1, 2, 3, 4, 6])
  760. """
  761. return unique(np.concatenate((ar1, ar2), axis=None))
  762. def _setdiff1d_dispatcher(ar1, ar2, assume_unique=None):
  763. return (ar1, ar2)
  764. @array_function_dispatch(_setdiff1d_dispatcher)
  765. def setdiff1d(ar1, ar2, assume_unique=False):
  766. """
  767. Find the set difference of two arrays.
  768. Return the unique values in `ar1` that are not in `ar2`.
  769. Parameters
  770. ----------
  771. ar1 : array_like
  772. Input array.
  773. ar2 : array_like
  774. Input comparison array.
  775. assume_unique : bool
  776. If True, the input arrays are both assumed to be unique, which
  777. can speed up the calculation. Default is False.
  778. Returns
  779. -------
  780. setdiff1d : ndarray
  781. 1D array of values in `ar1` that are not in `ar2`. The result
  782. is sorted when `assume_unique=False`, but otherwise only sorted
  783. if the input is sorted.
  784. See Also
  785. --------
  786. numpy.lib.arraysetops : Module with a number of other functions for
  787. performing set operations on arrays.
  788. Examples
  789. --------
  790. >>> a = np.array([1, 2, 3, 2, 4, 1])
  791. >>> b = np.array([3, 4, 5, 6])
  792. >>> np.setdiff1d(a, b)
  793. array([1, 2])
  794. """
  795. if assume_unique:
  796. ar1 = np.asarray(ar1).ravel()
  797. else:
  798. ar1 = unique(ar1)
  799. ar2 = unique(ar2)
  800. return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]