## NumPy中如何实现逐列增长矩阵？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (53)

```data = []
for i in something:
newColumn = getColumnDataAsList(i)
data.append(newColumn)```

NumPy数组没有附加函数。`hstack`函数不适用于大小为零的数组，因此以下内容无法工作：

```data = numpy.array([])
for i in something:
newColumn = getColumnDataAsNumpyArray(i)
data = numpy.hstack((data, newColumn)) # ValueError: arrays must have same number of dimensions```

```data = None
for i in something:
newColumn = getColumnDataAsNumpyArray(i)
if data is None:
data = newColumn
else:
data = numpy.hstack((data, newColumn)) # works```

```data = []
for i in something:
newColumn = getColumnDataAsNumpyArray(i)
data.append(newColumn)
data = numpy.array(data)```

### 2 个回答

NumPy使用append方法：

```import numpy as NP
my_data = NP.random.random_integers(0, 9, 9).reshape(3, 3)
new_col = NP.array((5, 5, 5)).reshape(3, 1)
res = NP.append(my_data, new_col, axis=1)```

```my_data = NP.random.random_integers(0, 9, 16).reshape(4, 4)
# the line to add--does not depend on array dimensions
new_col = NP.zeros_like(my_data[:,-1]).reshape(-1, 1)
res = NP.hstack((my_data, new_col))```

`hstack`给出的结果与`concatenate((my_data, new_col), axis=1)`我不知道他们是怎么比较性能的。

```>>> # initialize your skeleton array using 'empty' for lowest-memory footprint
>>> M = NP.empty(shape=(10, 5), dtype=float)

>>> # create a small function to mimic step-wise populating this empty 2D array:
>>> fnx = lambda v : NP.random.randint(0, 10, v)```

```>>> for index, itm in enumerate(range(5)):
M[:,index] = fnx(10)

>>> M
array([[ 1.,  7.,  0.,  8.,  7.],
[ 9.,  0.,  6.,  9.,  4.],
[ 2.,  3.,  6.,  3.,  4.],
[ 3.,  4.,  1.,  0.,  5.],
[ 2.,  3.,  5.,  3.,  0.],
[ 4.,  6.,  5.,  6.,  2.],
[ 0.,  6.,  1.,  6.,  8.],
[ 3.,  8.,  0.,  8.,  0.],
[ 5.,  2.,  5.,  0.,  1.],
[ 0.,  6.,  5.,  9.,  1.]])```

```>>> M[:3,:3]
array([[ 9.,  3.,  1.],
[ 9.,  6.,  8.],
[ 9.,  7.,  5.]])```

```x = len(something)
y = getColumnDataAsNumpyArray.someLengthProperty

data = numpy.zeros( (x,y) )
for i in something:
data[i] = getColumnDataAsNumpyArray(i)```