How can I prepopulate while initializing numpy array with fixed values?
I tried generating list
and using that as a fill
.
>>> c = np.empty(5)
>>> c
array([0.0e 000, 9.9e-324, 1.5e-323, 2.0e-323, 2.5e-323])
>>> np.array(list(range(0,10,1)))
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>
>>> c.fill(np.array(list(range(0,10,1))))
TypeError: only length-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.
>>> c.fill([np.array(list(range(0,10,1)))])
TypeError: float() argument must be a string or a real number, not 'list'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: setting an array element with a sequence.
Expected -
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
CodePudding user response:
fill
fills each entry with the same value. c = np.empty(size); c.fill(5)
allocates an array of size size
without initialising any values and then fills it with all 5
.
In addition to the answer by AJ Biffl, you can also assign values to an ndarray via broadcasting:
c = np.empty(5)
c[:] = range(5)
This only works if the shapes match, but it does let you do stuff like this:
a = np.empty((5, 3))
a[:] = [range(i, i 3) for i in range(5)]
>>> array([[0., 1., 2.],
[1., 2., 3.],
[2., 3., 4.],
[3., 4., 5.],
[4., 5., 6.]])
CodePudding user response:
np.tile(np.arange(10), (5,1))
np.arange(10)
creates an array of integers from 0 to 9
np.tile(..., (5,1))
tiles copies of the array - 5 copies going "down" (new rows) and 1 "across" (1 copy within each row)