Reputation: 569
I have a numpy
array, e.g.,
import numpy as np
A = np.exp(np.random.randn(3,10))
i.e., the array
array([[ 1.17164655, 1.39153953, 0.68628548, 0.1051013 ],
[ 0.45604269, 2.21059251, 1.79624195, 0.37553947],
[ 1.03063907, 0.28035114, 1.70371105, 3.66090236]])
and I compute the maximum of row as follows
np.max(A, axis=1)
array([ 1.39153953, 2.21059251, 3.66090236])
I want to zero the elements of A
, whose values are less than a fraction of the maximum value of the corresponding row. For instance, for the above example, if we set this fraction to 0.9, I would like to zero the following elements:
1st row: Zero the elements that are less than 0.9 * maximum = 1.25238557
2nd row: Zero the elements that are less than 0.9 * maximum = 1.98953326
3rd row: Zero the elements that are less than 0.9 * maximum = 3.29481212
I took a look at numpy
's documentation, but I had no luck. I also tried
A < np.max(A, axis=1)
which I'd expect to work, but it doesn't.
Upvotes: 1
Views: 135
Reputation: 281958
Use the keepdims
argument to keep a length-1 axis instead of removing the collapsed axis, so the axes line up with the original shape for broadcasting:
A[A < 0.9*np.amax(A, axis=1, keepdims=True)] = 0
Upvotes: 3