Python - Concatenate n copies of an array along second axis and m copies along first axis

By IncludeHelp Last updated : September 14, 2024

To concatenate n copies of an array along the second axis and m copies along the first axis in Python, we can define a function which will accept numpy array arr and two integers n and m as input. Here, we will first use numpy.tile() to tile the input array n times along the second axis and create a new tiled array.

We will then use numpy.tile() again to tile the tiled array m times along the first axis and create a new tiled and concatenated array. Finally, we will return the new array.

Python code to concatenate n copies of an array along the second axis and m copies along the first axis

Let us understand with the help of an example:

# Importing numpy
import numpy as np

# Creating a string array
arr = np.array([1, 2, 3, 4])

# Defining values for n and m
n, m = 2, 3

# Display original array
print("Original array", arr, "\n")

# Defining a function
def fun(arr, n, m):
    # Tile the input array along the second axis
    tiled_arr = np.tile(arr, (1, n))

    # Tile the tiled array along the first axis
    tiled_and_concatenated_arr = np.tile(tiled_arr, (m, 1))

    return tiled_and_concatenated_arr

# Display result
print("Result:\n", fun(arr, n, m), "\n")

Output

Original array [1 2 3 4] 

Result:
 [[1 2 3 4 1 2 3 4]
 [1 2 3 4 1 2 3 4]
 [1 2 3 4 1 2 3 4]] 

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.