Python Forum
Import CSV data into array and turn into integers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Import CSV data into array and turn into integers (/thread-28366.html)



Import CSV data into array and turn into integers - DoctorSmiles - Jul-16-2020

Hey guys,

I am working on a school project and need to make it so that i can import data from a CSV file into an array and use it to do calculations. I am able to import the file but when i do it imports as strings. I also need that data in an array. This is what i have:
import csv 

x = []
y = []

with open('FinalData.csv') as csvfile:    
	csvReader = csv.reader(csvfile)    
	for row in csvReader:        
		x.append(row[0]), y.append(row[1])
        
print(x,y)
It will print the arrays but the number values will be strings. Any idea how to change?
Thanks for the help


RE: Import CSV data into array and turn into integers - sridhar - Jul-16-2020

In Python you have an option called list for the concept of array.
I couldn't able to get what your expected output will look like.
This might work !
import csv 
data =[]
 
with open('FinalData.csv') as csvfile:    
    csvReader = csv.reader(csvfile)    
    data = list (csvReader)
         
print(data) 



RE: Import CSV data into array and turn into integers - ndc85430 - Jul-16-2020

You need to use the int of float functions to convert the strings to numbers.


RE: Import CSV data into array and turn into integers - DoctorSmiles - Jul-16-2020

(Jul-16-2020, 04:21 AM)ndc85430 Wrote: import csv
data =[]
  
with open('FinalData.csv') as csvfile:   
    csvReader = csv.reader(csvfile)   
    data = list (csvReader)
          
print(data)

Can you explain? i tried adding x = int(x) but i got the error
int() argument must be a string, a bytes-like object or a number, not 'list'


RE: Import CSV data into array and turn into integers - ndc85430 - Jul-16-2020

That quote is wrong; I didn't write that code.

In any case, the error is self explanatory: you can't pass a list to int, only individual strings. So either iterate over the list calling it in each one or use a list comprehension (or map).


RE: Import CSV data into array and turn into integers - perfringo - Jul-16-2020

If floats are OK for calculations then one can use QUOTE_NONNUMERIC with csv.reader.

import csv

with open('numbers', 'r', newline='') as f:
    reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC)
    floats = list(*zip(*reader))
# floats value with random sample data, one value per row in 'numbers' file:
[5.0, 7.0, 12.0, 65.0, 7.0, 12.0, 65.0]