Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all elements in a NumPy array except for a sequence of indices [duplicate]

Say I have some long array and a list of indices. How can I select everything except those indices? I found a solution but it is not elegant:

import numpy as np x = np.array([0,10,20,30,40,50,60]) exclude = [1, 3, 5] print x[list(set(range(len(x))) - set(exclude))] 
like image 592
kilojoules Avatar asked Nov 28 '17 20:11

kilojoules


People also ask

How do I get all the elements of a NumPy array?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do I remove duplicates from a NumPy array in Python?

The unique() method is a built-in method in the numpy, that takes an array as input and return a unique array i.e by removing all the duplicate elements. In order to remove duplicates we will pass the given NumPy array to the unique() method and it will return the unique array.

What is NumPy fancy indexing?

Fancy indexing is conceptually simple: it means passing an array of indices to access multiple array elements at once. For example, consider the following array: import numpy as np rand = np. random. RandomState(42) x = rand.

How do I select a specific index in a NumPy array?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.


2 Answers

This is what numpy.delete does. (It doesn't modify the input array, so you don't have to worry about that.)

In [4]: np.delete(x, exclude) Out[4]: array([ 0, 20, 40, 60]) 
like image 153
user2357112 supports Monica Avatar answered Oct 16 '22 10:10

user2357112 supports Monica


np.delete does various things depending what you give it, but in a case like this it uses a mask like:

In [604]: mask = np.ones(x.shape, bool) In [605]: mask[exclude] = False In [606]: mask Out[606]: array([ True, False,  True, False,  True, False,  True], dtype=bool) In [607]: x[mask] Out[607]: array([ 0, 20, 40, 60]) 
like image 20
hpaulj Avatar answered Oct 16 '22 10:10

hpaulj