python - 如何在 for 循环中逐行构建一个 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 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: Required argument 'object' (pos 1) not found。但我不知道数组的最终大小。

其次,我知道最后一行不正确,但我不确定如何在 python/numpy 中调用它。那我该怎么做呢?

最佳答案

必须创建具有固定大小的 numpy 数组。您可以创建一个小的行(例如,一行),然后一次追加一行,但这效率很低。无法有效地将 numpy 数组逐渐增长到不确定的大小。您需要提前决定您想要它的大小,或者接受您的代码将是低效的。根据您的数据格式,您可以使用类似 numpy.loadtxt 的格式。或 pandas 中的各种功能读入。

关于python - 如何在 for 循环中逐行构建一个 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35688312/

相关文章:

Python:用if语句替换Dataframe中的单元格值

python - 响应错误 : operation not permitted

python - 将 float64 项目的 Numpy 数组作为二进制插入 PostgreSQL

python - 将两个高斯组合成另一个高斯

python - Python Matplotlib stackplot 中的标签区域

python - 在析构函数中创建检查类型映射

python - 使用临时凭证将数据从 S3 存储桶传输到 GCP 存储桶

python - 按二维索引对三维 numpy 数组进行排序

python - 使用 Python 函数高效处理 DataFrame 行?

python - 向随机游走图添加动画 [Python]