+2 votes
in Programming Languages by (73.2k points)
I have a list / Numpy array and want to remove some of the elements from it. I can use 'for loop' and 'if condition' to perform this task. What is the best pythonic way to do this?

1 Answer

+2 votes
by (346k points)
selected by
 
Best answer

You can use 'in1d()' and 'isin()' functions of Numpy. Have a look at the following examples.

Approach 1:

>>> import numpy as np
>>> a=np.array([11,12,34,545,67,87,43,23,98,78,90])
>>> b=np.array([23,34])
>>> idx = (np.isin(a,b)==False).nonzero()[0]
>>> idx
array([ 0,  1,  3,  4,  5,  6,  8,  9, 10], dtype=int64)
>>> a[idx]
array([ 11,  12, 545,  67,  87,  43,  98,  78,  90])

Approach 2:

>>> idx = (np.in1d(a,b)==False).nonzero()[0]
>>> a[idx]
array([ 11,  12, 545,  67,  87,  43,  98,  78,  90])

Approach 3:

>>> c=np.array()
>>> for e in a:
...     if (e not in b):
...             c=np.append(c,e)
...
>>> c
array([ 11.,  12., 545.,  67.,  87.,  43.,  98.,  78.,  90.])

Maybe you are interested in approach 1 and 2.


...