I have an nd array, for example this:
x = np.array([[1,2,3],[4,5,6]])
I would like to double the size of the last dimension, and insert zeroes between the elements to fill the space. The result should look like this:
[[1,0,2,0,3,0],[4,0,5,0,6,0]]
I tried to solve it using expand_dims
and pad
. But the pad
function inserts zeroes not just after each value in the last dimension. The shape of it's result is (3, 4, 2)
, but it should be (2,3,2)
y = np.expand_dims(x,-1)
z = np.pad(y, (0,1), 'constant', constant_values=0)
res = np.reshape(z,[-1,2*3]
Result of my code:
array([[1, 0, 2, 0, 3, 0],
[0, 0, 4, 0, 5, 0],
[6, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
How is it possible with pad
to insert zeroes in the last dimension after each element? Or is there any better way to solve the problem?
You can use numpy. pad , which pads default 0 to both ends of the array while in constant mode, specify the pad_width = (0, N) will pad N zeros to the right and nothing to the left: N = 4 np.
The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy. int8.
Use the numpy. append() Function to Add a Row to a Matrix in NumPy. The append() function from the numpy module can add elements to the end of the array. By specifying the axis as 0, we can use this function to add rows to a matrix.
Simply initialize output array and assign with slicing
-
m,n = x.shape
out = np.zeros((m,2*n),dtype=x.dtype)
out[:,::2] = x
Alternatively with stacking -
np.dstack((x,np.zeros_like(x))).reshape(x.shape[0],-1)
You can simply do it with the insert function:
np.insert(x, [1,2,3], 0, axis=1)
array([[1, 0, 2, 0, 3, 0],
[4, 0, 5, 0, 6, 0]])
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