我试图在两个Numpy数组之间编写一个连接操作,惊讶地发现Numpy的
recfunctions.join_by
不处理重复值。
我采取的方法是使用要连接的列,并在它们之间找到索引映射。从网上看,大多数仅Numpy的解决方案都存在无法处理重复的问题(您将在代码部分看到我的意思)。
如果可能的话,我希望完全留在Numpy库中,以利用矢量化操作,所以理想情况下没有原生Python代码、Pandas(出于其他原因)或Numpy索引。
以下是我研究过的几个问题:
A way to map one array onto another in numpy?
Find index mapping between two numpy arrays
Numpy: For every element in one array, find the index in another array
Index mapping between two sorted partially overlapping numpy arrays
例如,数组
X
和
Y
它们将使用来自它们中的每一个的柱连接,
x
和
y
分别。
映射定义为,以及
f
这就是我想要的
mapping = f(x, y)
x = y[mapping]
例如,
x = np.array([1,1,2,100])
y = np.array([1,2,3,4,5,6,7])
mapping = [0, 0, 1, -] # '-' indicates masked
x = y[mapping]
从网上查看类似问题,找到以下映射
x
到
y
有
np.where(np.isin(x,y))
其对值进行重复数据消除。还有
np.searchsorted(x,y)
它不处理中的重复项
x
完全。我想知道是否还有别的办法。
由于中的重复,以下不是正确的映射
x
import numpy as np
x = np.array([1,1,2,100])
y = np.array([1,2,3,4,5,6,7])
mapping = np.searchsorted(x, y)
# [0 2 3 3 3 3 3]
这也不是一个正确的映射,因为映射的长度需要与
x
.
import numpy as np
x = np.array([1,1,2,100])
y = np.array([1,2,3,4,5,6,7])
mapping = np.where(np.isin(x, y))[0]
# [0, 1, 2]