Hasani
Hasani

Reputation: 3869

Changing the value of some indexes of an array in python

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

Upvotes: 1

Views: 15576

Answers (6)

Mohammad Madkhanah
Mohammad Madkhanah

Reputation: 1

You may want to replace the for statement with this:

for x in range(len(j))

Upvotes: 0

Jab
Jab

Reputation: 27485

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]]

Upvotes: 4

motleycodes
motleycodes

Reputation: 41

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

Upvotes: 1

Shadab Ahmed
Shadab Ahmed

Reputation: 576

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

Upvotes: 1

Youcef Benyettou
Youcef Benyettou

Reputation: 193

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

Upvotes: 1

sal
sal

Reputation: 3593

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

Upvotes: 1

Related Questions