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

PythonNumpy

Python Problem Overview


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]

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

a_new = np.delete(a, 3, 0)

3 here is the index you wish to remove, and 0 is the axis (zero in this case if using 1D array). See np.delete

Solution 3 - Python

Here's a one-liner if a is a NumPy array:

>>> a[np.arange(len(a))!=3]
array([0, 1, 2, 4, 5, 5, 6, 7, 8, 9])

Solution 4 - Python

This should do it:

In [9]: np.hstack((a[:3], a[4:]))
Out[9]: array([0, 1, 2, 4, 5, 5, 6, 7, 8, 9])

If performance is an issue, the following will do it in place:

In [22]: a[3:-1] = a[4:]; a = a[:-1]

Solution 5 - Python

Another solution is to use the concatenate function of NumPy:

>>> x = np.arange(0,10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> i = 3
>>> np.concatenate((x[:i],x[(i+1):]))
array([0, 1, 2, 4, 5, 6, 7, 8, 9])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShanView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonJdogView Answer on Stackoverflow
Solution 3 - PythonAkuView Answer on Stackoverflow
Solution 4 - PythonNPEView Answer on Stackoverflow
Solution 5 - PythonAlexDCView Answer on Stackoverflow