Element wise comparison between 1D and 2D array

▼魔方 西西 提交于 2020-12-09 09:30:27

问题


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. ])

I want to do

A<B 

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,)

Any ideas?


回答1:


You need to insert an extra dimension into array B:

A < B[:, None]

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)

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.



来源:https://stackoverflow.com/questions/33045855/element-wise-comparison-between-1d-and-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!