Remove Elements from a NumPy Array in a specific order

This tutorial will discuss about unique ways to remove elements from a numpy array in a specific order.

Suppose we have an NumPy Array containing city names. Like this,

```# create sample numpy array
cityNames = np.array([
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Phoenix',
```

now we want to delete the elements at index position 2, 5, and 1.

First of all we will sort the given index positions in the reverse order. Basically in the descending order. Then we will iterate over all the index positions that we want to delete from the array one by one, and for each index position we will delete the element at that specific index position from the array.

```# Specify indices of elements to
# remove in order
indices = [2, 5, 1]

# Sort the indices in descending order
indices.sort(reverse=True)

# Remove elements from the array
# in the specified order
for i in indices:
cityNames = np.delete(cityNames, i)
```

As we are I treating from largest index position to smallest index position ,so we can safely use the numpy.delete() function to delete the elements.

Let’s see the complete example,

```import numpy as np

# create sample numpy array
cityNames = np.array([
'New York',
'Los Angeles',
'Chicago',
'Houston',
'Phoenix',

print('Before removing elements:')
print(cityNames)

# Specify indices of elements to
# remove in order
indices = [2, 5, 1]

# Sort the indices in descending order
indices.sort(reverse=True)

# Remove elements from the array
# in the specified order
for i in indices:
cityNames = np.delete(cityNames, i)

print('After removing elements:')
print(cityNames)
```

Output

```Before removing elements:
['New York' 'Los Angeles' 'Chicago' 'Houston' 'Phoenix' 'Philadelphia']

After removing elements:
['New York' 'Houston' 'Phoenix']

```

Summary

We learned how to delete elements from a NumPy Array in a specific order.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top