0

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)

2
  • 1
    This question is hard to follow. Can you consider simplifying the base case? For example, I presume the method you wish to use would work equally well for an array of length 9 and 3d array of shape 9*8*1? It's not clear from your example if you re talking specifically about this arr. Can you also provide for the simple case, what you would expect the output to look like. Thanks! Commented Jul 17, 2019 at 12:20
  • @ColBates-collynomial I have add some stuffs in my questions related to what i tried. I am expecting pythonic approach to get the results.. Commented Jul 17, 2019 at 12:38

2 Answers 2

1

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 !?

Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.