hpnk85 hpnk85 - 6 months ago 8
Python Question

Python: How do I fill an array with a range of numbers?

So I have an array of 100 elements:

a = np.empty(100)


How do I fill it with a range of numbers? I want something like this:

b = a.fill(np.arange(1, 4, 0.25))


So I want it to keep filling
a
with that values of that range on and on until it reaches the size of it

Thanks

Answer

np.put places values from b into a at the target indices, ind. If v is shorter than ind, its values are repeated as necessary:

import numpy as np

a = np.empty(100)
b = np.arange(1, 4, 0.25)
ind = np.arange(len(a))
np.put(a, ind, b)
print(a)

yields

[ 1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75  2.    2.25  2.5   2.75  3.    3.25  3.5   3.75
  1.    1.25  1.5   1.75]
Comments