Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do conditional array arithmetic on a numpy array?

Tags:

python

numpy

I'm trying to get a better grip on numpy arrays, so I have a sample question to ask about them:

Say I have a numpy array called a. I want to perform an operation on a that increments all the values inside it that are less than 0 and leaves the rest alone. for example, if I had:

a = np.array([1,2,3,-1,-2,-3])

I would want to return:

([1,2,3,0,-1,-2])

What is the most compact syntax for this?

Thanks!

like image 258
pr0crastin8r Avatar asked Aug 04 '10 19:08

pr0crastin8r


People also ask

How can we use conditions in NumPy within an array?

It returns a new numpy array, after filtering based on a condition, which is a numpy-like array of boolean values. For example, if condition is array([[True, True, False]]) , and our array is a = ndarray([[1, 2, 3]]) , on applying a condition to array ( a[:, condition] ), we will get the array ndarray([[1 2]]) .

Does += work with NumPy arrays?

Numpy arrays are mutable objects that have clearly defined in place operations. If a and b are arrays of the same shape, a += b adds the two arrays together, using a as an output buffer.

How do I add an array to a NumPy array?

You can use numpy. append() function to add an element in a NumPy array. You can pass the NumPy array and multiple values as arguments to the append() function. It doesn't modify the existing array but returns a copy of the passed array with given values added.


2 Answers

In [45]: a = np.array([1,2,3,-1,-2,-3])

In [46]: a[a<0]+=1

In [47]: a
Out[47]: array([ 1,  2,  3,  0, -1, -2])
like image 118
unutbu Avatar answered Sep 28 '22 02:09

unutbu


To mutate it:

a[a<0] += 1

To leave the original array alone:

a+[a<0]
like image 45
John Kugelman Avatar answered Sep 28 '22 02:09

John Kugelman