A.M.
A.M.

Reputation: 1797

Copy a 2D array to make it 3D

Suppose that I have a 2D Numpy array, A.

I want to build a 3D array B with depth of 100 such that for every i such that 0 <= i < 100, we have B[:,:,i] == A.

Is there any efficient way to do this in Python/Numpy?

Upvotes: 3

Views: 216

Answers (1)

CT Zhu
CT Zhu

Reputation: 54340

Just make a zero 3D array of your desired shape, and add your A to it

In [13]:

A = np.array([[1,2,3],[4,5,6]])
In [14]:

C = np.zeros(shape=(A.shape[0], A.shape[1], 100), dtype=A.dtype))
In [15]:

B = C+A[...,...,np.newaxis]
In [16]:

B[:,:,1]
Out[16]:
array([[ 1,  2,  3],
       [ 4,  5,  6]])
In [17]:

B[:,:,2]
Out[17]:
array([[ 1,  2,  3],
       [ 4,  5,  6]])

It is not going to be 100 copies of A, (and I doubt if you can ever make it so), because B has to be a contiguous memory block by itself.

Upvotes: 1

Related Questions