如何在for循环中逐行构建一个numpy数组? [英] How to build a numpy array row by row in a for loop?

查看:877
本文介绍了如何在for循环中逐行构建一个numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is basically what I am trying to do:

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).但是我不知道数组的最终大小.

This code doesn't work. First of all it complains: TypeError: Required argument 'object' (pos 1) not found. But I don't know the final size of the array.

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

Second, I know that last line is incorrect but I am not sure how to call this in python/numpy. So how can I do this?

推荐答案

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

A numpy array must be created with a fixed size. You can create a small one (e.g., one row) and then append rows one at a time, but that will be inefficient. There is no way to efficiently grow a numpy array gradually to an undetermined size. You need to decide ahead of time what size you want it to be, or accept that your code will be inefficient. Depending on the format of your data, you can possibly use something like numpy.loadtxt or various functions in pandas to read it in.

这篇关于如何在for循环中逐行构建一个numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆