将CSV文件读入Numpy数组

时间:2019-04-02 21:01:26

标签: python numpy

我对numpy很陌生。我正在尝试打开一个CSV文件,该文件包含4列和大约100行。我想要一个2D 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))

我不断收到各种错误消息,最常见的是“无法理解的数据类型”。关于我的逻辑错误/通用代码错误在哪里存在的任何建议?

3 个答案:

答案 0 :(得分:1)

尝试:

from numpy import genfromtxt    
data = genfromtxt('data.csv', delimiter=',')

res = data[:,0:2]

答案 1 :(得分:1)

您也可以尝试:

// This test will perma-hang if the exception is not thrown
[TestMethod]
[ExpectedException(typeof(OperationCanceledException))]
public async Task TestMethod1()
{
    var source = new Mock<IHttpManager>();
    source.Setup(s => s.TryCallThirdParty(It.IsAny<CancellationToken>())).Returns<CancellationToken>(
        async token =>
        {
            // Spin until the token is cancelled
            while (true)
            {
                token.ThrowIfCancellationRequested();
                // Add some delay to make this not-CPU-bound
                await Task.Delay(100);
            }
        });

    var tcs = new CancellationTokenSource(1000);
    await new Caller().Get(source.Object, tcs.Token);
}

答案 2 :(得分:0)

replace: myArray = np.array(splitDocument[0], splitDocument[1])
with: myArray = np.array((splitDocument[0], splitDocument[1])) 
in your method and should solve the issue.

问题是由于您要将splitDocument[1]作为dtype参数传递给np.array

相关问题