Dyland
Dyland

Reputation: 93

Reading CSV File into Numpy Array

I am attempting to open a CSV file that contains 4 columns with about 100 rows. 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.

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?

Upvotes: 0

Views: 6209

Answers (3)

n1tk
n1tk

Reputation: 2490

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.

Upvotes: 0

wander95
wander95

Reputation: 1366

You can also try:

 import numpy as np
 d = np.loadtxt('a.csv', delimiter=',')
 x = d[:,0]
 y = d[:,1]

Upvotes: 1

sentence
sentence

Reputation: 8903

Try:

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

res = data[:,0:2]

Upvotes: 1

Related Questions