1

Is it possible to read csv files in columns instead of rows in python?

e.g. if i have a csv file like this:

a b c
1 0 1
1 4 1

How would one get a list of [a,1,1],[b,0,4],[c,1,1] or something of the sorts?

Markwin
  • 177
  • 2
  • 16
  • http://stackoverflow.com/questions/16503560/read-specific-columns-from-csv-file-with-python-csv this answers your question – WannaBeCoder Nov 22 '16 at 06:58

3 Answers3

3

You are looking for transpose functionality. To solve your problem,

  1. First read csv as rows and create row wise tuples in a list ex: [(a,b,c),(1,0,1),(1,4,1)..]
  2. Transpose above list using any of the solutions present in Transpose a matrix in Python.

Post transpose , your data will look like [(a,1,1),(b,0,4)..]

Community
  • 1
  • 1
Vijayakumar Udupa
  • 1,115
  • 1
  • 6
  • 15
3

use zip(*reader).

some.csv

a b c 
1 0 1 
1 4 1

scrip.py

import csv 
with open('some.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=' ')
    print zip(*reader)

output:

[('a', '1', '1'), ('b', '0', '4'), ('c', '1', '1')]
Fujiao Liu
  • 2,195
  • 2
  • 24
  • 28
0

You can use something like this:

# Open file and read lines
input_file = open('filename.csv')
lines = input_file.readlines()

# Create list with n sublists (n - number of columns)
l = [[] for _ in lines[0].split('\t')]

# Fill in sublists
for line in lines:
    for i, column in enumerate(line.split('\t')):    
        l[i].append(column)
Fejs
  • 2,734
  • 3
  • 21
  • 40