1

Good morning everyone.

I have a csv file with 3 columns: product, quantity and price.

I want to create 3 list, one for each column.

I try with the following code, but this create a list for each row instead of a list for each column. Any idea, please??

Thanks in advance :)

import csv
with open ("./02_CSV_data.csv","r") as myCSV:
   contenido=csv.reader(myCSV)
   for i in contenido:
      print(i)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Why do you want to put them in separate lists? It's much easier to work with data if you keep the related information together. – Barmar Oct 04 '20 at 10:21
  • See https://stackoverflow.com/questions/6473679/transpose-list-of-lists – mousetail Oct 04 '20 at 10:21

3 Answers3

1

Append each element of the list to the appropriate list.

import csv

products = []
quantities = []
prices = []

with open ("./02_CSV_data.csv","r") as myCSV:
   contenido=csv.reader(myCSV)
   for i in contenido:
        products.append(i[0])
        quantities.append(i[1])
        prices.append(i[2])
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

I know you are trying to do this with csv but Pandas can do this easily :

Install Pandas using pip:

pip install pandas

Code to convert csv columns to list:

import pandas as pd

df = pd.read_csv(r'path/of/csv/file.csv')

list1 = df['col_name_1'].to_list()
list2 = df['col_name_2'].to_list()
list3 = df['col_name_3'].to_list()
Vishal Upadhyay
  • 781
  • 1
  • 5
  • 19
0

You can transpose the read in rows - this is less efficient then Barmars solution though - it creates the big list of data and then creates 3 smaller lists from it instead of only creating the smaller lists:

Create data:

with open ("./02_CSV_data.csv","w") as f:
    f.write("""
1,1a,1b
2,2a,2b
3,3a,3b
""")

Read data as rows:

import csv

data = []
with open ("./02_CSV_data.csv","r") as myCSV:
   contenido = csv.reader(myCSV)
   for i in contenido:
       if i: # avoid empty rows
           data.append(i)

Extract colums using zip():

products, quantities, prices = map(list, zip(*data))

print(products)
print(quantities)
print(prices)

Output:

['1', '2', '3']
['1a', '2a', '3a']
['1b', '2b', '3b']
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69