Let us say I have a numpy array of numbers (eg: integers). I want to drop the number k wherever it happens in the sequence. Currently I am writing a for loop for this which seems to be a overkill. Is there a straight forward way to do it? In general, what if I have one more than one number to be dropped.
Assuming A to the input array and B to be the array containing the numbers to be removed, you can use np.in1d to get a mask of matches of B in A and then use an inverted version of the mask to map A and get the desired output. Here's how the implementation would look like -
A[~np.in1d(A,B).reshape(A.shape)]
Sample run -
In [14]: A
Out[14]: array([3, 2, 1, 4, 3, 3, 2, 2, 4, 1])
In [15]: B
Out[15]: array([2, 4])
In [16]: A[~np.in1d(A,B).reshape(A.shape)]
Out[16]: array([3, 1, 3, 3, 1])
For a 2D input array case, you would get a 1D array as output, like so -
In [21]: A
Out[21]:
array([[3, 3, 3, 4, 0, 4],
[2, 4, 4, 4, 4, 3],
[1, 2, 4, 4, 3, 1],
[0, 3, 1, 4, 1, 1]])
In [22]: B
Out[22]: array([2, 4])
In [23]: A[~np.in1d(A,B).reshape(A.shape)]
Out[23]: array([3, 3, 3, 0, 3, 1, 3, 1, 0, 3, 1, 1, 1])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With