acpigeon
acpigeon

Reputation: 1719

CSV Columns to Arrays in Python

I'm having a hard time dealing with what seems to me to be a simple problem. I'm trying to import a csv and split its columns into arrays that I can run different operations on, then zip() back together.

import csv

data = csv.reader(open('test.csv', 'rb'), delimiter=",", quotechar='|')
column1, column2 = [], []

for row in data:
    column1.extend(row[0])
    column2.extend(row[1])

print column1
print column2

This code prints two arrays with elements that are individual chars rather than strings. When I try to do this with a single column, column1.extend(row) does what I want.

I'm interested in ways to solve this particular problem or to generalize this to n number of columns.

Upvotes: 5

Views: 34910

Answers (4)

Aldur
Aldur

Reputation: 21

another option:

column1 = [row[0] for row in data]

Upvotes: 2

C2H5OH
C2H5OH

Reputation: 5602

Each row index is a string, so if you want to add it to your columns you either do this:

column1.append(row[0])

or this:

column1.extend([row[0]])

Upvotes: 1

Pico
Pico

Reputation: 603

column1 and column2 are lists. The method you want to use is append() not extend().

Check the official documentation: http://docs.python.org/tutorial/datastructures.html

Upvotes: 1

Nolen Royalty
Nolen Royalty

Reputation: 18633

You need to change column1.extend(row[0]) to column1.append(row[0]) (and the same for column2, clearly). Extend is for adding the contents of one list to another, append is for adding a single element. Extend is telling python to treat the string as a list of its chars and append each char.

>>> lst = []
>>> lst.extend("foo")
>>> lst
['f', 'o', 'o']
>>> lst.append("foo")
>>> lst
['f', 'o', 'o', 'foo']

Upvotes: 6

Related Questions