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
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.
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.
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']]
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