Home »
Python »
Python Programs
Python NumPy - Add a new row of zeros to the bottom of an array
By IncludeHelp Last updated : September 11, 2024
Problem statement
Given a NumPy array, write a Python program to add a new row of zeroes at the bottom of this array.
Adding a new row of zeros to the bottom of an array
To add a new row of zeros to the bottom of the array, we will first create a new row of zeros with the same number of columns as the input array and then we will use numpy.row_stack() to stack this new row below the input array, resulting in a new array with an additional row of zeros at the bottom.
Python code to add a new row of zeros to the bottom of an array
Let us understand with the help of an example:
# Importing numpy
import numpy as np
# Creating an array
arr = np.array([[1, 2], [3, 4]])
# Display original array
print("Original array", arr,"\n")
# Defining a function
def fun(arr):
# Create a new row of zeros
zeros_row = np.zeros(arr.shape[1])
# Stack the new row below the input array
# using numpy.row_stack
new_arr = np.row_stack((arr, zeros_row))
return new_arr
# Display result
print("Result:\n",fun(arr),"\n")
Output
The output of the above program is:
Original array [[1 2]
[3 4]]
Result:
[[1. 2.]
[3. 4.]
[0. 0.]]
Python NumPy Programs »