arraysetops.py 25 KB

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