Python Forum

Full Version: Import CSV data into array and turn into integers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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) 
You need to use the int of float functions to convert the strings to numbers.
(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'
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).
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]