Skip to Content

Extract the First N Elements of Numpy Array

The Numpy library in Python comes with a number of useful methods and techniques to work with and manipulate data in arrays. In this tutorial, we will look at how to get the first N elements of a one-dimensional Numpy Array with the help of some examples.

How to get the first n elements of a Numpy array?

get the first n elements of a numpy array

To get the first n elements of a Numpy array, slice the array from index 0 to index n. The following is the syntax –

# first n elements of numpy array
ar[:n]

This will give us the elements in the array starting from the element at index 0 up to (but not including) the element at index n.

Steps to get the first n elements in an array

Let’s now look at a step-by-step example of using the above syntax on a Numpy array.

Step 1 – Create a Numpy array

First, we will create a Numpy array that we’ll operate on.

import numpy as np

# create numpy array
ar = np.array([1, 5, 6, 3, 2, 4, 7])
# display the array 
print(ar)

Output:

[1 5 6 3 2 4 7]

Here, we used the numpy.array() function to create a one-dimensional Numpy array containing some numbers. There are seven elements in the array.

Step 2 – Slice the array to get the first n elements

To get the first n elements of the above array, slice the array starting from the first element (0th index) up to (but not including) the element with the index n.

For example, let’s get the first 3 elements from the array that we created in step 1.

# get first 3 elements of the array
print(ar[0:3])

Output:

[1 5 6]

We get the first 3 elements of the array.

In the above code, you don’t need to explicitly specify 0 (since you’re slicing starting from the very first element of the array).

# get first 3 elements of the array
print(ar[:3])

Output:

[1 5 6]

We get the same result as above.

For more on slicing Numpy arrays, refer to its documentation.

Summary

In this tutorial, we looked at how to get the first n elements of a one-dimensional Numpy array using slicing. The following is a short summary of the steps mentioned in the tutorial.

  1. Create a Numpy array (skip this step if you already have an array to operate on).
  2. Slice the array from index 0 to index n to get the first n elements of the array.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.