我有以下4个数组,我想得到数组A和X中相等的值的索引,这些值对应于B和Y中相同位置的值。所以对于下面的例子
import numpy as np
A = np.asarray([400.5, 100, 700, 200, 15, 900])
B = np.asarray([500.5, 200, 500, 600.5, 8, 999])
X = np.asarray([400.5, 700, 100, 300, 15, 555, 900])
Y = np.asarray([500.5, 500,600.5, 100, 8, 555, 999])
我想要两个带索引的数组:
式中,indAB是A和B中的值的指数,它们等于X和Y中的值,indXY是X和Y中的值的指数,它们等于A和B中的值
这是我目前为止的尝试:
^{pr2}$我一直得到indXY的[0 1 2 4 6],这是不正确的。不应包括2,因为即使Y和B中为600.5,A和B中的200和100(分别)不相等。在
如果有人能提出解决办法,我将不胜感激。非常感谢!在
这是另一种方法。我敢说这是相对清楚的,由于使用了集合,它应该是高效的,而且它只需要
O( len(A) + len(X) )
内存。在甚至不需要
numpy
,但可以用于数组。在numpy_indexed包(免责声明:我是它的作者)包含高效优雅地完成这类事情的功能。这种方法的内存需求是线性的,计算要求是NlogN。对于您正在考虑的大量阵列,与当前接受的暴力方法相比,速度优势很容易达到数量级:
请注意,您也可以选择如何处理缺少的值。还要看一下set操作,比如npi交叉口(XY,AB);它们可能提供一个更简单的途径,让你在更高的层次上实现你的目标。在
试试这个:
输出:
^{pr2}$说明
AB
和{A
和{eq
保存AB
和XY
中元素的all-overall比较;np.newaxis
用于向AB
和{AB
在位置1获得一个新维度,在位置0中{==
通过数组的新维度广播数组。第一个np.logical_and.reduce
是确保这两个的“组件”是相等的(A
到{np.logical_or.reduce
操作检查从AB
到{XY
到{np.where
得到索引。在作为缺点,请注意,这需要一个大小为
len(A)
xlen(X)
x2的布尔数组,因此,如果原始数组非常则可能会遇到内存问题。在更新
如前所述,非常大的阵列可能是一个问题。如果您想“一次性”进行所有的比较,实际上并没有办法绕过它(中间数组的大小就是比较的次数)。但是,您也可以“按块”运行算法,例如:
输出仍然是:
^{pr2}$我使用2的
MAX_SIZE
只是为了说明它在示例中可以工作,但是在实践中,您可以根据您愿意使用的最大内存量来选择它(例如,对于MAX_SIZE = 10000
,它应该是几百兆字节的顺序)。MAX_SIZE
不需要小于数组的大小,也不必是数组大小的除数。在相关问题 更多 >
编程相关推荐