Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove numbers from a numpy array

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.

like image 270
dineshdileep Avatar asked Jan 26 '26 17:01

dineshdileep


1 Answers

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])
like image 74
Divakar Avatar answered Jan 28 '26 06:01

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!