Your iterator is not creating indices, but the actual elements in the array

Use with AIfor label in labels_class

In the above label is not an index, but the actual element you are trying to change

You can do something like this:

Use with AIfor i, label in enumerate(labels_class):
     labels_class[i] = 1 if (label == classifier) else 0
Answer from sedavidw on Stack Overflow
Discussions

python - How to iterate and modify over a numpy array? - Stack Overflow
I have an array that I would like to iterate over and modify the array itself, through inserts or deletions. for idx, ele in enumerate(np.nditer(array)): if idx + 1 More on stackoverflow.com
🌐 stackoverflow.com
python - Change values of numpy array iteratively - Stack Overflow
I have problems with a numpy array: a1 is a numpy array ( A 3-dimensional vector) while update is a list of three values. I want that the first dimension of a1 is the first value, the second dimens... More on stackoverflow.com
🌐 stackoverflow.com
November 2, 2018
python - How do I iterate through a numpy array and perform calculations? - Stack Overflow
I want to iterate through a numpy array and perform division, multiplication, and addition. I keep coming up with several errors. The latest is IndexError: invalid index to scalar variable. imp... More on stackoverflow.com
🌐 stackoverflow.com
Iterate and change values of python numpy matrix columns - Stack Overflow
I have a numpy matrix containing numbers. 1,0,1,1 0,1,1,1 0,0,1,0 1,1,1,1 I would like to perform a Z-Score Normalization over each column; z_Score[y] = (y-mean(column))/sqrt(var) y being each el... More on stackoverflow.com
🌐 stackoverflow.com
October 10, 2019
🌐
W3Schools
w3schools.com › python › numpy › numpy_array_iterating.asp
NumPy Array Iterating
Iterate on the elements of the ... Try it Yourself » · To return the actual values, the scalars, we have to iterate the arrays in each dimension....
🌐
NumPy
numpy.org › doc › stable › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.5 Manual
The remainder of this document presents the nditer object and covers more advanced usage. The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion. This page introduces some basic ways to use the object for computations on arrays in Python, then concludes with how one can accelerate the inner loop in Cython.
🌐
Pluralsight
pluralsight.com › blog › tech guides & tutorials
Iterating Numpy Arrays | Pluralsight
November 12, 2018 - Iterating a one-dimensional array is simple with the use of For loop. A = np.arange(12) for cell in A: print(cell, end=' ') ... The end specifies the character that needs to be printed after printing the value.
Top answer
1 of 2
2

You cannot mutate the length of a numpy array, because numpy assigns the required memory for an array upon its creation.

With

array = np.delete(array, idx+1)

You are creating a new array on the right hand side of the = and reassign the name array.

The return value for enumerate(np.nditer(array)) has already been created at that point and won't recognize that the name array has been rebound.

In principle, you can iterate over a sequence and mutate its length at the same time (generally not a good idea). The object just needs to have methods that let you mutate its length (like lists, for example).

Consider:

>>> l = [5, 4, 3, 2, 1]                                                         
>>> for idx, ele in enumerate(l): 
...:     if ele == 3: 
...:         l.pop(idx) # mutates l 
...:     print(ele) 
...:                                                                            
5
4
3
1
>>> l                                                                           
[5, 4, 2, 1]

Notice that

  1. l is mutated.
  2. The loop does not print 2 because popping an element reduces the indexes of all the remaining elements by one. Now l[2] == 2, but index 2 has already been visited by the iterator, so the next print-call prints l[3] which is 1.

This proves that mutations to l have effect on subsequent iterations.

2 of 2
0

Instead of looping over an array, you can use where method to find indices of elements meeting some condition.

Then to delete the selected element (or elements), you can use delete method, passing the source array, and a list of indices. Then save the result, e.g. under the same variable.

To add an element, you can use append or insert methods (for details see Numpy documentation).

I have also found a SO post concerning how to loop and delete over an array. See Deleting elements from numpy array with iteration

Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › numpy › numpy_iterating_over_array.htm
NumPy - Iterating Over Array
Iterating with indices involves using nested loops to traverse through each dimension of the array and access elements using their specific indices. This approach allows for more precise control over element access and manipulation compared ...
🌐
EDUCBA
educba.com › home › software development › software development tutorials › numpy tutorial › numpy for loop
NumPy for loop | Learn the Examples of NumPy for loop
April 3, 2023 - In this example will discuss how to iterate through a two-dimensional array. ... In this example, we have created an array and iterated it twice using python for a loop. This method allows us to perform different operations while iterating multiple times, and this method is very efficient and requires less coding. In this example, we have created a zero-dimensional array and converted it into a two-dimensional array. ... import numpy as np arr = np.array([[[8, 16, 44], [0, 4, 7]], [[22, 40, 16], [7, 14, 21]]]) for x in arr: for y in x: for z in y: print(z)
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Top answer
1 of 3
1

There are several issues with your example (some of which may be actual problems, others just typos or over simplifiactions):

import numpy as np     # if you want to use for-loops don't use numpy
rays = np.array(...    # closing parentheses instead of brackets
                       # unequal dimensions row of 5 and row of 6
                            
for i in range(rays):  # rays is not a number, did you mean len(rays[0])?
    for w in range(i): # w is not used anywhere
        estimate = rays[0][i]/(rays[0][i]+rays[1][i]) 
                       # estimate is overwritten at each iteration

The whole point of using numpy is to avoid "manually" iterating through array elements using for-loops. You should think of your result as an operation between matrices (or vectors):

For example (without for-loops):

import numpy as np
rays = np.array([[7.651e-03, 7.284e-03, 5.134e-03, 7.442e-03, 3.035e-03],
                 [2.373e-03, 6.877e-03, 4.809e-03, 2.870e-04, 3.175e-04]])

estimates = rays[0]/(rays[0]+rays[1])
print(estimates)
[0.76326816 0.51437045 0.51634316 0.96286712 0.90529456]

Note that I removed the last value from the second row because numpy requires fixed dimensions (i.e. it cannot have one row with 5 elements and another with 6)

Your nested loop for w in range(i), though you're not doing anything with w, suggests that you may be looking for the ratio between cumulative sums. If that is the case, use the cumsum function from numpy:

estimates = np.cumsum(rays[0])/np.cumsum(rays[0]+rays[1])
print(estimates)
[0.76326816 0.61753153 0.58805087 0.65726163 0.67565445]
2 of 3
0
rays = [
[7.651e-03, 7.284e-03, 5.134e-03, 7.442e-03, 3.035e-03],
[2.373e-03, 6.877e-03, 4.809e-03, 2.870e-04, 3.175e-04],
]

for i in range(min(len(rays[0]), len(rays[1]))):
    estimate = rays[0][i] / (rays[0][i] + rays[1][i])
    print(estimate)
🌐
Finxter
blog.finxter.com › home › learn python blog › how to iterate over a numpy array
How to Iterate over a NumPy Array - Be on the Right Side of Change
August 16, 2022 - This fills in any missing values for lists of unequal lengths with the stated value. The loop iterates until the end of the arrays are reached, outputting to the terminal for each iteration. This method uses a while loop combined with np.size to iterate through a NumPy array.
🌐
Scaler
scaler.com › home › topics › numpy › numpy iterating over array
NumPy Iterating Over Array - Scaler Topics - Scaler Topics
September 9, 2022 - Nditer is a multidimensional iterator object in the NumPy package that can traverse an array efficiently. We can modify the array value by using an optional parameter of the nditer object called Op flags (operand flags). Broadcasting array iteration is used for iterating an array in Python ...
🌐
Reddit
reddit.com › r/learnpython › best practice for replacing a value in a numpy array
r/learnpython on Reddit: Best practice for replacing a value in a numpy array
November 20, 2020 -

After having used Matlab pretty extensively for the past few years, I'm used to a few practices that aren't considered great in Python. For instance, when I wanted to iterate through an array and evaluate each individual value in Matlab, I would iterate over the indices of the array rather than the values of the array as one would do in Python. In other words, I would do something like for i in range(len(array)): instead of for x in array:.

While I see the benefit in iterating through the values, I don't know how to easily evaluate and modify values in this manner. If anyone has any insight as to how to go about this, I'd certainly appreciate it.

Just to provide a little more information, this is the most obvious way for me to change a particular value based on some criteria:

import numpy as np

A = np.arange(5)

for i in range(len(A)):
    if A[i] == 3:
        A[i] = 14

I'm looking for a better, more pythonic way to do this. Thanks!

🌐
Stack Overflow
stackoverflow.com › questions › 39299187 › iterate-and-assign-value-python-numpy
arrays - Iterate and assign value - Python - Numpy - Stack Overflow
September 3, 2016 - a1 = numpy.array(range(10)) a2 = numpy.array(range(15,25)) print a2[a1==5] print a2[a1 >= 8] print a2[a1 < 5]
🌐
Medium
medium.com › @whyamit404 › understanding-numpy-array-iteration-e9813c6946d0
Understanding NumPy Array Iteration | by whyamit404 | Medium
February 26, 2025 - They handle large datasets faster and more efficiently compared to Python lists. When you’re just starting out, the easiest way to iterate over a NumPy array is with a good old-fashioned for loop. ... We’ve created a simple NumPy array: ...
🌐
NumPy
numpy.org › doc › 2.1 › reference › arrays.nditer.html
Iterating over arrays — NumPy v2.1 Manual
The remainder of this document presents the nditer object and covers more advanced usage. The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion. This page introduces some basic ways to use the object for computations on arrays in Python, then concludes with how one can accelerate the inner loop in Cython.
🌐
Saturn Cloud
saturncloud.io › blog › changing-specific-values-in-a-numpy-array-a-comprehensive-guide
Changing Specific Values in a Numpy Array: A Guide | Saturn Cloud Blog
May 1, 2026 - In the above code, (arr > 2) & (arr &lt; 4) creates a Boolean array of the same shape as arr, where each element is True if the corresponding element in arr is between 2 and 4, and False otherwise. The = operator then changes all True elements to 0. ... Solution: Use parentheses to ensure correct order of operations. # Correct Boolean indexing syntax arr[(arr > 2) & (arr < 4)] = 0 · # Attempting to use NumPy operations on a regular Python list python_list = [1, 2, 3, 4, 5] python_list[(python_list > 2) & (python_list < 4)] = 0