Remove The Middle Element from a NumPy Array

This tutorial will discuss about unique ways to remove the middle element from a numpy array.

Suppose we have a numpy array of strings. Like this,

city_names = np.array([ 'New York',
                        'Los Angeles',
                        'Chicago',
                        'Houston',
                        'Phoenix',
                        'Philadelphia'])

Now, we want to remove an element from the middle of this numpy array.

To remove an element from the middle of the numpy array, first we need to get the index position of the middle element of the numpy array. That we can fetch easily by dividing its length by 2 i.e.

len(city_names) // 2

It will give us the index position of the middle element of the array. Then we can use the delete() function of numpy module to delete the element at that specific index position.

# remove middle element from the array
city_names = np.delete(city_names, len(city_names) // 2)

In the below code, we have a numpy array of city names and we will be deleting an element from the middle of this numpy array.

Let’s see the complete example,

import numpy as np

# create sample numpy array
city_names = np.array([ 'New York',
                        'Los Angeles',
                        'Chicago',
                        'Houston',
                        'Phoenix',
                        'Philadelphia'])

print('Before removing element:')
print(city_names)

# remove middle element from the array
city_names = np.delete(city_names, len(city_names) // 2)

print('After removing element:')
print(city_names)

Output

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


After removing element:
['New York' 'Los Angeles' 'Chicago' 'Phoenix' 'Philadelphia']

Summary

We learned how to remove element from the middle of a NumPy Array in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

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

Scroll to Top