【问题标题】:Compare two numpy arrays by first Column and create a third numpy array by concatenating two arrays按第一列比较两个 numpy 数组,并通过连接两个数组创建第三个 numpy 数组
【发布时间】:2014-09-01 07:29:41
【问题描述】:

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

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

有什么 numpy 技巧可以做到这一点吗?

例如:

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   ]]  

【问题讨论】:

  • 你能把ab放在不同的行上,以便于将数据复制到IPython中吗?
  • 我已将 'a' 和 'b' 编辑为两个不同的行
  • a 有 6e-3,b 有 6e-4,而c 又有 6e-3,在它们的第一列中。这是数据输入错误吗?
  • c 是预期输出,a 和 b 是两个输入,a 和 b 的第一列是时间间隔,如 [0.002, 0.004],第三个数组 c 必须包含匹配的时间间隔 a 和b 他们的数据在第二列
  • a[2,0] 约为 6*10**-3。但是b[9,0]6*10**-4。因数 10 不同。我认为您的数据输入有误。

标签: python arrays numpy


【解决方案1】:

我可以很快想到解决方案

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

如上面cmets中指出的,好像有数据输入错误

【讨论】:

    【解决方案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 垂直堆叠输入的元素,需要转置才能得到正确的维度(非常快的操作)。

    然后使用setdiff1d 查找a 中不在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.   ]])
    

    【讨论】:

      【解决方案3】:

      以下内容适用于 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)
      

      比我勇敢的人可以尝试制作这条线。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-04
        相关资源
        最近更新 更多