1

通过阅读 Python 文档和 stackoverflow,我无法弄清楚。可能我想错了方向..

假设我有一个预定义的 2D Numpy 数组,如下所示:

a = np.zeros(shape=(3,2)) 
print a
array([[ 0.,  0.],
       [ 0.,  0.],
       [ 0.,  0.]])

现在我想用一维数据数组(一个接一个)填充这个二维数组的每一列,如下所示:

b = np.array([1,2,3])

# Some code, that I just can't figure out. I've studied insert, column_stack, 
# h_stack, append. Nothing seems to do what I need

print a
array([[ 1.,  0.],
       [ 2.,  0.],
       [ 3.,  0.]])

c = np.array([4,5,6])

# Some code, that I just can't figure out. I've studied insert, column_stack, 
# h_stack, append. Nothing seems to do what I need

print a
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])

任何建议,将不胜感激!

4

1 回答 1

1

您可以分配给具有切片的列:

>>> a[:,0] = b
>>> a
array([[ 1.,  0.],
       [ 2.,  0.],
       [ 3.,  0.]])

要一次分配它们而不是一次分配一个,请使用np.column_stack

>>> np.column_stack((b, c))
array([[1, 4],
       [2, 5],
       [3, 6]])

如果您需要将它放回同一个数组中,而不仅仅是具有相同的名称,您可以分配给包含整个矩阵的切片(这在列表中很常见):

>>> a[:] = np.column_stack((b, c))
>>> a
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])
于 2013-06-06T10:51:06.170 回答