将值从一个numpy矩阵复制到另一个依赖于布尔掩码的值 [英] Copying values from one numpy matrix to another dependent on boolean mask
问题描述
作为一个简单的例子,我有以下内容:
As a simple example, I've got the following:
import numpy as np
a = np.matrix([[0.34, 0.44, 0.21, 0.51]])
a_max = np.matrix([[0.35, 0.40, 0.20, 0.50]])
我想应用一个转换,其中a中大于a_max的任何内容都以a_max为上限.我试图通过以下方式做到这一点:
I would like to apply a transformation where anything in a, that is greater than a_max, is capped at a_max. I have tried to do this via:
a[a>a_max] = a_max[a>a_max]
但是这会引发错误:
ValueError: array is not broadcastable to correct shape
执行此操作的正确方法是什么?忽略我正在做一个简单的最大值的事实(我猜颠簸的人可能具有内置工具来解决该特定问题).我真正的问题是使用一组更为复杂的布尔值来创建布尔值掩码,然后该布尔值掩码应替换替换矩阵中的值.
What is the proper way to do this? Ignore the fact that I am doing a simple maximum (I am guessing bumpy may have builtin tools to do that particular problem). My real problem uses a much more complicated set of booleans to create a boolean mask, which then should replace values from a replacement matrix.
推荐答案
如果使用数组而不是矩阵,则生活会容易得多;才行(tm).
Life's much easier if you work with arrays and not matrices; it Just Works (tm).
>>> a = np.array([[0.34, 0.44, 0.21, 0.51]])
>>> a_max = np.array([[0.35, 0.40, 0.20, 0.50]])
>>> a[a > a_max] = a_max[a > a_max]
>>> a
array([[ 0.34, 0.4 , 0.2 , 0.5 ]])
我想您可以使用np.where
,
>>> a = np.matrix([[0.34, 0.44, 0.21, 0.51]])
>>> a_max = np.matrix([[0.35, 0.40, 0.20, 0.50]])
>>> np.where(a > a_max, a_max, a)
matrix([[ 0.34, 0.4 , 0.2 , 0.5 ]])
>>>
这篇关于将值从一个numpy矩阵复制到另一个依赖于布尔掩码的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!