python - Numpy.where 与值列表一起使用

标签 python numpy

我有一个二维和一维数组。我正在寻找包含至少一次来自 1d 数组的值的两行,如下所示:

import numpy as np

A = np.array([[0, 3, 1],
           [9, 4, 6],
           [2, 7, 3],
           [1, 8, 9],
           [6, 2, 7],
           [4, 8, 0]])

B = np.array([0,1,2,3])

results = []

for elem in B:
    results.append(np.where(A==elem)[0])

这有效并产生以下数组:

[array([0, 5], dtype=int64),
 array([0, 3], dtype=int64),
 array([2, 4], dtype=int64),
 array([0, 2], dtype=int64)]

但这可能不是最好的处理方式。按照这个问题 ( Search Numpy array with multiple values ) 给出的答案,我尝试了以下解决方案:

out1 = np.where(np.in1d(A, B))

num_arr = np.sort(B)
idx = np.searchsorted(B, A)
idx[idx==len(num_arr)] = 0 
out2 = A[A == num_arr[idx]]

但是这些给了我不正确的值:

In [36]: out1
Out[36]: (array([ 0,  1,  2,  6,  8,  9, 13, 17], dtype=int64),)

In [37]: out2
Out[37]: array([0, 3, 1, 2, 3, 1, 2, 0])

谢谢你的帮助

最佳答案

如果您需要知道 A 的每一行是否包含数组 B 的任何元素而不关心它是 B 的哪个特定元素,可以使用以下脚本:

输入:

np.isin(A,B).sum(axis=1)>0 

输出:

array([ True, False,  True,  True,  True,  True])

关于python - Numpy.where 与值列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49987552/

相关文章:

Python:在一个完整的项目中组织用户定义的异常

python - 为 pip 安装缓存远程存储库

python - Google App Engine 中的 key 生成

python - 根据列的值连续性按行拆分/分组 pandas DataFrame

numpy - 如何并行化函数 "leastsq"或/和 "curve_fit"

python - 将多个numpy图像转换为灰度

java - 以 RESTful 方式上传文件?

python - pexpect 匹配问题

python - keras 的形状问题 `fit_generator()`

python - NumPy 数组中相同行的索引