Home »
Python »
Python Programs
Python NumPy - Stack an Array Vertically and Tile Array n Times
By IncludeHelp Last updated : September 11, 2024
Problem Statement
Suppose that we are going with a NumPy array and we need to create a new array where the input array is tiled n times along the first axis and stacked vertically.
Stacking an Array Vertically and Tile Array n Times
To stack an array vertically and tile the array n times, first use the numpy.tile() function to tile the input array n times along the first axis, and stores the result in a variable. We will then use numpy.row_stack() to stack the tiled array vertically, and stores the result in another variable.
Python Code to Stack an Array Vertically and Tile Array n Times
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 value for n
n = 3
# Tile the input array n times along the first axis
tiled_arr = np.tile(arr, (n, 1))
# Stack the tiled array vertically
res = np.row_stack(tiled_arr)
# Display result
print("Result:\n",res,"\n")
Output
The output of the above program is:
Original array [1 2 3 4]
Result:
[[1 2 3 4]
[1 2 3 4]
[1 2 3 4]]
Python NumPy Programs »