I have a numpy
array, e.g.,
我有一个numpy数组,例如,
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:
我想将A的元素归零,其值小于相应行的最大值的一小部分。例如,对于上面的示例,如果我们将此分数设置为0.9,我想将以下元素归零:
1st row: Zero the elements that are less than 0.9 * maximum = 1.25238557
第1行:将小于0.9 *的元素归零= 1.25238557
2nd row: Zero the elements that are less than 0.9 * maximum = 1.98953326
第2行:将小于0.9 *的元素归零= 1.98953326
3rd row: Zero the elements that are less than 0.9 * maximum = 3.29481212
第3行:将小于0.9 *的元素归零= 3.29481212
I took a look at numpy
's documentation, but I had no luck. I also tried
我看了一下numpy的文档,但我没有运气。我也试过了
A < np.max(A, axis=1)
which I'd expect to work, but it doesn't.
我希望它可以工作,但事实并非如此。
1 个解决方案
#1
3
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:
使用keepdims参数保持长度为1的轴而不是删除折叠的轴,因此轴与原始形状对齐以进行广播:
A[A < 0.9*np.amax(A, axis=1, keepdims=True)] = 0
#1
3
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:
使用keepdims参数保持长度为1的轴而不是删除折叠的轴,因此轴与原始形状对齐以进行广播:
A[A < 0.9*np.amax(A, axis=1, keepdims=True)] = 0