可能重复:
What's the simplest way to extend a numpy array in 2 dimensions?
作为一名Matlab用户切换到python,我一直很沮丧,因为我不知道所有的技巧,并且在代码工作之前就会被黑客攻击。下面是一个例子,我有一个矩阵,我想添加一个虚拟列。当然,有一种比下面的zip vstack zip方法更简单的方法。它有效,但它完全是一个noob尝试。请赐教。提前感谢您花时间学习本教程。
# BEGIN CODE
from pylab import *
# Find that unlike most things in python i must build a dummy matrix to
# add stuff in a for loop.
H = ones((4,10-1))
print "shape(H):"
print shape(H)
print H
### enter for loop to populate dummy matrix with interesting data...
# stuff happens in the for loop, which is awesome and off topic.
### exit for loop
# more awesome stuff happens...
# Now I need a new column on H
H = zip(*vstack((zip(*H),ones(4)))) # THIS SEEMS LIKE THE DUMB WAY TO DO THIS...
print "shape(H):"
print shape(H)
print H
# in conclusion. I found a hack job solution to adding a column
# to a numpy matrix, but I'm not happy with it.
# Could someone educate me on the better way to do this?
# END CODE
答案 0 :(得分:2)
In [12]: import numpy as np
In [13]: H = np.ones((4,10-1))
In [14]: x = np.ones(4)
In [15]: np.column_stack((H,x))
Out[15]:
array([[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
In [16]: np.column_stack((H,x)).shape
Out[16]: (4, 10)
答案 1 :(得分:0)
有几个函数可以让你concatenate数组在不同的维度:
在您的情况下,np.hstack
看起来像您想要的。 np.column_stack
将一组1D数组堆叠为2D数组,但您已经开始使用2D数组。
当然,没有什么能阻止你这么做:
>>> new = np.empty((a.shape[0], a.shape[1]+1), dtype=a.dtype)
>>> new.T[:a.shape[1]] = a.T
在这里,我们创建了一个带有额外列的空数组,然后使用一些技巧将第一列设置为a
(使用转置运算符T
,以便new.T
具有与a.T
相比的额外行...)