从numpydocs
>>> np.where([[True, False], [True, True]],
... [[1, 2], [3, 4]],
... [[9, 8], [7, 6]])
array([[1, 8],
[3, 4]])
根据docs参数,我假设[[True, False], [True, True]]
部分是条件,[[1, 2], [3, 4]]
和[[9, 8], [7, 6]]
分别是x和y是对的。你知道吗
那么函数究竟是如何选择以下示例中的元素的呢?你知道吗
另外,为什么这些示例中的元素类型是列表?你知道吗
>>> np.where([[True, False,True], [False, True]], [[1, 2,56], [3, 4]], [[9, 8,79], [7, 6]])
array([list([1, 2, 56]), list([3, 4])], dtype=object)
>>> np.where([[False, False,True,True], [False, True]], [[1, 2,56,69], [3, 4]], [[9, 8,90,100], [7, 6]])
array([list([1, 2, 56, 69]), list([3, 4])], dtype=object)
在第一种情况下,每个术语都是一个
(2,2)
数组(或者更确切地说是可以组成这样一个数组的列表)。对于条件中的每个True
,它返回x
中相应的项[[1 -][3,4]]
,对于每个False
,返回来自y
[[- 8][- -]]
的项在第二种情况下,名单参差不齐
数组是(2,),有两个列表。当转换为布尔值时,一个2元素数组,两者都为真。只有空列表才会产生False。你知道吗
where只返回
x
值。你知道吗第二个病例是可以理解的,但是是病理性的。你知道吗
更多细节
让我们用一个更简单的例子来更详细地演示
where
。相同条件数组:单参数版本,相当于
condition.nonzero()
:有些人发现更容易将元组的
transpose
可视化,即condition
为真的3对坐标:现在最简单的版本有3个参数,标量值。你知道吗
可视化此操作的一个好方法是使用两个隐藏的任务。你知道吗
另一种方法是用
y
值初始化一个数组,其中非零值填充x
值。你知道吗如果
x
和y
是数组,而不是标量,那么这个掩蔽的赋值将需要细化,但希望从一开始这会有所帮助。你知道吗np.where(condition,x,y)
它检查条件,如果其真值返回x,否则返回ynp.where([[True, False], [True, True]], [[1, 2], [3, 4]], [[9, 8], [7, 6]])
这里的条件是
[[True, False], [True, True]] x = [[1 , 2] , [3 , 4]] y = [[9 , 8] , [7 , 6]]
第一个条件为true,因此它返回1而不是9
第二个条件为false,因此它返回8而不是2
在阅读了@hpaulj建议的broadcasting之后,我想我知道了函数的工作原理。 它将尝试广播3个数组,然后如果广播成功,它将使用
True
和False
值从x或y中选取元素。 在示例中我们有
现在
所以这三个数组都是有2个元素(类型列表)甚至条件(cnd)的数组,所以
[True, False,True]
和[False, True]
都将被计算为True
,并且这两个元素都将从x中选择我还尝试了一个更复杂的例子(一个
2x2x2
广播),它仍然解释了这个问题。你知道吗在哪里
这里
cnd
和x
具有形状(2,2,2)
,y
具有形状(2,2)
。你知道吗现在@hpaulj评论说
y
将广播到(2,2,2)。 可能是这样的结果很容易预测
相关问题 更多 >
编程相关推荐