gpt4 book ai didi

python - 如何在 for 循环中逐行构建一个 numpy 数组?

转载 作者:行者123 更新时间:2023-11-28 16:27:06 24 4
gpt4 key购买 nike

这基本上就是我想要做的:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com