gpt4 book ai didi

python - 如何使用掩码将元素和索引放入原始数组中

转载 作者:行者123 更新时间:2023-12-04 10:13:12 28 4
gpt4 key购买 nike

我试图从元素匹配的两个数组中获取元素和索引。我想我想多了,但我已经尝试过 where函数和交叉点,不能让它工作。我的实际数组要长得多,但这里有两个简单的数组来演示我想要的:

import numpy as np

arr1 = np.array([0.00, 0.016, 0.033, 0.050, 0.067])
arr2 = np.array([0.016, 0.033, 0.050, 0.067, 0.083])

ind = np.intersect1d(np.where(arr1 >= 0.01), np.where(arr2 >= 0.01))

打印 ind显示 array([1, 2, 3, 4]) .从技术上讲,我想要元素 1, 2, 3, 4来自 arr1和元素 0, 1, 2, 3来自 arr2 ,这给出了元素 0.016, 0.033, 0.050, 0.067 ,在两个数组中都匹配。

最佳答案

np.where转换 bool 掩码,如 arr1 >= 0.01成索引。您可以直接使用蒙版进行选择,但它不可逆。您需要反转索引,因为您想与原始数组相交,而不是选择。确保设置 return_indices=Trueintersect1d 获取索引:

index1 = np.nonzero(arr1 >= 0.01)
index2 = np.nonzero(arr2 >= 0.01)
selection1 = arr1[index1]
selection2 = arr2[index1]

elements, ind1, ind2 = np.intersect1d(selection1, selection2, return_indices=True)

index1 = index1[ind1]
index2 = index2[ind2]

当你得到 elements直接从交集,索引 ind1ind2正在引用被屏蔽的选择。自 index1selection1中每个元素的原始索引, index1[ind1]转换 ind1回到 arr1引用范围。

你原来的表达其实毫无意义。您正在与满足您条件的每个数组中的索引相交。这与这些索引的值无关(根本不必匹配)。看似正确的结果纯粹是基于偶然的阵列构造的巧合。

关于python - 如何使用掩码将元素和索引放入原始数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61216291/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com