简体   繁体   English

添加Numpy数组不成功

[英]Unsuccessful in Appending Numpy Arrays

I am trying to iterate through a CSV file and create a numpy array for each row in the file, where the first column represents the x-coordinates and the second column represents the y-coordinates. 我试图遍历CSV文件并为文件中的每一行创建一个numpy数组,其中第一列表示x坐标,第二列表示y坐标。 I then am trying to append each array into a master array and return it. 然后我试图将每个数组附加到主数组并返回它。

import numpy as np 

thedoc = open("data.csv")
headers = thedoc.readline()


def generatingArray(thedoc):
    masterArray = np.array([])

    for numbers in thedoc: 
        editDocument = numbers.strip().split(",")
        x = editDocument[0]
        y = editDocument[1]
        createdArray = np.array((x, y))
        masterArray = np.append([createdArray])


    return masterArray


print(generatingArray(thedoc))

I am hoping to see an array with all the CSV info in it. 我希望看到一个包含所有CSV信息的数组。 Instead, I receive an error: "append() missing 1 required positional argument: 'values' Any help on where my error is and how to fix it is greatly appreciated! 相反,我收到一个错误:“append()缺少1个必需的位置参数:'values'非常感谢我的错误在哪里以及如何解决它的任何帮助!

Numpy arrays don't magically grow in the same way that python lists do. Numpy数组并没有像python列表那样神奇地增长。 You need to allocate the space for the array in your "masterArray = np.array([])" function call before you add everything to it. 在添加所有内容之前,需要在“masterArray = np.array([])”函数调用中为数组分配空间。

The best answer is to import directly to a numpy array using something like genfromtxt ( https://docs.scipy.org/doc/numpy-1.10.1/user/basics.io.genfromtxt.html ) but... 最好的答案是使用genfromtxt( https://docs.scipy.org/doc/numpy-1.10.1/user/basics.io.genfromtxt.html )直接导入numpy数组,但......

If you know the number of lines you're reading in, or you can get it using something like this. 如果你知道你正在阅读的行数,或者你可以使用这样的东西得到它。

file_length = len(open("data.csv").readlines())

Then you can preallocate the numpy array to do something like this: 然后你可以预先分配numpy数组来做这样的事情:

masterArray = np.empty((file_length, 2))

for i, numbers in enumerate(thedoc): 
    editDocument = numbers.strip().split(",")
    x = editDocument[0]
    y = editDocument[1]
    masterArray[i] = [x, y]

I would recommend the first method but if you're lazy then you can always just build a python list and then make a numpy array. 我会推荐第一种方法但是如果你很懒,那么你总是可以构建一个python列表然后创建一个numpy数组。

masterArray = []

for numbers in thedoc: 
    editDocument = numbers.strip().split(",")
    x = editDocument[0]
    y = editDocument[1]
    createdArray = [x, y]
    masterArray.append(createdArray)

return np.array(masterArray)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM