I have an array A
that has shape (480, 640, 3)
, and an array B
with shape (480, 640)
.
How can I append these two as one array with shape (480, 640, 4)
?
I tried np.append(A,B)
but it doesn't keep the dimension, while the axis
option causes the ValueError: all the input arrays must have same number of dimensions
.
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns. Similarly, you can declare a three-dimensional (3d) array.
Python numpy append 3d array In Python, the append() function will add items at the end of an array and this function will merge two numpy arrays and it always returns a new array.
The easiest way of understanding a multidimensional array is to acknowledge every array as a one dimensional array. i.e A 3 dimensional array is one dimensional array and every element in the one dimensional is a 2 dimensional array.
Use dstack
:
>>> np.dstack((A, B)).shape (480, 640, 4)
This handles the cases where the arrays have different numbers of dimensions and stacks the arrays along the third axis.
Otherwise, to use append
or concatenate
, you'll have to make B
three dimensional yourself and specify the axis you want to join them on:
>>> np.append(A, np.atleast_3d(B), axis=2).shape (480, 640, 4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With