假设我有两个 ndarray:
a = [[1.1,10]
[2.2,20]
[3.3,30]
[4.4,40]
[5.5,50]]
b = [[1.5,100]
[1.9,200]
[2.3,250]
[3.9,300]]
我想将这两个表连接在一起,以便我返回:
c = [[1.1,10,None]
[2.2,20,200] #note this is 200 not 250
[3.3,30,250]
[4.4,40,300]
[5.5,50,300]]
换句话说,我想做类似“A 左连接 B,如果键不完全匹配,则使用小于且距离 B 最近的键”。
如果我没有正确地格式化这个问题,请原谅我,这是我在 StackOverflow 上的第一个问题,而且我不是专业的程序员。不过,我已经通过 StackOverflow 和 Google 进行了彻底的搜索。
我有某种预感,答案可能在 merging indexed array in Python 之间。 并使用掩码数组。基本上我不知道,请帮忙!
最佳答案
import numpy as np
a = np.array([[1.1,10],
[2.2,20],
[3.3,30],
[4.4,40],
[5.5,50]])
b = np.array([[1.5,100],
[1.9,200],
[2.3,250],
[3.9,300]])
idx = b[:,0].searchsorted(a[:,0], side='right')
bval = np.r_[np.nan, b[:,1]]
c = np.column_stack([a, bval[idx]])
print(c)
产量
[[ 1.1 10. nan]
[ 2.2 20. 200. ]
[ 3.3 30. 250. ]
[ 4.4 40. 300. ]
[ 5.5 50. 300. ]]
请注意,上述计算将 3.3
与 250
关联,而不是与 200
关联。如果我正确理解了问题,那么这就是期望的结果,因为 3.3 > 2.3
。
关于python - 在Python中连接ndarrays,其中索引是 float 并且仅近似相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19882943/