0

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

2
  • Can you print this statement? I would like to see what it returns. np.zeros(len(num_list)) Commented Feb 19, 2019 at 0:35
  • @FranJ [0. 0. 0. 0. 0. 0.] Commented Feb 19, 2019 at 0:39

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.