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).
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.
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.
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.
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)
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With