17.6 C
London
Tuesday, July 22, 2025
HomePandas in PythonGeneral Functions in PythonHow to Add Row to Matrix in NumPy (With Examples)

How to Add Row to Matrix in NumPy (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 add a row to a matrix in NumPy:

#add new_row to current_matrix
current_matrix = np.vstack([current_matrix, new_row])

You can also use the following syntax to only add rows to a matrix that meet a certain condition:

#only add rows where first element is less than 10
current_matrix = np.vstack((current_matrix, new_rows[new_rows[:,0] 10]))

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

Example 1: Add Row to Matrix in NumPy

The following code shows how to add a new row to a matrix in NumPy:

import numpy as np

#define matrix
current_matrix = np.array([[1 ,2 ,3], [4, 5, 6], [7, 8, 9]])

#define row to add
new_row = np.array([10, 11, 12])

#add new row to matrix
current_matrix = np.vstack([current_matrix, new_row])

#view updated matrix
current_matrix

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

Notice that the last row has been successfully added to the matrix.

Example 2: Add Rows to Matrix Based on Condition

The following code shows how to add several new rows to an existing matrix based on a specific condition:

import numpy as np

#define matrix
current_matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

#define potential new rows to add
new_rows = np.array([[6, 8, 10], [8, 10, 12], [10, 12, 14]])

#only add rows where first element in row is less than 10
current_matrix = np.vstack((current_matrix, new_rows[new_rows[:,0] 10]))

#view updated matrix
current_matrix

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

Only the rows where the first element in the row was less than 10 were added.

Note: You can find the complete online documentation for the vstack() function here.

Additional Resources

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

How to Find Index of Value in NumPy Array
How to Add Numpy Array to Pandas DataFrame
How to Convert NumPy Array to Pandas DataFrame

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