python - 使用 np.where 从子数组中查找元素

标签 python numpy

我正在尝试使用 np.where() 查找数组 X 中与数组 Y 中的元素匹配的所有元素,并且 where() 函数的条件是比较列表 (a) 而不是一个元素。请看下面的代码:

X = np.array([[0, 2], [2, 1], [1, 3], [5, 9], [6, 7], [4, 6]])
Y = np.array([1, 2, 3, 4, 4, 5])
a = [2, 3, 4]
matchedX = X[np.where(Y == a)]

我希望得到这样的结果:

array([[2, 1],
   [1, 3],
   [5, 9],
   [6, 7]])

但我得到了不同的结果:

array([], shape=(0, 2), dtype=int64)

所以,我需要一个替代解决方案,如果我不知道 a 的值,我可以获得相同的元素?下面这一行给出了我想要的确切结果,但我不知道以前的 a 值。

matchedX = X[np.where((Y == 2) | (Y==3) | (Y==4))]

最佳答案

可以使用numpy的set函数:

X[np.where(np.isin(Y, a))]

array([[2, 1],
       [1, 3],
       [5, 9],
       [6, 7]])

关于python - 使用 np.where 从子数组中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53346940/

相关文章:

python - Numpy 向量化错误

python - 声明大小未知的 2D numpy 数组

python - 使用 Tensorflow 的多元线性回归模型

python - 自定义数据集上的 Mask RCNN 训练挂起

python - 数据集中的成对比较

python - 属性错误 : module 'sys' has no attribute 'setdefaultencoding'

python - Pandas 在 python 中填充昨天数据(相同的 DateTime)中的缺失值

python - numpy.sum 性能取决于轴

Python 在迭代过程中就地修改字典条目

c++ - 在 C++ 上(在 ubuntu 上)我必须为编译器配置什么才能找到导入?(如 iostream、stdio、math 等)