Home > Blockchain >  How to create an array with values along specified axis?
How to create an array with values along specified axis?

Time:06-16

numpy.full() is a great function which allows us to generate an array of specific shape and values. For example,

>>>np.full((2,2),[1,2])
array([[1,2],
       [1,2]])

However, it does not have a built-in option to apply values along a specific axis. So, the following code would not work:

>>>np.full((2,2),[1,2],axis=0)
array([[1,1],
       [2,2]])

Hence, I am wondering how I can create a 10x48x271x397 multidimensional array with values [1,2,3,4,5,6,7,8,9,10] inserted along axis=0? In other words, an array with [1,2,3,4,5,6,7,8,9,10] repeated along the first dimensional axis. Is there a way to do this using numpy.full() or an alternative method?

#Does not work, no axis argument in np.full()
values=[1,2,3,4,5,6,7,8,9,10]
np.full((10, 48, 271, 397), values, axis=0)

CodePudding user response:

You can use np.broadcast_to as follows:

import numpy as np

shape = (10, 48, 271, 397)

root = np.arange(shape[0])
arr = np.broadcast_to(root, shape[::-1]).T

print(f"{arr.shape = }")  # (10, 48, 271, 397)

Check that it does what we want:

for i in range(shape[0]):
    sub = arr[i]
    assert np.all(sub == i)
  • Related