Home » How to Add Row to Matrix in NumPy (With Examples)

How to Add Row to Matrix in NumPy (With Examples)

by Tutor Aspire

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

You may also like