解决方案
使用任何一种以下三种方法 ? 来获得你想要的。您可以运行以下代码块来检查这一点。
-
方法一:
C = np.concatenate((A, B), axis=1)
-
方法二:
C = np.hstack((A, B))
-
方法3:不使用
numpy
代码:Method-1和Method-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]]