'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
Solution 1:[1]
updating solution to fit description
a = np.empty(100)
filler = np.arange(1,4,0.25)
index = np.arange(a.size)
np.put(a,index,filler)
Solution 2:[2]
Such a simple feat can be achieved in plain python, too
>>> size = 100
>>> b = [v/4 for v in range(4,16)]
>>> a = (b * (size // len(b) + 1))[:size]
>>> a
[1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25, 3.5, 3.75,
1.0, 1.25, 1.5, 1.75]
with these exact conditions it's about 3 times faster than numpy.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
