Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append 2D array to 3D array, extending third dimension

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.

like image 214
trminh89 Avatar asked Dec 18 '15 14:12

trminh89


People also ask

Can an array have up to 3 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.

How do you append a 3 dimensional array in Python?

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.

Can array have more than 2 dimensions?

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.


1 Answers

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) 
like image 181
Alex Riley Avatar answered Sep 22 '22 17:09

Alex Riley