追加Numpy数组失败

2024-04-19 19:48:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图遍历CSV文件,并为文件中的每一行创建一个numpy数组,其中第一列表示x坐标,第二列表示y坐标。然后我尝试将每个数组附加到主数组中并返回它。你知道吗

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))

我希望看到一个数组中的所有CSV信息。相反,我收到一个错误:“append()缺少1个必需的位置参数:‘values' 任何帮助我的错误在哪里以及如何修复它是非常感谢的!你知道吗


Tags: 文件csvimportnumpy错误np数组array
1条回答
网友
1楼 · 发布于 2024-04-19 19:48:08

Numpy数组并不像python列表那样神奇地增长。您需要在“masterArray=np.数组([])”函数调用,然后再将所有内容添加到函数中。你知道吗

最好的方法是使用genfromtxt(https://docs.scipy.org/doc/numpy-1.10.1/user/basics.io.genfromtxt.html)之类的东西直接导入numpy数组,但是。。。你知道吗

如果你知道你在读的行数,或者你可以用这样的方法得到它。你知道吗

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

然后可以预先分配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]

我建议使用第一种方法,但是如果你很懒,那么你可以构建一个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)

相关问题 更多 >