1

I am trying this simple code to search in an array and replace the elements that are greater than 1 to 1:

import numpy as np

j = np.array([[1],[3],[1],[0],[9]])

for x in j:
    if abs(x) > 1 :
        j[x] = 1

But I get such errors:

IndexError: index 9 is out of bounds for axis 0 with size 5

2
  • @CarcigenicateL I edited my question Commented Mar 2, 2019 at 21:10
  • Try using enumerate, and use the enumerated index to change the element. Commented Mar 2, 2019 at 21:16

6 Answers 6

4

If all you're doing is making all values if absolute(j[i]) is greater than 1 to 1 then numpy has this capability built in and it's so simple it can be done in one line and more efficient than any python loop:

j[np.absolute(j) > 1] = 1

To show you how this would work:

#made 3 a negitive value to prove absolute works.
j = np.array([[1],[-3],[1],[0],[9]])

j[np.absolute(j) > 1] = 1

j is now:

[[1]
 [1]
 [1]
 [0]
 [1]]
Sign up to request clarification or add additional context in comments.

Comments

1

When you traverse an array in a for loop you are actually accessing the elements, not the index. After all, you are comparing x against 1. You can retrieve the index in many ways, one of the common ones is to use enumerate, like so:

import numpy as np

j = np.array([[1],[3],[1],[0],[9]])

for i,x in enumerate(j):    # i is the index, x is the value
    if abs(x) > 1 :
        j[i] = 1

Comments

1

Try to change the for loop using enumerate to :

import numpy as np

j = np.array([[1],[3],[1],[0],[9]])

for i,x in enumerate(j):
    if abs(x) > 1 :
        j[i] = 1

Comments

1

as you see in your error output

IndexError: index 9 is out of bounds for axis 0 with size 5

you are trying to update a value at index 9 but your array is of size 5. which clearly means you are not using the index of array but actually the value at index.

enumerate your array and run a loop with both index & value

for i,x in  enumerate(j):
    if abs(x) > 1 :
        j[i] = 1

Comments

1

Are you trying to make a two dimensional array? You have your elements in brackets within brackets "[[1],[3],[1],[0],[9]]" .... also, you're iterating over values, not indices: x is an array value "[3]" not an index "1".

Change to:

import numpy as np

j = np.array([1,3,1,0,9])

# Keep track of index starting at 0
i = 0
for x in j:
    if abs(x) > 1 :
        # change value at index i
        j[i] = 1
    # increment index
    i += 1

Comments

0

You may want to replace the for statement with this:

for x in range(len(j))

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.