【问题标题】:Unsuccessful in Appending Numpy Arrays附加 Numpy 数组失败
【发布时间】:2019-08-26 20:14:21
【问题描述】:

我正在尝试遍历 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' 非常感谢任何有关我的错误在哪里以及如何解决它的帮助!

【问题讨论】:

  • numpy.append,不像list.append,不是就地操作。还提供指针 numpy.append(ind, i)
  • 参考this doc
  • 非常感谢您的评论。当我将 masterArray = np.append([createdArray]) 更改为 np.append(masterArray, createdArray) 时,它返回的只是 []。关于为什么现在发生这种情况的任何建议?
  • 查看answer
  • @Dyland 是的,这通常是一种更好的方法。最好的办法是根本不这样做,而是将整个文件读入一个 numpy 数组或 pandas 数据帧。

标签: python arrays numpy


【解决方案1】:

Numpy 数组不会像 python 列表那样神奇地增长。在添加所有内容之前,您需要在“masterArray = np.array([])”函数调用中为数组分配空间。

最好的答案是使用类似 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)

【讨论】:

  • genfromtxtloadtxt 使用列表追加方法。必须这样做,因为他们不提前知道行数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2017-05-22
  • 2020-06-02
相关资源
最近更新 更多