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!
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]]) .
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.
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.
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])
To mutate it:
a[a<0] += 1
To leave the original array alone:
a+[a<0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With