一维和二维数组之间的元素明智比较 [英] Element wise comparison between 1D and 2D array

查看:161
本文介绍了一维和二维数组之间的元素明智比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要在1D和2D数组之间执行元素明智的比较.需要将1D数组的每个元素与2D的相应行进行比较(例如,更大),然后创建一个遮罩.这是一个示例:

Want to perform an element wise comparison between an 1D and 2D array. Each element of the 1D array need to be compared (e.g. greater) against the corresponding row of 2D and a mask will be created. Here is an example:

A = np.random.choice(np.arange(0, 10), (4,100)).astype(np.float)
B = np.array([5., 4.,  8.,  2. ])

我想做

A<B 

,以便将A的第一行与B [0](即5)进行比较,结果将是一个布尔数组.

so that first row of A will be compared against B[0] which is 5. and the result will be an boolean array.

如果我尝试这样做,我将得到:

If I try this I get:

operands could not be broadcast together with shapes (4,100) (4,)

有什么想法吗?

推荐答案

您需要在数组 B 中插入一个额外的维度:

You need to insert an extra dimension into array B:

A < B[:, None]

这允许NumPy正确匹配两个形状以进行广播; B 现在具有形状(4,1),并且尺寸可以配对:

This allows NumPy to properly match up the two shapes for broadcasting; B now has shape (4, 1) and the dimensions can be paired up:

(4, 100)
(4,   1)

规则是尺寸要么具有相同的长度,要么长度之一必须为1;否则,长度不能为1.这里100可以与1配对,而4可以与4配对.在插入新尺寸之前,NumPy尝试将100与4配对,这会引起错误.

The rule is that either the dimensions have the same length, or one of the lengths needs to be 1; here 100 can be paired with 1, and 4 can be paired with 4. Before the new dimension was inserted, NumPy tried to pair 100 with 4 which raised the error.

这篇关于一维和二维数组之间的元素明智比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆