简体   繁体   English

numpy 中是否存在二维“位置”?

[英]Is there a 2-D "where" in numpy?

This might seem an odd question, but it boils down to quite a simple operation that I can't find a numpy equivalent for.这似乎是一个奇怪的问题,但它归结为一个非常简单的操作,我找不到 numpy 的等效项。 I've looked at np.where as well as many other operations but can't find anything that does this:我查看了np.where以及许多其他操作,但找不到执行此操作的任何内容:

a = np.array([1,2,3])
b = np.array([1,2,3,4])
c = np.array([i<b for i in a])

The output is a 2-D array (3,4), of booleans comparing each value. output 是一个二维数组 (3,4),由比较每个值的布尔值组成。

If you're asking how to get c without loop, try this如果你问如何在没有循环的情况下获得c ,试试这个

# make "a" a column vector
# > broadcasts to produce a len(a) x len(b) array
c = b > a[:, None]
c
array([[False,  True,  True,  True],
       [False, False,  True,  True],
       [False, False, False,  True]])

You can extend the approach in the other answer to get the values of a and b .您可以扩展其他答案中的方法以获取ab的值。 Given a mask of给定一个面具

c = b > a[:, None]

You can extract the indices for each dimension using np.where or np.nonzero :您可以使用np.wherenp.nonzero提取每个维度的索引:

row, col = np.nonzero(c)

And use the indices to get the corresponding values:并使用索引获取相应的值:

ag = a[row]
bg = b[col]

Elements of a and b may be repeated in the result.结果中可能会重复ab的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM