CSV列在Python阵列 [英] CSV Columns to Arrays in Python

查看:134
本文介绍了CSV列在Python阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很难对付的,在我看来是一个简单的问题。我试图导入CSV和其拆分成列,我可以运行不同的操作,然后压缩()一起回来阵列。

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

这code打印两个数组与个别字符,而不是字符串的元素。当我尝试与单个列要做到这一点,column1.extend(行)我想要做什么。

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.

我感兴趣的方式来解决这个特定的问题或概括这列n个。

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

推荐答案

您需要修改 column1.extend(行[0]) column1.append(行[0])(与同为列2,清楚)。延伸的,用于将一个列表中的内容到另一个,追加是添加单个元素。扩展告诉蟒蛇治疗字符串作为其字符的列表,并追加每个字符。

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']

这篇关于CSV列在Python阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆