通过阅读Python文档和stackoverflow我无法弄清楚的东西。可能我在想错误的方向..
假设我有一个预定义的2D Numpy数组,如下所示:
a = np.zeros(shape=(3,2))
print a
array([[ 0., 0.],
[ 0., 0.],
[ 0., 0.]])
现在我想用一维数据阵列(逐个)填充这个2D数组的每一列,如:
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.]])
任何建议都将不胜感激!
答案 0 :(得分: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.]])