2.4 C
London
Friday, December 20, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Get Specific Row from NumPy Array (With Examples)

How to Get Specific Row from NumPy Array (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to get a specific row from a NumPy array:

#get row in index position 2 from NumPy array
my_array[2, :]

The following examples shows how to use this syntax in practice.

Example 1: Get One Row from NumPy Array

The following code shows how to get one specific row from a NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

#view NumPy array
print(data)

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

#get row in index position 2
data[2, :]

array([ 9, 10, 11, 12])

Notice that only the row in index position 2 of the NumPy array is returned.

Example 2: Get Multiple Rows from NumPy Array

The following code shows how to get multiple rows from a NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

#view NumPy array
data

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

#get rows in index positions 0 and 2 from NumPy array
data[[0,2], :]

array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

Example 3: Get Rows in Range from NumPy Array

The following code shows how to get rows in a range from a NumPy array:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

#view NumPy array
data

array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])

#get rows in index positions 0 through 1
data[0:2, :]

array([[1, 2, 3, 4],
       [5, 6, 7, 8]])

Note that the last value in the range (in this case, 2) is not included in the range of rows that is returned.

Additional Resources

The following tutorials explain how to perform other common operations in NumPy:

How to Get Specific Column from NumPy Array
How to Map a Function Over a NumPy Array
How to Add a Column to a NumPy Array

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories