【问题标题】:Fast merge elements of two arrays of arrays only if the element is different than zero仅当元素不为零时才快速合并两个数组数组的元素
【发布时间】:2021-09-29 20:33:18
【问题描述】:

所以我有两个 numpy 数组数组

a = [[[1, 2, 3, 4], [3, 3, 3, 3], [4, 4, 4, 4]]]
b = [[[0, 0, 4, 0], [0, 0, 0, 0], [0, 1, 0, 1]]]

两个数组的大小始终相同。

结果应该是这样的

c = [[[1, 2, 4, 4], [3, 3, 3, 3], [4, 1, 4, 1]]]

如何在 numpy 中以非常快速的方式做到这一点?

【问题讨论】:

    标签: python python-3.x numpy


    【解决方案1】:

    使用numpy.where:

    import numpy as np
    
    a = np.array([[1, 2, 3, 4], [3, 3, 3, 3], [4, 4, 4, 4]])
    b = np.array([[0, 0, 4, 0], [0, 0, 0, 0], [0, 1, 0, 1]])
    
    res = np.where(b == 0, a, b)
    print(res)
    

    输出

    [[1 2 4 4]
     [3 3 3 3]
     [4 1 4 1]]
    

    【讨论】:

      【解决方案2】:

      为了获得最佳速度,请直接使用b 标准。

      而不是

      np.where(b == 0, a, b)
      # array([[1, 2, 4, 4],
      #        [3, 3, 3, 3],
      #        [4, 1, 4, 1]])
      
      timeit(lambda:np.where(b==0,a,b))
      # 2.6133874990046024
      

      做得更好

      np.where(b,b,a)
      # array([[1, 2, 4, 4],
      #        [3, 3, 3, 3],
      #        [4, 1, 4, 1]])
      
      timeit(lambda:np.where(b,b,a))
      # 1.5850481310044415
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 2019-01-12
        • 1970-01-01
        相关资源
        最近更新 更多