I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this?
simple way , with some math
at first you know the number of array elements , lets say 100 and then devide 100 on 3 steps like:
25 * 2 * 2 = 100
or: 4 * 5 * 5 = 100
import numpy as np
D = np.arange(100)
# change to 3d by division of 100 for 3 steps 100 = 25 * 2 * 2
D3 = D.reshape(2,2,25) # 25*2*2 = 100
another way:
another_3D = D.reshape(4,5,5)
print(another_3D.ndim)
to 4D:
D4 = D.reshape(2,2,5,5)
print(D4.ndim)
If you just want to add a 3rd axis (x,y) to (x,y,1), Numpy allows you to easily do this using the dstack
command.
import numpy as np
a = np.eye(3) # your matrix here
b = np.dstack(a).T
You need to transpose (.T
) it to get it into the (x,y,1) format you want.