arraysetops.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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):
  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):
  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. .. versionadded:: 1.9.0
  127. axis : int or None, optional
  128. The axis to operate on. If None, `ar` will be flattened. If an integer,
  129. the subarrays indexed by the given axis will be flattened and treated
  130. as the elements of a 1-D array with the dimension of the given axis,
  131. see the notes for more details. Object arrays or structured arrays
  132. that contain objects are not supported if the `axis` kwarg is used. The
  133. default is None.
  134. .. versionadded:: 1.13.0
  135. Returns
  136. -------
  137. unique : ndarray
  138. The sorted unique values.
  139. unique_indices : ndarray, optional
  140. The indices of the first occurrences of the unique values in the
  141. original array. Only provided if `return_index` is True.
  142. unique_inverse : ndarray, optional
  143. The indices to reconstruct the original array from the
  144. unique array. Only provided if `return_inverse` is True.
  145. unique_counts : ndarray, optional
  146. The number of times each of the unique values comes up in the
  147. original array. Only provided if `return_counts` is True.
  148. .. versionadded:: 1.9.0
  149. See Also
  150. --------
  151. numpy.lib.arraysetops : Module with a number of other functions for
  152. performing set operations on arrays.
  153. repeat : Repeat elements of an array.
  154. Notes
  155. -----
  156. When an axis is specified the subarrays indexed by the axis are sorted.
  157. This is done by making the specified axis the first dimension of the array
  158. (move the axis to the first dimension to keep the order of the other axes)
  159. and then flattening the subarrays in C order. The flattened subarrays are
  160. then viewed as a structured type with each element given a label, with the
  161. effect that we end up with a 1-D array of structured types that can be
  162. treated in the same way as any other 1-D array. The result is that the
  163. flattened subarrays are sorted in lexicographic order starting with the
  164. first element.
  165. .. versionchanged: NumPy 1.21
  166. If nan values are in the input array, a single nan is put
  167. to the end of the sorted unique values.
  168. Also for complex arrays all NaN values are considered equivalent
  169. (no matter whether the NaN is in the real or imaginary part).
  170. As the representant for the returned array the smallest one in the
  171. lexicographical order is chosen - see np.sort for how the lexicographical
  172. order is defined for complex arrays.
  173. Examples
  174. --------
  175. >>> np.unique([1, 1, 2, 2, 3, 3])
  176. array([1, 2, 3])
  177. >>> a = np.array([[1, 1], [2, 3]])
  178. >>> np.unique(a)
  179. array([1, 2, 3])
  180. Return the unique rows of a 2D array
  181. >>> a = np.array([[1, 0, 0], [1, 0, 0], [2, 3, 4]])
  182. >>> np.unique(a, axis=0)
  183. array([[1, 0, 0], [2, 3, 4]])
  184. Return the indices of the original array that give the unique values:
  185. >>> a = np.array(['a', 'b', 'b', 'c', 'a'])
  186. >>> u, indices = np.unique(a, return_index=True)
  187. >>> u
  188. array(['a', 'b', 'c'], dtype='<U1')
  189. >>> indices
  190. array([0, 1, 3])
  191. >>> a[indices]
  192. array(['a', 'b', 'c'], dtype='<U1')
  193. Reconstruct the input array from the unique values and inverse:
  194. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  195. >>> u, indices = np.unique(a, return_inverse=True)
  196. >>> u
  197. array([1, 2, 3, 4, 6])
  198. >>> indices
  199. array([0, 1, 4, 3, 1, 2, 1])
  200. >>> u[indices]
  201. array([1, 2, 6, 4, 2, 3, 2])
  202. Reconstruct the input values from the unique values and counts:
  203. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  204. >>> values, counts = np.unique(a, return_counts=True)
  205. >>> values
  206. array([1, 2, 3, 4, 6])
  207. >>> counts
  208. array([1, 3, 1, 1, 1])
  209. >>> np.repeat(values, counts)
  210. array([1, 2, 2, 2, 3, 4, 6]) # original order not preserved
  211. """
  212. ar = np.asanyarray(ar)
  213. if axis is None:
  214. ret = _unique1d(ar, return_index, return_inverse, return_counts)
  215. return _unpack_tuple(ret)
  216. # axis was specified and not None
  217. try:
  218. ar = np.moveaxis(ar, axis, 0)
  219. except np.AxisError:
  220. # this removes the "axis1" or "axis2" prefix from the error message
  221. raise np.AxisError(axis, ar.ndim) from None
  222. # Must reshape to a contiguous 2D array for this to work...
  223. orig_shape, orig_dtype = ar.shape, ar.dtype
  224. ar = ar.reshape(orig_shape[0], np.prod(orig_shape[1:], dtype=np.intp))
  225. ar = np.ascontiguousarray(ar)
  226. dtype = [('f{i}'.format(i=i), ar.dtype) for i in range(ar.shape[1])]
  227. # At this point, `ar` has shape `(n, m)`, and `dtype` is a structured
  228. # data type with `m` fields where each field has the data type of `ar`.
  229. # In the following, we create the array `consolidated`, which has
  230. # shape `(n,)` with data type `dtype`.
  231. try:
  232. if ar.shape[1] > 0:
  233. consolidated = ar.view(dtype)
  234. else:
  235. # If ar.shape[1] == 0, then dtype will be `np.dtype([])`, which is
  236. # a data type with itemsize 0, and the call `ar.view(dtype)` will
  237. # fail. Instead, we'll use `np.empty` to explicitly create the
  238. # array with shape `(len(ar),)`. Because `dtype` in this case has
  239. # itemsize 0, the total size of the result is still 0 bytes.
  240. consolidated = np.empty(len(ar), dtype=dtype)
  241. except TypeError as e:
  242. # There's no good way to do this for object arrays, etc...
  243. msg = 'The axis argument to unique is not supported for dtype {dt}'
  244. raise TypeError(msg.format(dt=ar.dtype)) from e
  245. def reshape_uniq(uniq):
  246. n = len(uniq)
  247. uniq = uniq.view(orig_dtype)
  248. uniq = uniq.reshape(n, *orig_shape[1:])
  249. uniq = np.moveaxis(uniq, 0, axis)
  250. return uniq
  251. output = _unique1d(consolidated, return_index,
  252. return_inverse, return_counts)
  253. output = (reshape_uniq(output[0]),) + output[1:]
  254. return _unpack_tuple(output)
  255. def _unique1d(ar, return_index=False, return_inverse=False,
  256. return_counts=False):
  257. """
  258. Find the unique elements of an array, ignoring shape.
  259. """
  260. ar = np.asanyarray(ar).flatten()
  261. optional_indices = return_index or return_inverse
  262. if optional_indices:
  263. perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
  264. aux = ar[perm]
  265. else:
  266. ar.sort()
  267. aux = ar
  268. mask = np.empty(aux.shape, dtype=np.bool_)
  269. mask[:1] = True
  270. if aux.shape[0] > 0 and aux.dtype.kind in "cfmM" and np.isnan(aux[-1]):
  271. if aux.dtype.kind == "c": # for complex all NaNs are considered equivalent
  272. aux_firstnan = np.searchsorted(np.isnan(aux), True, side='left')
  273. else:
  274. aux_firstnan = np.searchsorted(aux, aux[-1], side='left')
  275. if aux_firstnan > 0:
  276. mask[1:aux_firstnan] = (
  277. aux[1:aux_firstnan] != aux[:aux_firstnan - 1])
  278. mask[aux_firstnan] = True
  279. mask[aux_firstnan + 1:] = False
  280. else:
  281. mask[1:] = aux[1:] != aux[:-1]
  282. ret = (aux[mask],)
  283. if return_index:
  284. ret += (perm[mask],)
  285. if return_inverse:
  286. imask = np.cumsum(mask) - 1
  287. inv_idx = np.empty(mask.shape, dtype=np.intp)
  288. inv_idx[perm] = imask
  289. ret += (inv_idx,)
  290. if return_counts:
  291. idx = np.concatenate(np.nonzero(mask) + ([mask.size],))
  292. ret += (np.diff(idx),)
  293. return ret
  294. def _intersect1d_dispatcher(
  295. ar1, ar2, assume_unique=None, return_indices=None):
  296. return (ar1, ar2)
  297. @array_function_dispatch(_intersect1d_dispatcher)
  298. def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
  299. """
  300. Find the intersection of two arrays.
  301. Return the sorted, unique values that are in both of the input arrays.
  302. Parameters
  303. ----------
  304. ar1, ar2 : array_like
  305. Input arrays. Will be flattened if not already 1D.
  306. assume_unique : bool
  307. If True, the input arrays are both assumed to be unique, which
  308. can speed up the calculation. If True but ``ar1`` or ``ar2`` are not
  309. unique, incorrect results and out-of-bounds indices could result.
  310. Default is False.
  311. return_indices : bool
  312. If True, the indices which correspond to the intersection of the two
  313. arrays are returned. The first instance of a value is used if there are
  314. multiple. Default is False.
  315. .. versionadded:: 1.15.0
  316. Returns
  317. -------
  318. intersect1d : ndarray
  319. Sorted 1D array of common and unique elements.
  320. comm1 : ndarray
  321. The indices of the first occurrences of the common values in `ar1`.
  322. Only provided if `return_indices` is True.
  323. comm2 : ndarray
  324. The indices of the first occurrences of the common values in `ar2`.
  325. Only provided if `return_indices` is True.
  326. See Also
  327. --------
  328. numpy.lib.arraysetops : Module with a number of other functions for
  329. performing set operations on arrays.
  330. Examples
  331. --------
  332. >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
  333. array([1, 3])
  334. To intersect more than two arrays, use functools.reduce:
  335. >>> from functools import reduce
  336. >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  337. array([3])
  338. To return the indices of the values common to the input arrays
  339. along with the intersected values:
  340. >>> x = np.array([1, 1, 2, 3, 4])
  341. >>> y = np.array([2, 1, 4, 6])
  342. >>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
  343. >>> x_ind, y_ind
  344. (array([0, 2, 4]), array([1, 0, 2]))
  345. >>> xy, x[x_ind], y[y_ind]
  346. (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
  347. """
  348. ar1 = np.asanyarray(ar1)
  349. ar2 = np.asanyarray(ar2)
  350. if not assume_unique:
  351. if return_indices:
  352. ar1, ind1 = unique(ar1, return_index=True)
  353. ar2, ind2 = unique(ar2, return_index=True)
  354. else:
  355. ar1 = unique(ar1)
  356. ar2 = unique(ar2)
  357. else:
  358. ar1 = ar1.ravel()
  359. ar2 = ar2.ravel()
  360. aux = np.concatenate((ar1, ar2))
  361. if return_indices:
  362. aux_sort_indices = np.argsort(aux, kind='mergesort')
  363. aux = aux[aux_sort_indices]
  364. else:
  365. aux.sort()
  366. mask = aux[1:] == aux[:-1]
  367. int1d = aux[:-1][mask]
  368. if return_indices:
  369. ar1_indices = aux_sort_indices[:-1][mask]
  370. ar2_indices = aux_sort_indices[1:][mask] - ar1.size
  371. if not assume_unique:
  372. ar1_indices = ind1[ar1_indices]
  373. ar2_indices = ind2[ar2_indices]
  374. return int1d, ar1_indices, ar2_indices
  375. else:
  376. return int1d
  377. def _setxor1d_dispatcher(ar1, ar2, assume_unique=None):
  378. return (ar1, ar2)
  379. @array_function_dispatch(_setxor1d_dispatcher)
  380. def setxor1d(ar1, ar2, assume_unique=False):
  381. """
  382. Find the set exclusive-or of two arrays.
  383. Return the sorted, unique values that are in only one (not both) of the
  384. input arrays.
  385. Parameters
  386. ----------
  387. ar1, ar2 : array_like
  388. Input arrays.
  389. assume_unique : bool
  390. If True, the input arrays are both assumed to be unique, which
  391. can speed up the calculation. Default is False.
  392. Returns
  393. -------
  394. setxor1d : ndarray
  395. Sorted 1D array of unique values that are in only one of the input
  396. arrays.
  397. Examples
  398. --------
  399. >>> a = np.array([1, 2, 3, 2, 4])
  400. >>> b = np.array([2, 3, 5, 7, 5])
  401. >>> np.setxor1d(a,b)
  402. array([1, 4, 5, 7])
  403. """
  404. if not assume_unique:
  405. ar1 = unique(ar1)
  406. ar2 = unique(ar2)
  407. aux = np.concatenate((ar1, ar2))
  408. if aux.size == 0:
  409. return aux
  410. aux.sort()
  411. flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
  412. return aux[flag[1:] & flag[:-1]]
  413. def _in1d_dispatcher(ar1, ar2, assume_unique=None, invert=None):
  414. return (ar1, ar2)
  415. @array_function_dispatch(_in1d_dispatcher)
  416. def in1d(ar1, ar2, assume_unique=False, invert=False):
  417. """
  418. Test whether each element of a 1-D array is also present in a second array.
  419. Returns a boolean array the same length as `ar1` that is True
  420. where an element of `ar1` is in `ar2` and False otherwise.
  421. We recommend using :func:`isin` instead of `in1d` for new code.
  422. Parameters
  423. ----------
  424. ar1 : (M,) array_like
  425. Input array.
  426. ar2 : array_like
  427. The values against which to test each value of `ar1`.
  428. assume_unique : bool, optional
  429. If True, the input arrays are both assumed to be unique, which
  430. can speed up the calculation. Default is False.
  431. invert : bool, optional
  432. If True, the values in the returned array are inverted (that is,
  433. False where an element of `ar1` is in `ar2` and True otherwise).
  434. Default is False. ``np.in1d(a, b, invert=True)`` is equivalent
  435. to (but is faster than) ``np.invert(in1d(a, b))``.
  436. .. versionadded:: 1.8.0
  437. Returns
  438. -------
  439. in1d : (M,) ndarray, bool
  440. The values `ar1[in1d]` are in `ar2`.
  441. See Also
  442. --------
  443. isin : Version of this function that preserves the
  444. shape of ar1.
  445. numpy.lib.arraysetops : Module with a number of other functions for
  446. performing set operations on arrays.
  447. Notes
  448. -----
  449. `in1d` can be considered as an element-wise function version of the
  450. python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly
  451. equivalent to ``np.array([item in b for item in a])``.
  452. However, this idea fails if `ar2` is a set, or similar (non-sequence)
  453. container: As ``ar2`` is converted to an array, in those cases
  454. ``asarray(ar2)`` is an object array rather than the expected array of
  455. contained values.
  456. .. versionadded:: 1.4.0
  457. Examples
  458. --------
  459. >>> test = np.array([0, 1, 2, 5, 0])
  460. >>> states = [0, 2]
  461. >>> mask = np.in1d(test, states)
  462. >>> mask
  463. array([ True, False, True, False, True])
  464. >>> test[mask]
  465. array([0, 2, 0])
  466. >>> mask = np.in1d(test, states, invert=True)
  467. >>> mask
  468. array([False, True, False, True, False])
  469. >>> test[mask]
  470. array([1, 5])
  471. """
  472. # Ravel both arrays, behavior for the first array could be different
  473. ar1 = np.asarray(ar1).ravel()
  474. ar2 = np.asarray(ar2).ravel()
  475. # Ensure that iteration through object arrays yields size-1 arrays
  476. if ar2.dtype == object:
  477. ar2 = ar2.reshape(-1, 1)
  478. # Check if one of the arrays may contain arbitrary objects
  479. contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject
  480. # This code is run when
  481. # a) the first condition is true, making the code significantly faster
  482. # b) the second condition is true (i.e. `ar1` or `ar2` may contain
  483. # arbitrary objects), since then sorting is not guaranteed to work
  484. if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:
  485. if invert:
  486. mask = np.ones(len(ar1), dtype=bool)
  487. for a in ar2:
  488. mask &= (ar1 != a)
  489. else:
  490. mask = np.zeros(len(ar1), dtype=bool)
  491. for a in ar2:
  492. mask |= (ar1 == a)
  493. return mask
  494. # Otherwise use sorting
  495. if not assume_unique:
  496. ar1, rev_idx = np.unique(ar1, return_inverse=True)
  497. ar2 = np.unique(ar2)
  498. ar = np.concatenate((ar1, ar2))
  499. # We need this to be a stable sort, so always use 'mergesort'
  500. # here. The values from the first array should always come before
  501. # the values from the second array.
  502. order = ar.argsort(kind='mergesort')
  503. sar = ar[order]
  504. if invert:
  505. bool_ar = (sar[1:] != sar[:-1])
  506. else:
  507. bool_ar = (sar[1:] == sar[:-1])
  508. flag = np.concatenate((bool_ar, [invert]))
  509. ret = np.empty(ar.shape, dtype=bool)
  510. ret[order] = flag
  511. if assume_unique:
  512. return ret[:len(ar1)]
  513. else:
  514. return ret[rev_idx]
  515. def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None):
  516. return (element, test_elements)
  517. @array_function_dispatch(_isin_dispatcher)
  518. def isin(element, test_elements, assume_unique=False, invert=False):
  519. """
  520. Calculates `element in test_elements`, broadcasting over `element` only.
  521. Returns a boolean array of the same shape as `element` that is True
  522. where an element of `element` is in `test_elements` and False otherwise.
  523. Parameters
  524. ----------
  525. element : array_like
  526. Input array.
  527. test_elements : array_like
  528. The values against which to test each value of `element`.
  529. This argument is flattened if it is an array or array_like.
  530. See notes for behavior with non-array-like parameters.
  531. assume_unique : bool, optional
  532. If True, the input arrays are both assumed to be unique, which
  533. can speed up the calculation. Default is False.
  534. invert : bool, optional
  535. If True, the values in the returned array are inverted, as if
  536. calculating `element not in test_elements`. Default is False.
  537. ``np.isin(a, b, invert=True)`` is equivalent to (but faster
  538. than) ``np.invert(np.isin(a, b))``.
  539. Returns
  540. -------
  541. isin : ndarray, bool
  542. Has the same shape as `element`. The values `element[isin]`
  543. are in `test_elements`.
  544. See Also
  545. --------
  546. in1d : Flattened version of this function.
  547. numpy.lib.arraysetops : Module with a number of other functions for
  548. performing set operations on arrays.
  549. Notes
  550. -----
  551. `isin` is an element-wise function version of the python keyword `in`.
  552. ``isin(a, b)`` is roughly equivalent to
  553. ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences.
  554. `element` and `test_elements` are converted to arrays if they are not
  555. already. If `test_elements` is a set (or other non-sequence collection)
  556. it will be converted to an object array with one element, rather than an
  557. array of the values contained in `test_elements`. This is a consequence
  558. of the `array` constructor's way of handling non-sequence collections.
  559. Converting the set to a list usually gives the desired behavior.
  560. .. versionadded:: 1.13.0
  561. Examples
  562. --------
  563. >>> element = 2*np.arange(4).reshape((2, 2))
  564. >>> element
  565. array([[0, 2],
  566. [4, 6]])
  567. >>> test_elements = [1, 2, 4, 8]
  568. >>> mask = np.isin(element, test_elements)
  569. >>> mask
  570. array([[False, True],
  571. [ True, False]])
  572. >>> element[mask]
  573. array([2, 4])
  574. The indices of the matched values can be obtained with `nonzero`:
  575. >>> np.nonzero(mask)
  576. (array([0, 1]), array([1, 0]))
  577. The test can also be inverted:
  578. >>> mask = np.isin(element, test_elements, invert=True)
  579. >>> mask
  580. array([[ True, False],
  581. [False, True]])
  582. >>> element[mask]
  583. array([0, 6])
  584. Because of how `array` handles sets, the following does not
  585. work as expected:
  586. >>> test_set = {1, 2, 4, 8}
  587. >>> np.isin(element, test_set)
  588. array([[False, False],
  589. [False, False]])
  590. Casting the set to a list gives the expected result:
  591. >>> np.isin(element, list(test_set))
  592. array([[False, True],
  593. [ True, False]])
  594. """
  595. element = np.asarray(element)
  596. return in1d(element, test_elements, assume_unique=assume_unique,
  597. invert=invert).reshape(element.shape)
  598. def _union1d_dispatcher(ar1, ar2):
  599. return (ar1, ar2)
  600. @array_function_dispatch(_union1d_dispatcher)
  601. def union1d(ar1, ar2):
  602. """
  603. Find the union of two arrays.
  604. Return the unique, sorted array of values that are in either of the two
  605. input arrays.
  606. Parameters
  607. ----------
  608. ar1, ar2 : array_like
  609. Input arrays. They are flattened if they are not already 1D.
  610. Returns
  611. -------
  612. union1d : ndarray
  613. Unique, sorted union of the input arrays.
  614. See Also
  615. --------
  616. numpy.lib.arraysetops : Module with a number of other functions for
  617. performing set operations on arrays.
  618. Examples
  619. --------
  620. >>> np.union1d([-1, 0, 1], [-2, 0, 2])
  621. array([-2, -1, 0, 1, 2])
  622. To find the union of more than two arrays, use functools.reduce:
  623. >>> from functools import reduce
  624. >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  625. array([1, 2, 3, 4, 6])
  626. """
  627. return unique(np.concatenate((ar1, ar2), axis=None))
  628. def _setdiff1d_dispatcher(ar1, ar2, assume_unique=None):
  629. return (ar1, ar2)
  630. @array_function_dispatch(_setdiff1d_dispatcher)
  631. def setdiff1d(ar1, ar2, assume_unique=False):
  632. """
  633. Find the set difference of two arrays.
  634. Return the unique values in `ar1` that are not in `ar2`.
  635. Parameters
  636. ----------
  637. ar1 : array_like
  638. Input array.
  639. ar2 : array_like
  640. Input comparison array.
  641. assume_unique : bool
  642. If True, the input arrays are both assumed to be unique, which
  643. can speed up the calculation. Default is False.
  644. Returns
  645. -------
  646. setdiff1d : ndarray
  647. 1D array of values in `ar1` that are not in `ar2`. The result
  648. is sorted when `assume_unique=False`, but otherwise only sorted
  649. if the input is sorted.
  650. See Also
  651. --------
  652. numpy.lib.arraysetops : Module with a number of other functions for
  653. performing set operations on arrays.
  654. Examples
  655. --------
  656. >>> a = np.array([1, 2, 3, 2, 4, 1])
  657. >>> b = np.array([3, 4, 5, 6])
  658. >>> np.setdiff1d(a, b)
  659. array([1, 2])
  660. """
  661. if assume_unique:
  662. ar1 = np.asarray(ar1).ravel()
  663. else:
  664. ar1 = unique(ar1)
  665. ar2 = unique(ar2)
  666. return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]