0

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?

2
  • 1
    What 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. Commented Jul 24, 2022 at 21:11
  • I tried this way and it worked with me stackoverflow.com/a/58178333/14599063 Commented Jul 24, 2022 at 21:19

4 Answers 4

1

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

Comments

0

I would use pandas for better performances and manipulation for future

import pandas

df = pandas.read_csv("example.csv")

for row in df.iterrows():
    print(row)

Comments

0

You can do it using the pandas and specifying the column names.

import pandas as pd
df=pd.read_csv("example.csv")
        
array1=df["col_name1"].values # as numpy array
array2=list(df["col_name2"].values) # as python array

Comments

0

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

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.

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.