Numpy - check if elements of a array belong to another array Numpy - check if elements of a array belong to another array numpy numpy

Numpy - check if elements of a array belong to another array


You can make use of numpy.in1d, the rest is pretty simple:

The key part:

In [25]: np.in1d(xarr, y)Out[25]: array([ True,  True, False, False, False], dtype=bool)

Whole example:

In [16]: result = np.empty(len(xarr), dtype=object)In [17]: resultOut[17]: array([None, None, None, None, None], dtype=object)In [18]: result.fill("n")In [19]: resultOut[19]: array(['n', 'n', 'n', 'n', 'n'], dtype=object)In [20]: result[np.in1d(xarr, y)] = 'y'In [21]: resultOut[21]: array(['y', 'y', 'n', 'n', 'n'], dtype=object)In [23]: result[xarr == 1.3] = 'y1'In [24]: resultOut[24]: array(['y', 'y', 'y1', 'n', 'n'], dtype=object)

Edit:

A small modification of your original attempt:

In [16]: x = np.where(np.in1d(xarr, y),"y",np.where(xarr == 1.3,"y1","n"))In [17]: xOut[17]: array(['y', 'y', 'y1', 'n', 'n'],       dtype='|S2')

The problem in your original attempt was that xarr in y gives just False.


Check np.isin().

isin is an element-wise function version of the python keyword in.

isin(a, b) is roughly equivalent to np.array([item in b for item in a]) if a and b are 1-D sequences.