_arraysetops_impl.py 38 KB

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