Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import csv as List of List of Integers

Tags:

python

list

csv

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]]
like image 641
cooldood3490 Avatar asked Apr 25 '15 14:04

cooldood3490


People also ask

How do I convert a CSV file to a list?

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.

Can you have integers in a 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.

How do I create an array of csv files in Python?

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.


1 Answers

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=',')]
like image 137
Padraic Cunningham Avatar answered Oct 03 '22 08:10

Padraic Cunningham