3

I have data in a csv file that looks like that is imported as this.

import csv

with open('Half-life.csv', 'r') as f:
    data = list(csv.reader(f))

the data will come out as this to where it prints out the rows like data[0] = ['10', '2', '2'] and so on.

What i'm wanting though is to retrieve the data as columns in instead of rows, to where in this case, there are 3 columns.

1
  • 6
    can you install pandas? pandas.read_csv('Half-life.csv') would do this and infer proper types for you. Commented Jun 7, 2016 at 17:54

3 Answers 3

7

You can create three separate lists, and then append to each using csv.reader.

import csv

c1 = []
c2 = []
c3 = []
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        c1.append(row[0])
        c2.append(row[1])
        c3.append(row[2])
Sign up to request clarification or add additional context in comments.

1 Comment

The for loop could be replaced with columns = zip(*reader).
6

A little more automatic and flexible version of Alexander's answer:

import csv
from collections import defaultdict

columns = defaultdict(list)
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        for i in range(len(row)):
            columns[i].append(row[i])
# Following line is only necessary if you want a key error for invalid column numbers
columns = dict(columns)

You could also modify this to use column headers instead of column numbers.

import csv
from collections import defaultdict

columns = defaultdict(list)
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    headers = next(reader)
    column_nums = range(len(headers)) # Do NOT change to xrange
    for row in reader:
        for i in column_nums:
            columns[headers[i]].append(row[i])
# Following line is only necessary if you want a key error for invalid column names
columns = dict(columns)

Comments

4

Another option, if you have numpy installed, you can use loadtxt to read a csv file into a numpy array. You can then transpose the array if you want more columns than rows (I wasn't quite clear on how you wanted the data to look). For example:

import numpy as np
# Load data
data = np.loadtxt('csv_file.csv', delimiter=',')
# Transpose data if needs be
data = np.transpose(data)

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.