【问题标题】:put each rows of two array beside each other将两个数组的每一行并排放置
【发布时间】:2021-05-22 05:41:28
【问题描述】:

我有两个矩阵(AB),形状分别为 A = 2x3B = 2x1。我想构建第三个矩阵C,以便C 的每一行分别使用AB 的相应行的串联。例如,如下所示:

import numpy as np

# A.shape: (2, 3)
A = np.array([
    [  0., 1., 2.],
    [  0., 3., 5.]
])

# B.shape: (2, 1)
B = np.array([
    [0],
    [1]
])

我希望C 看起来像这样:

##  <----A---->|<-B->
[ [ 0., 1., 2.,   0. ],
  [ 0., 3., 5.,   1. ] ]

你能帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: python numpy concatenation


    【解决方案1】:

    对于那些可能需要解决方案的人,

    for i in range(2):
        eachrow =[]
        list1 = A[i,:]
        eachrow.append(list1)
        list2 = B[i,:]
        eachrow.append(list2)
        total.append(eachrow)
    C = np.array(total)
    

    【讨论】:

      【解决方案2】:

      解决方案

      使用任何一种以下三种方法 ? 来获得你想要的。您可以运行以下代码块来检查这一点。

      • 方法一C = np.concatenate((A, B), axis=1)
      • 方法二C = np.hstack((A, B))
      • 方法3不使用numpy

      代码:Method-1Method-2

      import numpy as np
      
      # A.shape: (2, 3)
      A = np.array([
          [  0., 1., 2.],
          [  0., 3., 5.]
      ])
      
      # B.shape: (2, 1)
      B = np.array([
          [0],
          [1]
      ])
      
      print(f'A.shape: {A.shape}')
      print(f'B.shape: {B.shape}')
      print('-'*20)
      
      ## Method-1: Concatenate A and B along axis=1 
      C = np.concatenate((A, B), axis=1)  ## ???
      
      ## Method-2: Stack A and B horizontally
      C = np.hstack((A, B)) ## ???
      
      # print C and it's shape
      print(f'C.shape: {C.shape}' + '\n' + '-'*20)
      print(f'C: \n{C}')
      

      输出

      A.shape: (2, 3)
      B.shape: (2, 1)
      --------------------
      C.shape: (2, 4)
      --------------------
      C: 
      [[0. 1. 2. 0.]
       [0. 3. 5. 1.]]
      

      代码:Method-3 ?

      纯pythonic解决方案:不使用numpy

      A = [[0.0, 1.0, 2.0], [0.0, 3.0, 5.0]] # A is a list
      B = [[0], [1]] # B is a list
      C = [] # empty list
      for rowA, rowB in zip(A, B):
          C.append(rowA + rowB)
      
      print(C)
      
      ## Output
      #  [[0.0, 1.0, 2.0, 0], [0.0, 3.0, 5.0, 1]]
      

      使用list-comprehension 可以在一行中编写相同的pythonic 解决方案。

      C = [rowA + rowB for rowA, rowB in zip(A, B)] # ??? A and B are lists
      #  [[0.0, 1.0, 2.0, 0], [0.0, 3.0, 5.0, 1]]
      

      【讨论】:

      • @Sadcow 试一试,如果您有任何问题,请告诉我。
      • 谢谢。我已经解决了。我刚刚发现这个,解决了我的问题:```for i in range(2): eachrow =[] list1 = A[i,:] eachrow.append(list1) list2 = B[i,:] eachrow.append (list2) total.append(eachrow) C = np.array(total)```
      • 你不应该附加这样的列表。 Numpy 使用矢量化,通常比附加列表快得多。人们使用 numpy(快速矩阵运算)是有原因的。你正在做的是一个次优的解决方案。
      • 你说得对。但我不知道其他选择。我的 A 和 B 矩阵非常非常大。这需要时间。我想为一些学习方法提供一个数据集。
      • 如果你需要非numpy的解决方案,看method-3。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2013-08-01
      相关资源
      最近更新 更多