Reputation: 49
I have an existing python array instantiated with zeros. How do I iterate through and change the values?
I can't iterate through and change elements of a Python array?
num_list = [1,2,3,3,4,5,]
mu = np.mean(num_list)
sigma = np.std(num_list)
std_array = np.zeros(len(num_list))
for i in std_array:
temp_num = ((i-mu)/sigma)
std_array[i]=temp_num
This the error:
only integers, slices (:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices
Upvotes: 0
Views: 72
Reputation: 3429
In your code you are iterating over the elements of the numpy.array
std_array
, but then using these elements as indices to dereference std_array
. An easy solution would be the following.
num_arr = np.array(num_list)
for i,element in enumerate(num_arr):
temp_num = (element-mu)/sigma
std_array[i]=temp_num
where I am assuming you wanted to use the value of the num_list
in the first line of the loop when computing temp_num
. Notice that I created a new numpy.array
called num_arr
though. This is because rather than looping, we can use alternative solution that takes advantage of broadcasting:
std_array = (num_arr-mu)/sigma
This is equivalent to the loop, but faster to execute and simpler.
Upvotes: 4
Reputation: 29742
You i
is an element from std_array
, which is float
. Numpy
is therefore complaining that you are trying slicing with float
where:
only integers, slices (
:
), ellipsis (...
), numpy.newaxis (None
) and integer or boolean arrays are valid indices
If you don't have to use for
, then numpy
can broadcast the calculations for you:
(std_array - mu)/sigma
# array([-2.32379001, -2.32379001, -2.32379001, -2.32379001, -2.32379001,
-2.32379001])
Upvotes: 0