1

可能重复:
在二维中扩展 numpy 数组的最简单方法是什么?

作为一个 Matlab 用户切换到 python 时,我感到很沮丧,因为我不知道所有的技巧,并且在代码工作之前被困在一起。下面是一个示例,其中我有一个要添加虚拟列的矩阵。当然,还有比下面的 zip vstack zip 方法更简单的方法。它有效,但这完全是一个菜鸟尝试。请赐教。提前感谢您抽出宝贵时间阅读本教程。

# 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
4

2 回答 2

2

使用np.column_stack

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)
于 2012-09-25T02:02:59.753 回答
0

有几个函数可以让您连接不同维度的数组:

在你的情况下,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

于 2012-09-25T08:19:10.313 回答