Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing NumPy array elements not in a given index list

Tags:

python

numpy

I have a NumPy array with the shape (100, 170, 256). And I have an array consisting of indexes [0, 10, 20, 40, 70].

I can get the sub-arrays corresponding to the indexes as follows:

sub_array = array[..., index] 

This returns an array with the shape (100, 170, 5) as expected. Now, I am trying to take the complement and get the sub-array NOT corresponding to those indexes. So, I did:

sub_array = array[..., ~index] 

This still returns me an array of shape (100, 170, 5) for some reason. I wonder how to do this complement operation of these indexes in python?

[EDIT]

Also tried:

sub_array = array[..., not(index.any)] 

However, this does not do the thing I want as well (getting array of shape (100, 170, 251).

like image 808
Luca Avatar asked Jan 07 '15 16:01

Luca


People also ask

How do you access the elements of a NumPy Matrix?

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 you access individual elements of an array in Python?

Overview. An array in Python is used to store multiple values or items or elements of the same type in a single variable. We can access elements of an array using the index operator [] . All you need do in order to access a particular element is to call the array you created.

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.


2 Answers

The way you have your data, the simplest approach is to use np.delete:

sub_array = np.delete(array, index, axis=2) 

Alternatively, the logical operators you were trying to use can be applied with boolean arrays as @DSM suggests:

mask = np.ones(a.shape[2], dtype=bool) mask[index] = False sub_array = array[:,:, mask] 

(I wouldn't call your array array but I followed the names in your question)

like image 160
Ramon Crehuet Avatar answered Sep 27 '22 16:09

Ramon Crehuet


have a look at what ~index gives you - I think it is:

array([ -1, -11, -21, -41, -71]) 

So, your call

sub_array = array[..., ~index] 

will return 5 entries, corresponding to indices [ -1, -11, -21, -41, -71] i.e. 255, 245, 235, 215 and 185 in your case

Similarly, not(index.any) gives

False 

hence why your second try doesn't work

This should work:

sub_array = array[..., [i for i in xrange(256) if i not in index]] 
like image 30
J Richard Snape Avatar answered Sep 27 '22 15:09

J Richard Snape