0

Suppose I have a csv file containing five columns each having 200 data. I have used these two codes but either of those storing row wise data. Can anyone tell me how to store each column as an individual array in python directly form .csv file?

Code1:

import csv
with open("figure1_plotdata.csv") as f:
    reader = csv.reader(f)
    next(reader)
    data = [r for r in reader]
print (data)

Code2:

from numpy import genfromtxt
my_data = genfromtxt('figure1_plotdata.csv', delimiter=',')
print (my_data)
2

2 Answers 2

1

If you want to convert a CSV file to list where individual list corresponds to a column, you can use pandas to load the csv and apply transpose to get the desired result.

It can be done like this.

import pandas as pd

df = pd.read_csv('your_file_name.csv')

data_list = df.T.values.tolist()

print(data_list)

Sample dataframe

A   B   C
1   10  11
2   20  22
3   30  33

Result

[[1, 2, 3], [10, 20, 30], [11, 22, 33]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the simplest solution, it works perfectly for me!
0

Try something like this. Store the data in the csv file in a 2 dimensional data array data[i][j] with i being the column and j the row, both indices starting at 0. (Basically the originally data being transposed)

import csv

file_name = 'figure1_plotdata.csv'
data = [[] for i in range(5)]

with open(file_name) as csvfile:
    csvdata = csv.reader(csvfile, dialect='excel', delimiter=',')

    '''  store column value in a 2 dimensional data array data[i][j] 
         with i being the column and j the row '''
    for row in csvdata:
        for i, column in enumerate(row):
            data[i].append(column)

for i, column in enumerate(data):
    for j, value in enumerate(column):
        print(f'row {j}, column {i}: {value}')

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.