Python 如何在for循环中逐行构建numpy数组?

Python 如何在for循环中逐行构建numpy数组?,python,numpy,Python,Numpy,这基本上就是我要做的: array = np.array() #initialize the array. This is where the error code described below is thrown for i in xrange(?): #in the full version of this code, this loop goes through the length of a file. I won't know the length until I

这基本上就是我要做的:

array = np.array()       #initialize the array. This is where the error code described below is thrown

for i in xrange(?):   #in the full version of this code, this loop goes through the length of a file. I won't know the length until I go through it. The point of the question is to see if you can build the array without knowing its exact size beforehand
    A = random.randint(0,10)
    B = random.randint(0,10)
    C = random.randint(0,10)
    D = random.randint(0,10)
    row = [A,B,C,D]
array[i:]= row        # this is supposed to add a row to the array with A,C,B,D as column values
这个代码不起作用。首先,它抱怨:TypeError:未找到必需的参数“object”(位置1)。但我不知道数组的最终大小


第二,我知道最后一行是不正确的,但我不知道如何在python/numpy中调用它。那我该怎么做呢

必须使用固定大小创建numpy数组。您可以创建一个小的行(例如,一行),然后一次附加一行,但这将是低效的。无法有效地将numpy阵列逐渐增长到未知大小。您需要提前决定您希望它的大小,或者接受代码效率低下的事实。根据数据的格式,您可以使用中的类似函数或各种函数来读取数据。

使用1D numpy数组列表或列表列表,然后将其转换为numpy 2D数组(或者根据需要使用更多嵌套和获取更多尺寸)


嗯,如果有预处理,那么用处理后的文件构建一个大的cvs或文本文件,然后使用numpy.fromfile还是一步一步地构建它更合理吗?另一种常见的
numpy
方法是收集列表中的“行”,并将其传递给
np.array
np.concatenate
。这就是
loadtxt
所做的。如果您不需要加载文件,您可以使用[subprocess]和[wc-l][code>array=np.empty((4,?)来读取其行数。?
import numpy as np

a = []
for i in range(5):
    a.append(np.array([1,2,3])) # or a.append([1,2,3])
a = np.asarray(a) # a list of 1D arrays (or lists) becomes a 2D array

print(a.shape)
print(a)