通过第一列比较两个numpy数组,并通过连接两个数组创建第三个numpy数组

时间:2014-09-01 07:29:42

标签: python arrays numpy

我有两个2d numpy数组,用于绘制模拟结果。

两个数组ab的第一列包含时间间隔,第二列包含要绘制的数据。这两个数组具有不同的形状a(500,2) b(600,2)。我想通过第一列比较这两个numpy数组,并创建第三个数组,其中匹配项位于a的第一列。如果未找到匹配项,请将0添加到第三列。

这样做有什么难题吗?

例如:

a=[[0.002,0.998],  
  [0.004,0.997],   
  [0.006,0.996],   
  [0.008,0.995],   
  [0.010,0.993]]   

b= [[0.002,0.666],  
    [0.004,0.665],  
    [0.0041,0.664], 
    [0.0042,0.664], 
    [0.0043,0.664], 
    [0.0044,0.663], 
    [0.0045,0.663], 
    [0.0005,0.663], 
    [0.006,0.663], 
    [0.0061,0.662],
    [0.008,0.661]] 

预期产出

c= [[0.002,0.998,0.666],       
    [0.004,0.997,0.665],           
    [0.006,0.996,0.663],           
    [0.008,0.995,0.661],
    [0.010,0.993, 0   ]]  

3 个答案:

答案 0 :(得分:2)

我可以快速将解决方案视为

import numpy as np

a = np.array([[0.002, 0.998],
     [0.004, 0.997],
     [0.006, 0.996],
     [0.008, 0.995],
     [0.010, 0.993]])

b = np.array([[0.002, 0.666],
     [0.004, 0.665],
     [0.0041, 0.664],
     [0.0042, 0.664],
     [0.0043, 0.664],
     [0.0044, 0.663],
     [0.0045, 0.663],
     [0.0005, 0.663],
     [0.0006, 0.663],
     [0.00061, 0.662],
     [0.0008, 0.661]])


c = []
for row in a:
    index = np.where(b[:,0] == row[0])[0]
    if np.size(index) != 0:
      c.append([row[0], row[1], b[index[0], 1]])
    else:
      c.append([row[0], row[1], 0])

print c

正如上面的评论所指出,似乎存在数据输入错误

答案 1 :(得分:2)

import numpy as np
i = np.intersect1d(a[:,0], b[:,0])
overlap = np.vstack([i, a[np.in1d(a[:,0], i), 1], b[np.in1d(b[:,0], i), 1]]).T
underlap = np.setdiff1d(a[:,0], b[:,0])
underlap = np.vstack([underlap, a[np.in1d(a[:,0], underlap), 1], underlap*0]).T
fast_c = np.vstack([overlap, underlap])

这可以通过使用intersect1d获取ab的第一列的交集,然后使用in1d来交叉引用与第二列的交集

vstack垂直堆叠输入元素,需要转置才能获得正确的尺寸(非常快速的操作)。

然后在a中使用setdiff1d查找不在b中的时间,并通过在第三列中添加0来完成结果。

打印出来

array([[ 0.002,  0.998,  0.666],
       [ 0.004,  0.997,  0.665],
       [ 0.006,  0.996,  0.   ],
       [ 0.008,  0.995,  0.   ],
       [ 0.01 ,  0.993,  0.   ]])

答案 2 :(得分:0)

以下适用于numpy数组和简单的python列表。

c = [[*x, y[1]] for x in a for y in b if x[0] == y[0]]
d = [[*x, 0] for x in a if x[0] not in [y[0] for y in b]]
c.extend(d)

比我更勇敢的人可以尝试制作这一行。