Reputation: 1382
import numpy as np
S = np.array(l)
for i in range(1, l):
random_int = randint(0, 1)
np.append(S, random_int)
I create a numpy array of size l and and fill it with zeros and ones. Let's say I want to print the third element of the array. How do I do that?
If I type
print(S[2])
I get the following error:
IndexError: too many indices for array
Upvotes: 1
Views: 949
Reputation: 13218
First, S = np.array(l)
does not result in an array of length l, but with a length 1 array whose only entry is l.
So you can replace this line with S = np.zeros(l)
(creating an array of length l full of zeros.
Then, in your for loop, you must do:
for i in range l:
S[i] = randint(0, 1)
This is just to point out your mistakes. As @Fabio said, you can do this in one line.
Upvotes: 1
Reputation: 21562
I would simply do in this way to generate L random numbers between 0 and 1:
L = 10
S = np.random.random_integers(0,1,L)
print S
print S[2]
returns:
[1 0 0 1 0 0 1 1 0 1]
0
Upvotes: 2
Reputation: 11961
np.append(S, random_int)
appends random_int
to a copy of the array S
. You need to use S = np.append(S, random_int)
in your for
loop.
Example
import numpy as np
from random import randint
l = 5
S = np.array(l)
for i in range(1, l):
random_int = randint(0, 1)
S = np.append(S, random_int)
print(S)
print(S[2])
Output
[5 1 1 0 1]
1
Upvotes: 1