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)
2

3 Answers 3

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])
Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.