简体   繁体   English

将CSV文件读入一个numpy数组,返回none

[英]Reading a CSV File into a numpy array returning none

I am trying to read a CSV data set into a two-dimensional numpy array and then return said array. 我试图将CSV数据集读入二维numpy数组,然后返回所述数组。 I continue to get a return none message and am unsure of my approach to this problem - I am new to numpy. 我继续收到一条返回无消息,并且不确定我对这个问题的处理方法 - 我是numpy的新手。

To be clear, the data set contains has two columns and about 100 rows of data. 需要说明的是,数据集包含两列和大约100行数据。 I want to create an array that consists of the first column of data being the x co-ordinates and the second column of data being the y co-ordinates. 我想创建一个数组,其中第一列数据是x坐标,第二列数据是y坐标。

import numpy as np 

data = open("mydata.csv")
read = data.read()

def generatingArray(read):
    for data in read:
        dataPoints = np.array(read[0], read[1])

        return dataPoints

print(generatingArray(dataFile))

When I call the function it returns 'None.' 当我调用该函数时,它返回'None'。 Playing around with the placement of the return statement typically gives me an error message. 使用return语句的位置通常会给我一个错误消息。 Any suggestions on how to adjust my code would be greatly appreciated. 任何关于如何调整我的代码的建议将不胜感激。

First thing is change the variable name 'read' to something else. 首先,将变量名称“read”更改为其他内容。 It is a bad practice to use variable names sharing with built-in methods/keywords. 使用与内置方法/关键字共享的变量名称是一种不好的做法。

X=[]
Y=[]
with open('mydata.csv','r') as f:
#opens file for reading
    for line in f:#this reads a line
         a,b=line.split()
         X.append(a)
         Y.append(b)
      #appends first element to listX second to Y

Use with-open when you have to read a line. 必须阅读一行时使用with-open。 Since a line has two space seperated values ,you split it and extract the two values and append it to lists X and Y containing X and Y coordinates. 由于一条线有两个空格分隔值,因此将其拆分并提取两个值并将其附加到包含X和Y坐标的列表X和Y. Now if you want to have a numpy array use this: ar=np.array([X,Y]) [X,Y] is a 2Dlist and no.array converts a list to numpy array. 现在,如果你想拥有一个numpy数组,请使用: ar=np.array([X,Y]) [X,Y]是一个2Dlist,no.array将列表转换为numpy数组。

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

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