This tutorial will discuss about unique ways to remove last n elements from a numpy array.
Suppose we have an NumPy array of numbers. Like this,
numbers = np.array([34, 35, 78, 61, 56, 35, 90, 35])
Now we want to remove last N elements from this array. For this we are going to use the slicing feature of Python, in which we can select a portion of elements from the numpy array using the subscript operator. Like this,
arr[start : end]
It will select the elements from the array, from index position start
till index position end
. If we don’t provide the start index position, then it will start picking the elements from the starting of the array. We can also use the negative indexing to select the elements from end.
To remove last N elements of array. We can use the -N
index, which denotes the index position of Nth element from the end of the array. For example, to remove last 3 elements from array, we can select elements from index 0 till -3. like this,
Frequently Asked:
# specify number of elements to remove n = 3 # Remove the last N elements from the array numbers = numbers[:-n]
It will remove last 3 elements from NumPy Array.
Let’s see the complete example,
import numpy as np # create sample numpy array numbers = np.array([34, 35, 78, 61, 56, 35, 90, 35]) print('Before removing elements:') print(numbers) # specify number of elements to remove n = 3 # Remove the last N elements from the array numbers = numbers[:-n] print('After removing elements:') print(numbers)
Output
Before removing elements: [34 35 78 61 56 35 90 35] After removing elements: [34 35 78 61 56]
Summary
We learned how to remove last n elements from a NumPy Array in Python.
Latest Video Tutorials