Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get all the values from a NumPy array excluding a certain index?

Tags:

python

numpy

I have a NumPy array, and I want to retrieve all the elements except a certain index. For example, consider the following array

a = [0,1,2,3,4,5,5,6,7,8,9] 

If I specify index 3, then the resultant should be

a = [0,1,2,4,5,5,6,7,8,9] 
like image 298
Shan Avatar asked Sep 15 '11 10:09

Shan


People also ask

How do I remove a specific indices from a NumPy array?

To remove an element from a NumPy array: Specify the index of the element to remove. Call the numpy. delete() function on the array for the given index.

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.

How do you get the product of all of the elements in a NumPy array?

prod() in Python. numpy. prod() returns the product of array elements over a given axis.


1 Answers

Like resizing, removing elements from an NumPy array is a slow operation (especially for large arrays since it requires allocating space and copying all the data from the original array to the new array). It should be avoided if possible.

Often you can avoid it by working with a masked array instead. For example, consider the array a:

import numpy as np  a = np.array([0,1,2,3,4,5,5,6,7,8,9]) print(a) print(a.sum()) # [0 1 2 3 4 5 5 6 7 8 9] # 50 

We can mask its value at index 3 and can perform a summation which ignores masked elements:

a = np.ma.array(a, mask=False) a.mask[3] = True print(a) print(a.sum()) # [0 1 2 -- 4 5 5 6 7 8 9] # 47 

Masked arrays also support many operations besides sum.

If you really need to, it is also possible to remove masked elements using the compressed method:

print(a.compressed()) # [0 1 2 4 5 5 6 7 8 9] 

But as mentioned above, avoid it if possible.

like image 111
unutbu Avatar answered Sep 17 '22 17:09

unutbu