在纯Python中,您可以很容易地逐列增长矩阵:
data = []
for i in something:
newColumn = getColumnDataAsList(i)
data.append(newColumn)
NumPy的数组没有append函数。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
..。或者使用Python列表并稍后转换为数组:
data = []
for i in something:
newColumn = getColumnDataAsNumpyArray(i)
data.append(newColumn)
data = numpy.array(data)
这两种变体看起来都有点尴尬。有没有更好的解决方案?
发布于 2009-11-24 00:07:23
通常,在创建NumPy数组时不会一直调整它的大小。你对你的第三个解决方案有什么不满意的地方?如果它是一个非常大的矩阵/数组,那么在你开始分配它的值之前,分配它可能是值得的:
x = len(something)
y = getColumnDataAsNumpyArray.someLengthProperty
data = numpy.zeros( (x,y) )
for i in something:
data[i] = getColumnDataAsNumpyArray(i)
发布于 2012-01-28 16:40:43
hstack可以在零大小的数组上工作:
import numpy as np
N = 5
M = 15
a = np.ndarray(shape = (N, 0))
for i in range(M):
b = np.random.rand(N, 1)
a = np.hstack((a, b))
https://stackoverflow.com/questions/1783251
复制相似问题