Suppose I have a 1D numpy array (A) containing 5 elements:
A = np.array([ -4.0, 5.0, -3.5, 5.4, -5.9])
I need to add 5 to all the elements of A that are lesser than zero. What is the numpy way to do this without for-looping ?
It can be done using mask:
A[A < 0] += 5
The way it works is - the expression A < 0 returns a boolean array. Each cell corresponds to the predicate applied on the matching cell. In the current example:
A < 0 # [ True False True False True]
And then, the action is applied only on the cells that match the predicate. So in this example, it works only on the True cells.
I found another answer:
A = np.where(A<0, A+5, A)
Related
import numpy as np
array = np.random.uniform(0.0, 1.0, (100, 2))
array[(array[:, 1:2] < 3.0).flatten()][:][1:2] = 4.0
I want to change the second value of the rows who is less than 3.0 to 4.0, but the above code does not work. I tried to search a little bit, it appears that fancy slicing always just operates on a copy of the original array. Is that true? How to do the correct assignment in this case?
Just use multi index (boolean index for the 1st dimension & integer index for 2nd dimension) to mutate in place:
array[array[:, 1] < 3, 1] = 4
array
# array([[2.59733369e-01, 4.00000000e+00],
# [5.08406931e-01, 4.00000000e+00],
# ...
I want to apply the function any() to all the rows of a matrix at the same time.
If I use any() with a vector, of course it will return True (or 1 in my case) whenever any element would return True:
import numpy as np
print any(np.array([0,0,0,1]))*1
Now suppose I have a matrix instead. If I want to obtain a vector with 1 and 0 depending on whether each element of the matrix would return True when taken alone, I can do it with a for loop:
matrix=np.array([[0,0,0],[0,0,1],[0,1,0]])
result=np.zeros(len(matrix)).astype('int')
i=0
for line in matrix:
result[i]=any(matrix[i])
i+=1
print result
However, this method does not seem very practical, because the elements of the matrix will be handled once at a time with the for loop. Is there a better way to extend any to a matrix input, in such a way that it returns a vector of several 1 and 0 as above?
Note that I do not want to use matrix.any() because it will just return a single True or False statement, whereas I want it to be applied to each individual element of the matrix.
numpy.any(matrix, axis=1)
numpy.any already has the functionality you want.
You can do this:
import numpy as np
matrix = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])
matrix_sums = np.sum(matrix, axis=1)
are_truthy_matrix_sums = matrix_sums > 0
print are_truthy_matrix_sums
We use np.sum to simplify the matrix to a 1D array with the sums, before comparing these sums against 0 to see if there were any truthy values in these rows.
This prints:
[False True True]
I need to know if all the elements of an array of numpy are equal to a number
It would be like:
numbers = np.zeros(5) # array[0,0,0,0,0]
print numbers.allEqual(0) # return True because all elements are 0
I can make an algorithm but, there is some method implemented in numpy library?
You can break that down into np.all(), which takes a boolean array and checks it's all True, and an equality comparison:
np.all(numbers == 0)
# or equivalently
(numbers == 0).all()
If you want to compare floats, use np.isclose instead:
np.all(np.isclose(numbers, numbers[0]))
np.array_equal() also works (for Python 3).
tmp0 = np.array([0]*5)
tmp1 = np.array([0]*5)
np.array_equal(tmp0, tmp1)
returns True
The following version checks the equality of all entries of the array without requiring the repeating number.
numbers_0 = np.zeros(5) # array[0,0,0,0,0]
numbers.ptp() == 0.0 # True
# checking an array having some random repeating entry
numbers_r = np.ones((10, 10))*np.random.rand()
numbers_r.ptp() == 0.0 # True
Are numpy methods necessary? If all the elements are equal to a number, then all the elements are the same. You could do the following, which takes advantage of short circuiting.
numbers[0] == 0 and len(set(numbers)) == 1
This way is faster than using np.all()
I have the foll. code in numpy:
mask_cntr = np.copy(map_ccodes)
mask_cntr[mask_cntr == cntr] = 1.0
mask_cntr[mask_cntr != 1.0] = 0.0
Here, I am copying the 2D array map_ccodes to mask_cntr, and assigning the values that equal cntr in that array to 1.0, and all others to 0.0.
Is there a faster and more pythonic way to do this in numpy?
np.where function accepts conditions and returns an output based on the condition being True or False:
np.where(mask_cntr == cntr, 1.0, 0.0)
Try
mask_cntr = 1.0*(map_ccodes==cntr)
I am assuming that cntr == 1 from your code?
Why do you need a separate mask anyway? You can always use the map_ccodes==cntr argument anywhere ...
I have an array x and I want to apply a function f to every item in the matrix that meets some condition. Does Numpy offer a mechanism to make this easy?
Here's an example. My matrix x is supposed to contain only elements in the exclusive range (0, 1). However, due to rounding errors, some elements can be equal to 0 or 1. For every element in x that is exactly 0 I want to add epsilon and for every element that is exactly 1 I want to subtract epsilon.
Edit: (This edit was made after I had accepted askewchan's answer.) Another way to do this is to use numpy.clip.
You can do this:
a = np.array([0,.1,.5,1])
epsilon = 1e-5
a[a==0] += epsilon
a[a==1] += -epsilon
The reason this works is that a==0 returns a boolean array, just like what Валера Горбунов referred to in their answer:
In : a==0
Out: array([True, False, False, False], dtype=bool)
Then you're using that array as an index to a, which exposes the elements where True but not where False. There's a lot that you can do with this, see http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html
Sorry this isn't more concrete, but you could create a Boolean array that has a TRUE value for every position that meets your condition and FALSE for those that don't.
For something like [0, 1, 0, 0] when testing for 1 you will get an array [FALSE, TRUE, FALSE, FALSE]. In which case you can do [0, 1, 0, 0] - (epsilon)[FALSE, TRUE, FALSE, FALSE] and leave the 0 values unaffected.
Boolean Array Example
You can use map() as documented at http://docs.python.org/2/tutorial/datastructures.html#functional-programming-tools:
def applyEpsilon(value):
myEpsilon = 0.001
if value == 0:
return myEpsilon
elif value == 1:
return 1-myEpsilon
return value
inputList = [0, 0.25, 0.5, 0.75, 0.99, 1]
print map(applyEpsilon, inputList)
Yields:
[0.001, 0.25, 0.5, 0.75, 0.99, 0.999]