I have the following CSV file
12,29,63,44
54,43,65,34
I'm trying to import it as a list of list such that each index is an integer. Here's what I have so far.
import csv
filename = 'file.csv'
with open(filename, 'rU') as p:
#reads csv into a list of lists
my_list = list(list(rec) for rec in csv.reader(p, delimiter=','))
print my_list
>>> [['12','29','63','44'],['54','43','65','34']]
As you can see this produces a list of list of strings, not integers. How do I import the CSV file as a list of list of integers? like this
>>> [[12,29,63,44],[54,43,65,34]]
You can use the pandas library for this which has an inbuilt method to convert values to a list. Pandas. values property is used to get a numpy. array and then use the tolist() function to convert that array to list.
As you would expect, we can also assign list values to variables and pass lists as parameters to functions. A list can contain only integer items.
You can convert a CSV file to a NumPy array simply by calling np. loadtxt() with two arguments: the filename and the delimiter string. For example, the expression np. loadtxt('my_file.
map to int:
my_list = [list(map(int,rec)) for rec in csv.reader(p, delimiter=',')]
[[12, 29, 63, 44], [54, 43, 65, 34]]
Which is equivalent to:
my_list = [[int(x) for x in rec] for rec in csv.reader(p, delimiter=',')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With