问题描述
我有两组坐标,想找出 coo
组的哪些坐标与 targets
组中的任何坐标相同.我想知道 coo
集中的索引,这意味着我想获取一个索引列表或布尔值.
I have two sets of coordinates and want to find out which coordinates of the coo
set are identical to any coordinate in the targets
set. I want to know the indices in the coo
set which means I'd like to get a list of indices or of bools.
import numpy as np
coo = np.array([[1,2],[1,6],[5,3],[3,6]]) # coordinates
targets = np.array([[5,3],[1,6]]) # coordinates of targets
print(np.isin(coo,targets))
[[ True False]
[ True True]
[ True True]
[ True True]]
期望的结果将是以下两个之一:
The desired result would be one of the following two:
[False True True False] # bool list
[1,2] # list of concerning indices
我的问题是...
-
np.isin
没有axis
属性,因此我可以使用axis = 1
. - 即使对输出的每一行应用 logical和,对于最后一个元素也会返回
True
,这是错误的.
np.isin
has noaxis
-attribute so that I could useaxis=1
.- even applying logical and to each row of the output would return
True
for the last element, which is wrong.
我知道循环和条件,但是我确信Python具备了更优雅的解决方案的方法.
I am aware of loops and conditions but I am sure Python is equipped with ways for a more elegant solution.
推荐答案
对于大数组,此解决方案的伸缩性将变差,在这种情况下,其他建议的答案将表现更好.
This solution will scale worse for large arrays, for such cases the other proposed answers will perform better.
这是利用 广播
的一种方法> :
Here's one way taking advantage of broadcasting
:
(coo[:,None] == targets).all(2).any(1)
# array([False, True, True, False])
详细信息
通过直接比较,将第一个轴添加到 coo
中,检查 coo
中的每一行是否与 target
中的另一行相匹配可以针对目标
进行广播:
Check for every row in coo
whether or not it matches another in target
by direct comparisson having added a first axis to coo
so it becomes broadcastable against targets
:
(coo[:,None] == targets)
array([[[False, False],
[ True, False]],
[[False, False],
[ True, True]],
[[ True, True],
[False, False]],
[[False, False],
[False, True]]])
然后检查第二个轴上哪个 ndarrays
具有 所有
值转换为 True
:
Then check which ndarrays
along the second axis have all
values to True
:
(coo[:,None] == targets).all(2)
array([[False, False],
[False, True],
[ True, False],
[False, False]])
最后使用 any
检查哪些行至少具有一个 True
.
这篇关于如何匹配两个numpy数组中包含的值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!