Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract elements from numpy array, that are not in list of indexes

I want to do something similar to what was asked here NumPy array, change the values that are NOT in a list of indices, but not quite the same.

Consider a numpy array:

> a = np.array([0.2, 5.6, 88, 12, 1.3, 6, 8.9])

I know I can access its elements via a list of indexes, like:

> indxs = [1, 2, 5] 
> a[indxs]
array([  5.6,  88. ,   6. ])

But I also need to access those elements which are not in the indxs list. Naively, this is:

> a[not in indxs]
> array([0.2, 12, 1.3, 8.9])

What is the proper way to do this?

like image 728
Gabriel Avatar asked Nov 30 '16 17:11

Gabriel


People also ask

How do I extract an element from a NumPy array?

Using the logical_and() method The logical_and() method from the numpy package accepts multiple conditions or expressions as a parameter. Each of the conditions or the expressions should return a boolean value. These boolean values are used to extract the required elements from the array.

Can you unpack NumPy array?

To unpack elements of a uint8 array into a binary-valued output array, use the numpy. unpackbits() method in Python Numpy. The result is binary-valued (0 or 1). The axis is the dimension over which bit-unpacking is done.

Can you use list comprehension with NumPy array?

You can compare different lists and pick the elements you need. You can even even use Pandas Series or Numpy Arrays with List Comprehension.

How do you find the index of an element in an array in NumPy?

Using ndenumerate() function to find the Index of value It is usually used to find the first occurrence of the element in the given numpy array.


2 Answers

In [170]: a = np.array([0.2, 5.6, 88, 12, 1.3, 6, 8.9])
In [171]: idx=[1,2,5]
In [172]: a[idx]
Out[172]: array([  5.6,  88. ,   6. ])
In [173]: np.delete(a,idx)
Out[173]: array([  0.2,  12. ,   1.3,   8.9])

delete is more general than you really need, using different strategies depending on the inputs. I think in this case it uses the boolean mask approach (timings should be similar).

In [175]: mask=np.ones_like(a, bool)
In [176]: mask
Out[176]: array([ True,  True,  True,  True,  True,  True,  True], dtype=bool)
In [177]: mask[idx]=False
In [178]: mask
Out[178]: array([ True, False, False,  True,  True, False,  True], dtype=bool)
In [179]: a[mask]
Out[179]: array([  0.2,  12. ,   1.3,   8.9])
like image 151
hpaulj Avatar answered Sep 22 '22 00:09

hpaulj


One way is to use a boolean mask and just invert the indices to be false:

mask = np.ones(a.size, dtype=bool)
mask[indxs] = False
a[mask]
like image 29
mgilson Avatar answered Sep 22 '22 00:09

mgilson