Reputation: 698
I have an numpy array of shape (271,) with binary elements.
For example :
arr = array([0., 0., 0., 1., 1., 1., 0., 0., 1., .........])
How to convert this into a 3d array of shape 271*80*1 to form new_3d_arr
?
such that my new_3d_arr[0]
is of shape 80 rows with 0's* 1 column
I hope there will be a simple approach to achieve this.
I tried below code & I can get the result what i required, but I hope there will be a simple approach to achieve this
new_3d_arr = []
for i in arr:
arr_2d = array([i]*80).reshape((-1,1))
new_3d_arr.append(arr_2d)
new_3d_arr = array(new_3d_arr)
Upvotes: 0
Views: 588
Reputation: 367
U can use numpy.newaxis
to add new axis and than use numpy.repeat
to repeat your array (of new size (271,1,1)) 80 times along axis 1. Here is the code:
import numpy as np
arr = np.random.randint(0, 2, size=271)
print(arr.shape) # out: (271,)
arr_3d = np.repeat(arr[:, np.newaxis, np.newaxis], 80, axis=1)
print(arr_3d.shape) # out: (271, 80, 1)
Hope this is what u were looking for !?
Upvotes: 1
Reputation: 45
I am not sure if I understand your question correctly. From what I understand from your numpy array with shape (271,) you want an 3d numpy array with shape (271,80,1) such that the rest of the entries are 0.
There might be more efficient solutions but here is what I came up with:
First create a new numpy array containing only zeros:
new_3d_arr = np.zeros((271,80,1))
Then for each of the 271 vectors of length 80, we change the first entry to the one with the binary entries.
for i in range(len(arr)):
new_3d_arr[i][0][0] = arr[i]
Upvotes: 0