【问题标题】:How do I add a column to a python (matix) multi-dimensional array? [duplicate]如何将列添加到 python(矩阵)多维数组? [复制]
【发布时间】:2012-09-16 12:01:27
【问题描述】:

可能重复:
What's the simplest way to extend a numpy array in 2 dimensions?

作为一个 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

【问题讨论】:

标签: python multidimensional-array numpy matplotlib


【解决方案1】:

使用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)

【讨论】:

    【解决方案2】:

    有几个函数可以让你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 与@987654338 相比多了一行@...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多