arraysetops.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. """
  2. Set operations for arrays based on sorting.
  3. :Contains:
  4. unique,
  5. isin,
  6. ediff1d,
  7. intersect1d,
  8. setxor1d,
  9. in1d,
  10. union1d,
  11. setdiff1d
  12. :Notes:
  13. For floating point arrays, inaccurate results may appear due to usual round-off
  14. and floating point comparison issues.
  15. Speed could be gained in some operations by an implementation of
  16. sort(), that can provide directly the permutation vectors, avoiding
  17. thus calls to argsort().
  18. To do: Optionally return indices analogously to unique for all functions.
  19. :Author: Robert Cimrman
  20. """
  21. from __future__ import division, absolute_import, print_function
  22. import functools
  23. import numpy as np
  24. from numpy.core import overrides
  25. array_function_dispatch = functools.partial(
  26. overrides.array_function_dispatch, module='numpy')
  27. __all__ = [
  28. 'ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', 'unique',
  29. 'in1d', 'isin'
  30. ]
  31. def _ediff1d_dispatcher(ary, to_end=None, to_begin=None):
  32. return (ary, to_end, to_begin)
  33. @array_function_dispatch(_ediff1d_dispatcher)
  34. def ediff1d(ary, to_end=None, to_begin=None):
  35. """
  36. The differences between consecutive elements of an array.
  37. Parameters
  38. ----------
  39. ary : array_like
  40. If necessary, will be flattened before the differences are taken.
  41. to_end : array_like, optional
  42. Number(s) to append at the end of the returned differences.
  43. to_begin : array_like, optional
  44. Number(s) to prepend at the beginning of the returned differences.
  45. Returns
  46. -------
  47. ediff1d : ndarray
  48. The differences. Loosely, this is ``ary.flat[1:] - ary.flat[:-1]``.
  49. See Also
  50. --------
  51. diff, gradient
  52. Notes
  53. -----
  54. When applied to masked arrays, this function drops the mask information
  55. if the `to_begin` and/or `to_end` parameters are used.
  56. Examples
  57. --------
  58. >>> x = np.array([1, 2, 4, 7, 0])
  59. >>> np.ediff1d(x)
  60. array([ 1, 2, 3, -7])
  61. >>> np.ediff1d(x, to_begin=-99, to_end=np.array([88, 99]))
  62. array([-99, 1, 2, 3, -7, 88, 99])
  63. The returned array is always 1D.
  64. >>> y = [[1, 2, 4], [1, 6, 24]]
  65. >>> np.ediff1d(y)
  66. array([ 1, 2, -3, 5, 18])
  67. """
  68. # force a 1d array
  69. ary = np.asanyarray(ary).ravel()
  70. # enforce propagation of the dtype of input
  71. # ary to returned result
  72. dtype_req = ary.dtype
  73. # fast track default case
  74. if to_begin is None and to_end is None:
  75. return ary[1:] - ary[:-1]
  76. if to_begin is None:
  77. l_begin = 0
  78. else:
  79. _to_begin = np.asanyarray(to_begin, dtype=dtype_req)
  80. if not np.all(_to_begin == to_begin):
  81. raise ValueError("cannot convert 'to_begin' to array with dtype "
  82. "'%r' as required for input ary" % dtype_req)
  83. to_begin = _to_begin.ravel()
  84. l_begin = len(to_begin)
  85. if to_end is None:
  86. l_end = 0
  87. else:
  88. _to_end = np.asanyarray(to_end, dtype=dtype_req)
  89. # check that casting has not overflowed
  90. if not np.all(_to_end == to_end):
  91. raise ValueError("cannot convert 'to_end' to array with dtype "
  92. "'%r' as required for input ary" % dtype_req)
  93. to_end = _to_end.ravel()
  94. l_end = len(to_end)
  95. # do the calculation in place and copy to_begin and to_end
  96. l_diff = max(len(ary) - 1, 0)
  97. result = np.empty(l_diff + l_begin + l_end, dtype=ary.dtype)
  98. result = ary.__array_wrap__(result)
  99. if l_begin > 0:
  100. result[:l_begin] = to_begin
  101. if l_end > 0:
  102. result[l_begin + l_diff:] = to_end
  103. np.subtract(ary[1:], ary[:-1], result[l_begin:l_begin + l_diff])
  104. return result
  105. def _unpack_tuple(x):
  106. """ Unpacks one-element tuples for use as return values """
  107. if len(x) == 1:
  108. return x[0]
  109. else:
  110. return x
  111. def _unique_dispatcher(ar, return_index=None, return_inverse=None,
  112. return_counts=None, axis=None):
  113. return (ar,)
  114. @array_function_dispatch(_unique_dispatcher)
  115. def unique(ar, return_index=False, return_inverse=False,
  116. return_counts=False, axis=None):
  117. """
  118. Find the unique elements of an array.
  119. Returns the sorted unique elements of an array. There are three optional
  120. outputs in addition to the unique elements:
  121. * the indices of the input array that give the unique values
  122. * the indices of the unique array that reconstruct the input array
  123. * the number of times each unique value comes up in the input array
  124. Parameters
  125. ----------
  126. ar : array_like
  127. Input array. Unless `axis` is specified, this will be flattened if it
  128. is not already 1-D.
  129. return_index : bool, optional
  130. If True, also return the indices of `ar` (along the specified axis,
  131. if provided, or in the flattened array) that result in the unique array.
  132. return_inverse : bool, optional
  133. If True, also return the indices of the unique array (for the specified
  134. axis, if provided) that can be used to reconstruct `ar`.
  135. return_counts : bool, optional
  136. If True, also return the number of times each unique item appears
  137. in `ar`.
  138. .. versionadded:: 1.9.0
  139. axis : int or None, optional
  140. The axis to operate on. If None, `ar` will be flattened. If an integer,
  141. the subarrays indexed by the given axis will be flattened and treated
  142. as the elements of a 1-D array with the dimension of the given axis,
  143. see the notes for more details. Object arrays or structured arrays
  144. that contain objects are not supported if the `axis` kwarg is used. The
  145. default is None.
  146. .. versionadded:: 1.13.0
  147. Returns
  148. -------
  149. unique : ndarray
  150. The sorted unique values.
  151. unique_indices : ndarray, optional
  152. The indices of the first occurrences of the unique values in the
  153. original array. Only provided if `return_index` is True.
  154. unique_inverse : ndarray, optional
  155. The indices to reconstruct the original array from the
  156. unique array. Only provided if `return_inverse` is True.
  157. unique_counts : ndarray, optional
  158. The number of times each of the unique values comes up in the
  159. original array. Only provided if `return_counts` is True.
  160. .. versionadded:: 1.9.0
  161. See Also
  162. --------
  163. numpy.lib.arraysetops : Module with a number of other functions for
  164. performing set operations on arrays.
  165. Notes
  166. -----
  167. When an axis is specified the subarrays indexed by the axis are sorted.
  168. This is done by making the specified axis the first dimension of the array
  169. and then flattening the subarrays in C order. The flattened subarrays are
  170. then viewed as a structured type with each element given a label, with the
  171. effect that we end up with a 1-D array of structured types that can be
  172. treated in the same way as any other 1-D array. The result is that the
  173. flattened subarrays are sorted in lexicographic order starting with the
  174. first element.
  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'],
  191. dtype='|S1')
  192. >>> indices
  193. array([0, 1, 3])
  194. >>> a[indices]
  195. array(['a', 'b', 'c'],
  196. dtype='|S1')
  197. Reconstruct the input array from the unique values:
  198. >>> a = np.array([1, 2, 6, 4, 2, 3, 2])
  199. >>> u, indices = np.unique(a, return_inverse=True)
  200. >>> u
  201. array([1, 2, 3, 4, 6])
  202. >>> indices
  203. array([0, 1, 4, 3, 1, 2, 1])
  204. >>> u[indices]
  205. array([1, 2, 6, 4, 2, 3, 2])
  206. """
  207. ar = np.asanyarray(ar)
  208. if axis is None:
  209. ret = _unique1d(ar, return_index, return_inverse, return_counts)
  210. return _unpack_tuple(ret)
  211. # axis was specified and not None
  212. try:
  213. ar = np.swapaxes(ar, axis, 0)
  214. except np.AxisError:
  215. # this removes the "axis1" or "axis2" prefix from the error message
  216. raise np.AxisError(axis, ar.ndim)
  217. # Must reshape to a contiguous 2D array for this to work...
  218. orig_shape, orig_dtype = ar.shape, ar.dtype
  219. ar = ar.reshape(orig_shape[0], -1)
  220. ar = np.ascontiguousarray(ar)
  221. dtype = [('f{i}'.format(i=i), ar.dtype) for i in range(ar.shape[1])]
  222. try:
  223. consolidated = ar.view(dtype)
  224. except TypeError:
  225. # There's no good way to do this for object arrays, etc...
  226. msg = 'The axis argument to unique is not supported for dtype {dt}'
  227. raise TypeError(msg.format(dt=ar.dtype))
  228. def reshape_uniq(uniq):
  229. uniq = uniq.view(orig_dtype)
  230. uniq = uniq.reshape(-1, *orig_shape[1:])
  231. uniq = np.swapaxes(uniq, 0, axis)
  232. return uniq
  233. output = _unique1d(consolidated, return_index,
  234. return_inverse, return_counts)
  235. output = (reshape_uniq(output[0]),) + output[1:]
  236. return _unpack_tuple(output)
  237. def _unique1d(ar, return_index=False, return_inverse=False,
  238. return_counts=False):
  239. """
  240. Find the unique elements of an array, ignoring shape.
  241. """
  242. ar = np.asanyarray(ar).flatten()
  243. optional_indices = return_index or return_inverse
  244. if optional_indices:
  245. perm = ar.argsort(kind='mergesort' if return_index else 'quicksort')
  246. aux = ar[perm]
  247. else:
  248. ar.sort()
  249. aux = ar
  250. mask = np.empty(aux.shape, dtype=np.bool_)
  251. mask[:1] = True
  252. mask[1:] = aux[1:] != aux[:-1]
  253. ret = (aux[mask],)
  254. if return_index:
  255. ret += (perm[mask],)
  256. if return_inverse:
  257. imask = np.cumsum(mask) - 1
  258. inv_idx = np.empty(mask.shape, dtype=np.intp)
  259. inv_idx[perm] = imask
  260. ret += (inv_idx,)
  261. if return_counts:
  262. idx = np.concatenate(np.nonzero(mask) + ([mask.size],))
  263. ret += (np.diff(idx),)
  264. return ret
  265. def _intersect1d_dispatcher(
  266. ar1, ar2, assume_unique=None, return_indices=None):
  267. return (ar1, ar2)
  268. @array_function_dispatch(_intersect1d_dispatcher)
  269. def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):
  270. """
  271. Find the intersection of two arrays.
  272. Return the sorted, unique values that are in both of the input arrays.
  273. Parameters
  274. ----------
  275. ar1, ar2 : array_like
  276. Input arrays. Will be flattened if not already 1D.
  277. assume_unique : bool
  278. If True, the input arrays are both assumed to be unique, which
  279. can speed up the calculation. Default is False.
  280. return_indices : bool
  281. If True, the indices which correspond to the intersection of the two
  282. arrays are returned. The first instance of a value is used if there are
  283. multiple. Default is False.
  284. .. versionadded:: 1.15.0
  285. Returns
  286. -------
  287. intersect1d : ndarray
  288. Sorted 1D array of common and unique elements.
  289. comm1 : ndarray
  290. The indices of the first occurrences of the common values in `ar1`.
  291. Only provided if `return_indices` is True.
  292. comm2 : ndarray
  293. The indices of the first occurrences of the common values in `ar2`.
  294. Only provided if `return_indices` is True.
  295. See Also
  296. --------
  297. numpy.lib.arraysetops : Module with a number of other functions for
  298. performing set operations on arrays.
  299. Examples
  300. --------
  301. >>> np.intersect1d([1, 3, 4, 3], [3, 1, 2, 1])
  302. array([1, 3])
  303. To intersect more than two arrays, use functools.reduce:
  304. >>> from functools import reduce
  305. >>> reduce(np.intersect1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  306. array([3])
  307. To return the indices of the values common to the input arrays
  308. along with the intersected values:
  309. >>> x = np.array([1, 1, 2, 3, 4])
  310. >>> y = np.array([2, 1, 4, 6])
  311. >>> xy, x_ind, y_ind = np.intersect1d(x, y, return_indices=True)
  312. >>> x_ind, y_ind
  313. (array([0, 2, 4]), array([1, 0, 2]))
  314. >>> xy, x[x_ind], y[y_ind]
  315. (array([1, 2, 4]), array([1, 2, 4]), array([1, 2, 4]))
  316. """
  317. ar1 = np.asanyarray(ar1)
  318. ar2 = np.asanyarray(ar2)
  319. if not assume_unique:
  320. if return_indices:
  321. ar1, ind1 = unique(ar1, return_index=True)
  322. ar2, ind2 = unique(ar2, return_index=True)
  323. else:
  324. ar1 = unique(ar1)
  325. ar2 = unique(ar2)
  326. else:
  327. ar1 = ar1.ravel()
  328. ar2 = ar2.ravel()
  329. aux = np.concatenate((ar1, ar2))
  330. if return_indices:
  331. aux_sort_indices = np.argsort(aux, kind='mergesort')
  332. aux = aux[aux_sort_indices]
  333. else:
  334. aux.sort()
  335. mask = aux[1:] == aux[:-1]
  336. int1d = aux[:-1][mask]
  337. if return_indices:
  338. ar1_indices = aux_sort_indices[:-1][mask]
  339. ar2_indices = aux_sort_indices[1:][mask] - ar1.size
  340. if not assume_unique:
  341. ar1_indices = ind1[ar1_indices]
  342. ar2_indices = ind2[ar2_indices]
  343. return int1d, ar1_indices, ar2_indices
  344. else:
  345. return int1d
  346. def _setxor1d_dispatcher(ar1, ar2, assume_unique=None):
  347. return (ar1, ar2)
  348. @array_function_dispatch(_setxor1d_dispatcher)
  349. def setxor1d(ar1, ar2, assume_unique=False):
  350. """
  351. Find the set exclusive-or of two arrays.
  352. Return the sorted, unique values that are in only one (not both) of the
  353. input arrays.
  354. Parameters
  355. ----------
  356. ar1, ar2 : array_like
  357. Input arrays.
  358. assume_unique : bool
  359. If True, the input arrays are both assumed to be unique, which
  360. can speed up the calculation. Default is False.
  361. Returns
  362. -------
  363. setxor1d : ndarray
  364. Sorted 1D array of unique values that are in only one of the input
  365. arrays.
  366. Examples
  367. --------
  368. >>> a = np.array([1, 2, 3, 2, 4])
  369. >>> b = np.array([2, 3, 5, 7, 5])
  370. >>> np.setxor1d(a,b)
  371. array([1, 4, 5, 7])
  372. """
  373. if not assume_unique:
  374. ar1 = unique(ar1)
  375. ar2 = unique(ar2)
  376. aux = np.concatenate((ar1, ar2))
  377. if aux.size == 0:
  378. return aux
  379. aux.sort()
  380. flag = np.concatenate(([True], aux[1:] != aux[:-1], [True]))
  381. return aux[flag[1:] & flag[:-1]]
  382. def _in1d_dispatcher(ar1, ar2, assume_unique=None, invert=None):
  383. return (ar1, ar2)
  384. @array_function_dispatch(_in1d_dispatcher)
  385. def in1d(ar1, ar2, assume_unique=False, invert=False):
  386. """
  387. Test whether each element of a 1-D array is also present in a second array.
  388. Returns a boolean array the same length as `ar1` that is True
  389. where an element of `ar1` is in `ar2` and False otherwise.
  390. We recommend using :func:`isin` instead of `in1d` for new code.
  391. Parameters
  392. ----------
  393. ar1 : (M,) array_like
  394. Input array.
  395. ar2 : array_like
  396. The values against which to test each value of `ar1`.
  397. assume_unique : bool, optional
  398. If True, the input arrays are both assumed to be unique, which
  399. can speed up the calculation. Default is False.
  400. invert : bool, optional
  401. If True, the values in the returned array are inverted (that is,
  402. False where an element of `ar1` is in `ar2` and True otherwise).
  403. Default is False. ``np.in1d(a, b, invert=True)`` is equivalent
  404. to (but is faster than) ``np.invert(in1d(a, b))``.
  405. .. versionadded:: 1.8.0
  406. Returns
  407. -------
  408. in1d : (M,) ndarray, bool
  409. The values `ar1[in1d]` are in `ar2`.
  410. See Also
  411. --------
  412. isin : Version of this function that preserves the
  413. shape of ar1.
  414. numpy.lib.arraysetops : Module with a number of other functions for
  415. performing set operations on arrays.
  416. Notes
  417. -----
  418. `in1d` can be considered as an element-wise function version of the
  419. python keyword `in`, for 1-D sequences. ``in1d(a, b)`` is roughly
  420. equivalent to ``np.array([item in b for item in a])``.
  421. However, this idea fails if `ar2` is a set, or similar (non-sequence)
  422. container: As ``ar2`` is converted to an array, in those cases
  423. ``asarray(ar2)`` is an object array rather than the expected array of
  424. contained values.
  425. .. versionadded:: 1.4.0
  426. Examples
  427. --------
  428. >>> test = np.array([0, 1, 2, 5, 0])
  429. >>> states = [0, 2]
  430. >>> mask = np.in1d(test, states)
  431. >>> mask
  432. array([ True, False, True, False, True])
  433. >>> test[mask]
  434. array([0, 2, 0])
  435. >>> mask = np.in1d(test, states, invert=True)
  436. >>> mask
  437. array([False, True, False, True, False])
  438. >>> test[mask]
  439. array([1, 5])
  440. """
  441. # Ravel both arrays, behavior for the first array could be different
  442. ar1 = np.asarray(ar1).ravel()
  443. ar2 = np.asarray(ar2).ravel()
  444. # Check if one of the arrays may contain arbitrary objects
  445. contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject
  446. # This code is run when
  447. # a) the first condition is true, making the code significantly faster
  448. # b) the second condition is true (i.e. `ar1` or `ar2` may contain
  449. # arbitrary objects), since then sorting is not guaranteed to work
  450. if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:
  451. if invert:
  452. mask = np.ones(len(ar1), dtype=bool)
  453. for a in ar2:
  454. mask &= (ar1 != a)
  455. else:
  456. mask = np.zeros(len(ar1), dtype=bool)
  457. for a in ar2:
  458. mask |= (ar1 == a)
  459. return mask
  460. # Otherwise use sorting
  461. if not assume_unique:
  462. ar1, rev_idx = np.unique(ar1, return_inverse=True)
  463. ar2 = np.unique(ar2)
  464. ar = np.concatenate((ar1, ar2))
  465. # We need this to be a stable sort, so always use 'mergesort'
  466. # here. The values from the first array should always come before
  467. # the values from the second array.
  468. order = ar.argsort(kind='mergesort')
  469. sar = ar[order]
  470. if invert:
  471. bool_ar = (sar[1:] != sar[:-1])
  472. else:
  473. bool_ar = (sar[1:] == sar[:-1])
  474. flag = np.concatenate((bool_ar, [invert]))
  475. ret = np.empty(ar.shape, dtype=bool)
  476. ret[order] = flag
  477. if assume_unique:
  478. return ret[:len(ar1)]
  479. else:
  480. return ret[rev_idx]
  481. def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None):
  482. return (element, test_elements)
  483. @array_function_dispatch(_isin_dispatcher)
  484. def isin(element, test_elements, assume_unique=False, invert=False):
  485. """
  486. Calculates `element in test_elements`, broadcasting over `element` only.
  487. Returns a boolean array of the same shape as `element` that is True
  488. where an element of `element` is in `test_elements` and False otherwise.
  489. Parameters
  490. ----------
  491. element : array_like
  492. Input array.
  493. test_elements : array_like
  494. The values against which to test each value of `element`.
  495. This argument is flattened if it is an array or array_like.
  496. See notes for behavior with non-array-like parameters.
  497. assume_unique : bool, optional
  498. If True, the input arrays are both assumed to be unique, which
  499. can speed up the calculation. Default is False.
  500. invert : bool, optional
  501. If True, the values in the returned array are inverted, as if
  502. calculating `element not in test_elements`. Default is False.
  503. ``np.isin(a, b, invert=True)`` is equivalent to (but faster
  504. than) ``np.invert(np.isin(a, b))``.
  505. Returns
  506. -------
  507. isin : ndarray, bool
  508. Has the same shape as `element`. The values `element[isin]`
  509. are in `test_elements`.
  510. See Also
  511. --------
  512. in1d : Flattened version of this function.
  513. numpy.lib.arraysetops : Module with a number of other functions for
  514. performing set operations on arrays.
  515. Notes
  516. -----
  517. `isin` is an element-wise function version of the python keyword `in`.
  518. ``isin(a, b)`` is roughly equivalent to
  519. ``np.array([item in b for item in a])`` if `a` and `b` are 1-D sequences.
  520. `element` and `test_elements` are converted to arrays if they are not
  521. already. If `test_elements` is a set (or other non-sequence collection)
  522. it will be converted to an object array with one element, rather than an
  523. array of the values contained in `test_elements`. This is a consequence
  524. of the `array` constructor's way of handling non-sequence collections.
  525. Converting the set to a list usually gives the desired behavior.
  526. .. versionadded:: 1.13.0
  527. Examples
  528. --------
  529. >>> element = 2*np.arange(4).reshape((2, 2))
  530. >>> element
  531. array([[0, 2],
  532. [4, 6]])
  533. >>> test_elements = [1, 2, 4, 8]
  534. >>> mask = np.isin(element, test_elements)
  535. >>> mask
  536. array([[ False, True],
  537. [ True, False]])
  538. >>> element[mask]
  539. array([2, 4])
  540. The indices of the matched values can be obtained with `nonzero`:
  541. >>> np.nonzero(mask)
  542. (array([0, 1]), array([1, 0]))
  543. The test can also be inverted:
  544. >>> mask = np.isin(element, test_elements, invert=True)
  545. >>> mask
  546. array([[ True, False],
  547. [ False, True]])
  548. >>> element[mask]
  549. array([0, 6])
  550. Because of how `array` handles sets, the following does not
  551. work as expected:
  552. >>> test_set = {1, 2, 4, 8}
  553. >>> np.isin(element, test_set)
  554. array([[ False, False],
  555. [ False, False]])
  556. Casting the set to a list gives the expected result:
  557. >>> np.isin(element, list(test_set))
  558. array([[ False, True],
  559. [ True, False]])
  560. """
  561. element = np.asarray(element)
  562. return in1d(element, test_elements, assume_unique=assume_unique,
  563. invert=invert).reshape(element.shape)
  564. def _union1d_dispatcher(ar1, ar2):
  565. return (ar1, ar2)
  566. @array_function_dispatch(_union1d_dispatcher)
  567. def union1d(ar1, ar2):
  568. """
  569. Find the union of two arrays.
  570. Return the unique, sorted array of values that are in either of the two
  571. input arrays.
  572. Parameters
  573. ----------
  574. ar1, ar2 : array_like
  575. Input arrays. They are flattened if they are not already 1D.
  576. Returns
  577. -------
  578. union1d : ndarray
  579. Unique, sorted union of the input arrays.
  580. See Also
  581. --------
  582. numpy.lib.arraysetops : Module with a number of other functions for
  583. performing set operations on arrays.
  584. Examples
  585. --------
  586. >>> np.union1d([-1, 0, 1], [-2, 0, 2])
  587. array([-2, -1, 0, 1, 2])
  588. To find the union of more than two arrays, use functools.reduce:
  589. >>> from functools import reduce
  590. >>> reduce(np.union1d, ([1, 3, 4, 3], [3, 1, 2, 1], [6, 3, 4, 2]))
  591. array([1, 2, 3, 4, 6])
  592. """
  593. return unique(np.concatenate((ar1, ar2), axis=None))
  594. def _setdiff1d_dispatcher(ar1, ar2, assume_unique=None):
  595. return (ar1, ar2)
  596. @array_function_dispatch(_setdiff1d_dispatcher)
  597. def setdiff1d(ar1, ar2, assume_unique=False):
  598. """
  599. Find the set difference of two arrays.
  600. Return the unique values in `ar1` that are not in `ar2`.
  601. Parameters
  602. ----------
  603. ar1 : array_like
  604. Input array.
  605. ar2 : array_like
  606. Input comparison array.
  607. assume_unique : bool
  608. If True, the input arrays are both assumed to be unique, which
  609. can speed up the calculation. Default is False.
  610. Returns
  611. -------
  612. setdiff1d : ndarray
  613. 1D array of values in `ar1` that are not in `ar2`. The result
  614. is sorted when `assume_unique=False`, but otherwise only sorted
  615. if the input is sorted.
  616. See Also
  617. --------
  618. numpy.lib.arraysetops : Module with a number of other functions for
  619. performing set operations on arrays.
  620. Examples
  621. --------
  622. >>> a = np.array([1, 2, 3, 2, 4, 1])
  623. >>> b = np.array([3, 4, 5, 6])
  624. >>> np.setdiff1d(a, b)
  625. array([1, 2])
  626. """
  627. if assume_unique:
  628. ar1 = np.asarray(ar1).ravel()
  629. else:
  630. ar1 = unique(ar1)
  631. ar2 = unique(ar2)
  632. return ar1[in1d(ar1, ar2, assume_unique=True, invert=True)]