What is a more efficient way to change a value in a numpy array?

  • Context: Comp Sci 
  • Thread starter Thread starter ver_mathstats
  • Start date Start date
  • Tags Tags
    Array Value
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 2K views
ver_mathstats
Messages
258
Reaction score
21
Homework Statement
Write a Python code to create the function array_change(a, new_val) that has two arguments:
a that is a NumPy array whose entries are numbers, and
new_val which is a number. The function returns a new array after changing every occurrence of entries in
a, that are in absolute value strictly less than 1, to new_val.
Relevant Equations
Python
Code:
import numpy as np

def array_change(a,new_val):
    a=np.array([])
    for i in range(a):
        if abs(i)<1:
            a[i]=new_val

e=np.arange(-2, 2, 0.2).reshape(4,5)
print(array_change(e,0))

I am not sure where I am going wrong exactly but I keep getting an error message.
I came up with a code that gives me the results I am looking for but it is not a function.

Code:
e=np.arange(-2, 2, 0.2).reshape(4,5)
c=abs(e)<1
e[c]=0
print(e)

Any help is appreciated. Thank you.
 
Physics news on Phys.org
ver_mathstats said:
I am not sure where I am going wrong exactly but I keep getting an error message.
If your code produces an error message, it's always a good idea to tell anyone helping what that error message says. A typical Python error message will give the type of error (e.g., Syntax Error, or Name Error) and will show you what line the error occurs on.
 
  • Like
Likes   Reactions: FactChecker
Aside from the program requirements (one parameter of the function must be a Numpy array), I don't see any other real reason why an ordinary Python list type can't be used.
 
I see at least two things wrong:

(1) a is the input array, which comes from outside the function. You should not be re-defining a within the function.

(2) The statement "for i in range(a)" requires that a be an integer. But a is a numpy array, not an integer. So this will fail right away.

Try fixing these two things and thinking a bit more about what you are trying to do. Then come back and tell us how you are doing.
 
To elaborate on the points that @phyzguy made, instead of doing this:
Python:
def array_change(a,new_val):
    a=np.array([])
      for i in range(a):
try this:
Python:
def array_change(arr, new_val):  
    arr_size = len(arr)
    for i in range(arr_size):
Note that I changed the name of the array parameter. Single letter variable names are discouraged in most programming languages, except possibly for loop control variables such as i, j, k, and so on.