This tutorial will discuss about unique ways to remove first 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 first 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 end index position, then it will keep picking the elements till the end of the array.
To remove first N elements of array. We can use the index N
as starting point, which denotes the index position of Nth element of array. We can use the default value for end index in slicing, so that it can pick elements till the end of array.
Frequently Asked:
For example, to remove first 3 elements from array, we can select elements from index 3 till the end of array. like this,
# specify number of elements to remove n = 3 # Remove the first N elements from the array numbers = numbers[n :]
It will remove first 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 first N elements from the array numbers = numbers[n :] print('After removing elements:') print(numbers)
Output
Latest Python - Video Tutorial
Before removing elements: [34 35 78 61 56 35 90 35] After removing elements: [61 56 35 90 35]
Summary
We learned how to remove first N elements from a NumPy Array in Python.
Latest Video Tutorials