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
๐ŸŒ
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.
Discussions

python - Iterate and modify array with NumPy - Stack Overflow
I have two vectors x and y with same length defined with NumPy. How can I iterate through x and modify values in y? I mean something like ingredients = empty(cakes.shape) for ingredient, cake in... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Iterate and replace values through a numpy array Python - Stack Overflow
I'm looking for creating a random dimension numpy array, iterate and replace values per 10 for example. I tried : # Import numpy library import numpy as np def Iter_Replace(x): print(x) fo... More on stackoverflow.com
๐ŸŒ stackoverflow.com
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 - 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
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ numpy โ€บ numpy_array_iterating.asp
NumPy Array Iterating
... import numpy as np arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) for x in np.nditer(arr): print(x) Try it Yourself ยป ยท We can use op_dtypes argument and pass it the expected datatype to change the datatype of elements while iterating.
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

๐ŸŒ
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...
Find elsewhere
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.3 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.3 Manual
There are two mechanisms which allow this to be done, temporary copies and buffering mode. With temporary copies, a copy of the entire array is made with the new data type, then iteration is done in the copy. Write access is permitted through a mode which updates the original array after all ...
๐ŸŒ
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 ...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ numpy โ€บ numpy iterating over array
NumPy Iterating Over Array - Scaler Topics - Scaler Topics
September 9, 2022 - Arrays are iterated using for and while loops. 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).
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.1 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.1 Manual
There are two mechanisms which allow this to be done, temporary copies and buffering mode. With temporary copies, a copy of the entire array is made with the new data type, then iteration is done in the copy. Write access is permitted through a mode which updates the original array after all ...
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)
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.2 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.2 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.
๐ŸŒ
NumPy
numpy.org โ€บ doc โ€บ 2.4 โ€บ reference โ€บ arrays.nditer.html
Iterating over arrays โ€” NumPy v2.4 Manual
There are two mechanisms which allow this to be done, temporary copies and buffering mode. With temporary copies, a copy of the entire array is made with the new data type, then iteration is done in the copy. Write access is permitted through a mode which updates the original array after all ...
๐ŸŒ
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 - The output is sent to the terminal. Then idx displays a Tuple containing the index value of the array and then the value of x for each iteration. This method uses a for loop and range()) to iterate through a 3D NumPy array.
๐ŸŒ
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!

๐ŸŒ
Medium
medium.com โ€บ @whyamit404 โ€บ understanding-numpy-array-iteration-e9813c6946d0
Understanding NumPy Array Iteration | by whyamit404 | Medium
February 26, 2025 - ndindex() gives only the index, and you can access the value separately if needed. 4. Is it necessary to use nditer() for small arrays? Not really. For small arrays, basic for loops work just fine. nditer() shines with larger datasets. 5. Can I skip elements while iterating over a NumPy array?
๐ŸŒ
SciPy
docs.scipy.org โ€บ doc โ€บ numpy-1.12.0 โ€บ reference โ€บ arrays.nditer.html
Iterating Over Arrays โ€” NumPy v1.12 Manual
January 16, 2017 - For example, you may want to visit the elements of an array in memory order, but use a C-order, Fortran-order, or multidimensional index to look up values in a different array. The Python iterator protocol doesnโ€™t have a natural way to query these additional values from the iterator, so we introduce an alternate syntax for iterating with an nditer. This syntax explicitly works with the iterator object itself, so its properties are readily accessible during iteration. With this looping construct, the current value is accessible by indexing into the iterator, and the index being tracked is the property index or multi_index depending on what was requested.