Home > Mobile >  how to export a columns of CSV file as an arrays in python?
how to export a columns of CSV file as an arrays in python?

Time:07-25

I have a CSV file containing 2 columns, I want to export these 2 columns as 2 arrays. How can I get it done using Python?

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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]
  • Related