Home > Mobile >  Best way to expand_dim and repeat a numpy array
Best way to expand_dim and repeat a numpy array

Time:09-16

I have an array that is of shape (1,5).

arr = np.arange(5)
arr = np.expand_dims(arr, axis=0)

I want to make an array that is of shape (1,4,5) with each value divided by 4. Is there another way to do this besides from the below solution?

arr2 = np.expand_dims(arr, axis=1)
arr2 = np.repeat(arr2, 4, axis=1)
arr2 = arr2*0.25

CodePudding user response:

You can use np.broadcast_to

arr2 = np.broadcast_to(arr, shape=(1, 4, 5))
arr2 = arr2 * 0.25

or as suggested in the comments

arr2 = np.broadcast_to(arr * 0.25, shape=(1, 4, 5))
  • Related