Ask Your Question
1

How can arrays with different numbers of rows be stacked on top of each other?

asked 2022-08-10 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-21 05:00:00 +0000

lakamha gravatar image

Arrays with different numbers of rows can be stacked on top of each other using the numpy.vstack() function. This function takes a tuple of arrays as input and stacks them vertically. The arrays being stacked must have the same number of columns. If the arrays have different numbers of columns, they can be horizontally stacked using the numpy.hstack() function.

Here is an example of stacking arrays with different numbers of rows using numpy.vstack():

import numpy as np

arr1 = np.array([[1, 2, 3],
                [4, 5, 6]])

arr2 = np.array([[7, 8, 9]])

arr3 = np.array([[10, 11, 12],
                [13, 14, 15],
                [16, 17, 18]])

result = np.vstack((arr1, arr2, arr3))

print(result)

The output of this code will be:

[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]
 [13 14 15]
 [16 17 18]]

In this example, arr1 has two rows, arr2 has one row, and arr3 has three rows. By using np.vstack(), these arrays are stacked vertically to create a single array with six rows.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-10 11:00:00 +0000

Seen: 20 times

Last updated: May 21 '21