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,
Frequently Asked:
- Remove All Occurrences of a Value from NumPy Array
- How to Delete Rows from a NumPy Array
- How to Remove Element from a NumPy Array?
- Remove elements from NumPy Array by Index
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.