Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn a csv file into a list of list in python

Tags:

python

list

csv

I want to be able to turn csv file into a list of lists with the column values for each list. For example:

6,2,4
5,2,3
7,3,6

into

[[6,5,7],[2,2,3],[4,3,6]]

Ive only managed to open the file and only having success printing it as rows

with open(input,'rb') as csvfile:
        csv_file = csv.reader(csvfile)

        header = csv_file.next() 

        raw_data = csv_file
like image 889
Kyuu Avatar asked Mar 24 '16 07:03

Kyuu


People also ask

How do I read a CSV file in a list?

Method 1: Using CSV module We can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries. We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV contents to list with or without headers.

How do I read a CSV file and store data in a dictionary Python?

The best way to convert a CSV file to a Python dictionary is to create a CSV file object f using open("my_file. csv") and pass it in the csv. DictReader(f) method. The return value is an iterable of dictionaries, one per row in the CSV file, that maps the column header from the first row to the specific row value.


1 Answers

In case you sure it's fixed number of items in each row, you can use zip:

import csv

with open('test.csv') as csvfile:
    rows = csv.reader(csvfile)
    res = list(zip(*rows))
    print(res)
    # [('6', '5', '7'), ('2', '2', '3'), ('4', '3', '6')]

Or in case it's different number of items in row:

6,2,4
5,2
7

Use zip_longest and filter:

import csv
from itertools import zip_longest

with open('test.txt') as csvfile:
    rows = csv.reader(csvfile)

    res = list(zip_longest(*rows))
    print(res)
    # [('6', '5', '7'), ('2', '2', None), ('4', None, None)]

    res2 = [list(filter(None.__ne__, l)) for l in res]
    print(res2)
    # [['6', '5', '7'], ['2', '2'], ['4']]
like image 176
Mikhail Gerasimov Avatar answered Sep 23 '22 09:09

Mikhail Gerasimov