【问题标题】:Numpy: Combine several arrays based on an indices arrayNumpy:根据索引数组组合几个数组
【发布时间】:2019-05-02 21:41:10
【问题描述】:

我有 2 个不同大小的数组 mn,例如:

x = np.asarray([100, 200])
y = np.asarray([300, 400, 500])

我还有一个大小为m+n 的整数数组,例如:

indices = np.asarray([1, 1, 0, 1 , 0])

我想将xy 组合成一个大小为m+n 的数组z,在这种情况下:

expected_z = np.asarray([300, 400, 100, 500, 200])

详细说明:

  • indices 的第一个值是 1,所以z 的第一个值应该来自y。因此300
  • indices的第二个值是1,所以z的第二个值也应该来自y。因此400
  • indices的第三个值是0,所以z的第三个值这次应该来自x。因此100
  • ...

我怎样才能在 NumPy 中有效地做到这一点?

提前致谢!

【问题讨论】:

    标签: python arrays numpy


    【解决方案1】:

    创建一个输出数组并使用布尔索引将xy 分配到输出的正确槽中:

    z = numpy.empty(len(x)+len(y), dtype=x.dtype)
    z[indices==0] = x
    z[indices==1] = y
    

    【讨论】:

      【解决方案2】:

      out 将是您想要的输出:

      out = indices.copy()
      out[np.where(indices==0)[0]] = x
      out[np.where(indices==1)[0]] = y
      

      或者按照上面的答案建议,只需这样做:

      out = indices.copy()
      out[indices==0] = x
      out[indices==1] = y
      

      【讨论】:

        【解决方案3】:

        我希望这可以帮助你:

        x          = np.asarray([100, 200])
        y          = np.asarray([300, 400, 500])
        indices    = np.asarray([1, 1, 0, 1 , 0])
        expected_z = np.asarray([])
        x_indice   = 0
        y_indice   = 0
        
        for i in range(0,len(indices)):
            if indices[i] == 0:
                expected_z = np.insert(expected_z,i,x[x_indice])
                x_indice += 1
            else:
                expected_z = np.insert(expected_z,i,y[y_indice])
                y_indice += 1
        
        expected_z
        

        输出是:

        output : array([300., 400., 100., 500., 200.])
        

        附:始终确保 len(indices) == len(x) + len(y) 和 :

        • 来自 y == len(y) 的值
        • 来自 x == len(x) 的值

        【讨论】:

        • 这需要二次时间并产生一个具有错误 dtype 的输出数组。
        • 感谢 Mehdi 的回复。如果数组很大,恐怕循环遍历数组会非常低效......
        • @FlorianPagnoux 对不起,我以为你有小数组
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-02
        • 2021-04-09
        • 2011-07-27
        • 1970-01-01
        • 2018-10-25
        相关资源
        最近更新 更多