I have a CSV file containing 2 columns and 1000 lines, I want to export these 2 columns as 2 arrays, each array containing the column values. How can I get it done using Python?
-
1What does "export as array" mean? I could see exporting as 2 CSV files. But arrays are in-memory things, not export things. There are a lot of examples out there for reading, manipulating and writing CSVs. Its best to get a script mostly working and ask questions if you have problems.tdelaney– tdelaney2022-07-24 21:11:48 +00:00Commented Jul 24, 2022 at 21:11
-
I tried this way and it worked with me stackoverflow.com/a/58178333/14599063Mike Brown– Mike Brown2022-07-24 21:19:13 +00:00Commented Jul 24, 2022 at 21:19
Add a comment
|
4 Answers
Using zip on the iterable of rows returned by csv.reader to assemble the data into columns:
import csv
with open('example.csv') as f:
reader = csv.reader(f)
columns_as_lists = [list(c) for c in zip(*reader)]
print(columns_as_lists[0]) # All the values in the first column of your CSV
print(columns_as_lists[1]) # All the values in the second column of your CSV
Comments
You can use List Comprehension and loop trough the csv file in this way:
import csv
with open('example.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
column1 = [row[0] for row in csv_reader]
column2 = [row[1] for row in csv_reader]
1 Comment
slothrop
column2 will be an empty list here. The first list comprehension exhausts the iterable csv_reader, so it has nothing to yield in the second list comprehension. csv_reader doesn't behave as a list of rows that can be repeatedly iterated over: it's a generator that yields rows.