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
More Pythonic Way of Editing a NumPy Array
You're not looking for the most pythonic way, you're looking for the actual way to do it with numpy :) If you're looping over all your values in numpy, there's a good chance it can be done another way. Here is the code for your question import numpy as np # Create a 100x100 2d array X = np.random.randint(0,10, (100,100)) # [EDIT from ES-Alexander's comment] # [CORRECT ANSWER] # Replace all values of 0 by 9 # X[condition] = result_if_true X[X==0] = 9 [Alternative] # Replace all values of 0 by 9 # use np.where(condition, result_if_true, result_else) Y = np.where(X == 0, 9, X) I'll add that more often than not to change stuff: you get the group of stuff you need to change you apply that change to that group You don't loop over everything to check and change it individually. Loops are great, I mean, your thing could be done with arrays too: # your numpy array X = np.random.randint(0,10, (100,100)) # your pythony hacky solution Y = [[ xi if xi != 0 else 9 for xi in x] for x in X] TBH idk what's more pythonic, learning the proper way to do things with libraries or just hacking in python with set comprehensions (single line loops) More on reddit.com
🌐 r/learnpython
5
5
May 13, 2022
python - Numpy array: iterate through column and change value depending on the next value - Stack Overflow
0 Numpy array: iterate through column and change value based on the current value and the next value · 3 Numpy array - change the next element based on a change on previous · 1 Changing a numpy array in place based on values in a given column? 0 How to change the value of an entire array based on one value in Python... More on stackoverflow.com
🌐 stackoverflow.com
November 30, 2021
🌐
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.
🌐
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....
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
🌐
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.
🌐
Reddit
reddit.com › r/learnpython › more pythonic way of editing a numpy array
r/learnpython on Reddit: More Pythonic Way of Editing a NumPy Array
May 13, 2022 -

I am learning about working with NumPy arrays, and I've written the below code to allow me to replace each instance of 0 with a 9 in a 2 dimensional NumPy array. The code works, but it feels hacky to me - is there a more efficient or more pythonic way of accomplishing this?

x_count = -1
y_count = -1

for i in array:
    for j in i:
        if array[x_count][y_count] == 0:
            array[x_count][y_count] = 9
        y_count += 1
    y_count = -1
    x_count += 1
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)
🌐
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 ...
🌐
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
🌐
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 ...
🌐
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
🌐
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: ...
Top answer
1 of 1
3

This error means that you are trying to get data from the 656th row of the sediment_transport array which is only 655 rows long. This is probably happening at the outlet of the flow direction raster. At this spot, the flow direction raster is saying something like "water will flow south from this cell." When you try to index the cell in sediment_transport that is one cell south, it doesn't exist and is throwing the error.

To get around this, you could just add a try and except and fill elevation_change with some placeholder value like -1:

for [i, j], flow in np.ndenumerate(flow_direction_np):
    try:
        if flow == 32:
            elevation_change[i, j]  = sediment_transport_np[i - 1, j - 1]
        elif flow == 16:
            elevation_change[i, j] = sediment_transport_np[i, j - 1]
        elif flow == 8:
            elevation_change[i, j] = sediment_transport_np[i + 1, j - 1]
        elif flow == 4:
            elevation_change[i, j] = sediment_transport_np[i + 1, j]
        elif flow == 64:
            elevation_change[i, j] = sediment_transport_np[i - 1, j]
        elif flow == 128:
            elevation_change[i, j] = sediment_transport_np[i - 1, j + 1]
        elif flow == 1:
            elevation_change[i, j] = sediment_transport_np[i, j + 1]
        elif flow == 2:
            elevation_change[i, j] = sediment_transport_np[i + 1, j + 1]
    except IndexError:
        elevation_change[i, j] = -1 #Placeholder for flow direction outlet

I also want to point out that if you are trying to do a flow accumulation of the sediment_transport data, the Flow Accumulation geoprocessing tool in ArcGIS has a parameter for an optional weight raster. The result would have the accumulated values from the in_weight_raster instead of just a count of upstream cells.

🌐
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!