Search code examples
pythonnumpyindexingnumpy-ndarray

Error while I want to get index of specific values from my numpy array in python


I have an numpy array which I want to to find index of values from it. Here is the code:

for i, memb_e in enumerate(memb_e):
    if memb_e == 1:
        x1 = e[i]
        y1 = 1
print(x1)

for i, memb_e in enumerate(memb_e):
    if memb_e == 0 :
        x0 = e[i]
        y0 = 0
        if i+1 < len(memb_e) and memb_e[i+1] != 0 :
            break

The first loop works perfectly but I got an error for second loop which is 'numpy.float64' object is not iterable.

Also fyi the len(e) = len(memb_e).

Anyone know how to solve this problem??


Solution

  • There is a small problem which depends on the context and may raise to ambiguous behaviors: the iteration variable is the same as the iteration object memb_e.

    The 1st attempt works because you don't try to access to the iteration object.

    Instead, in the 2nd loop you try get the length of the list len(memb_e) and read a value memb_e[i+1] but memb_e is an object of the iterable, a numpy.float64 object.

    So, use a different identifier as iteration variable for i, m_e in enumerate(memb_e):

    for i, m_e in enumerate(memb_e):
        if m_e == 0:  # <- comparing the iteration variable
            x0 = e[i]
            y0 = 0
            if i+1 < len(memb_e) and memb_e[i+1] != 0: # <- iterable object
                break