Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Negatives in an Array, Python

Tags:

python

arrays

How do I write a function that replaces all negative numbers in an array with a 0.
Here is what I have so far:

def negativesToZero(A):
    for x in A:
        if x < 0:
            A.append(0)
    else:
        pass
    print A 
A = ([[1,-2],\
      [-2,1]])
negativesToZero(A)
like image 211
madman Avatar asked Dec 30 '25 23:12

madman


2 Answers

Since A is a list of lists:

>>> A = [[1, -2], [-2, 1]]

>>> for lst in A:
...     for i, val in enumerate(lst):
...         lst[i] = max(val, 0)

>>> print A
[[1, 0], [0, 1]]

Alternatively using list comprehensions:

>>> A = [[max(val, 0) for val in lst] for lst in A]
like image 188
Ozgur Vatansever Avatar answered Jan 02 '26 14:01

Ozgur Vatansever


If you want an array operation, you should create a proper array to start with.

A=array([[1,-2],[-2,1]])

Array comprehensions like yours can be one-lined using boolean operations on indices:

A[A<0]=0

Of course you can frame it as a function:

def positive_attitude(x):
    x[x<0]=0
    return x
print positive_attitude(A)
like image 39
yevgeniy Avatar answered Jan 02 '26 13:01

yevgeniy