[英]Reading CSV File into Numpy Array
I am attempting to open a CSV file that contains 4 columns with about 100 rows.我正在尝试打开一个 CSV 文件,其中包含 4 列大约 100 行。 I want to have a 2D numpy array, that sets the first column as the x-coordinates and sets the second column as the y-coordinates.
我想要一个二维 numpy 数组,它将第一列设置为 x 坐标并将第二列设置为 y 坐标。
import numpy as np
dataDocument = open("data.csv")
headers = dataDoument.readline()
def generateArray(dataDocument):
for numbers in dataDocument:
splitDocument = numbers.strip().split(",")
myArray = np.array(splitDocument[0], splitDocument[1])
return myArray
print(generateArray(dataDocument))
I keep getting various error messages, the most common being 'data type "" not understood.'我不断收到各种错误消息,最常见的是“无法理解数据类型”。 Any suggestions on where my logic error/general code error exists?
关于我的逻辑错误/一般代码错误在哪里存在的任何建议?
Try:尝试:
from numpy import genfromtxt
data = genfromtxt('data.csv', delimiter=',')
res = data[:,0:2]
You can also try:你也可以试试:
import numpy as np
d = np.loadtxt('a.csv', delimiter=',')
x = d[:,0]
y = d[:,1]
replace: myArray = np.array(splitDocument[0], splitDocument[1]) with: myArray = np.array((splitDocument[0], splitDocument[1])) in your method and should solve the issue.
Problem is due that you are passing the splitDocument[1]
to your np.array
as dtype parameter.问题是由于您将
splitDocument[1]
作为np.array
参数传递给您的np.array
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.