Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace negative values in an numpy array

Tags:

python

numpy

Is there a simple way of replacing all negative values in an array with 0?

I'm having a complete block on how to do it using a NumPy array.

E.g.

a = array([1, 2, 3, -4, 5]) 

I need to return

[1, 2, 3, 0, 5] 

a < 0 gives:

[False, False, False, True, False] 

This is where I'm stuck - how to use this array to modify the original array.

like image 814
bph Avatar asked Apr 26 '12 14:04

bph


People also ask

How do you get rid of a negative in Python?

In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive.

How do you replace an array value in Python?

char. replace() method. In Python, this function is used to return a copy of the numpy array of string and this method is available in the NumPy package module. In Python this method will check the condition if the argument count is given, then only the first count occurrences is replaced.


1 Answers

You are halfway there. Try:

In [4]: a[a < 0] = 0  In [5]: a Out[5]: array([1, 2, 3, 0, 5]) 
like image 105
NPE Avatar answered Sep 21 '22 19:09

NPE