使用csv读取读入多列

时间:2013-07-17 16:21:37

标签: csv python-2.7 import time-series multiple-columns

也许我只是挑剔但是作为试图转换的Matlab用户我真的在导入数据时遇到了麻烦。我似乎无法在读取CSV的情况下阅读超过两列数据。这是我正在使用的编码

x,y = [],[]
csv_reader = csv.reader(open('Data.csv'))
for line in csv_reader:
    x.append(line[0])
    y.append(line[1])

如果我使用超过2列的Data.csv,我似乎无法从第3列及以上返回任何内容,因此我必须读入几个csv文件以获取我想要的数据。

我还想提出一点,我只使用CSV格式,因为我无法弄清楚如何导入其他任何东西。同样,作为以前的Matlab用户,我更喜欢将电子表格复制到.txt文件中并导入。对此的任何指示也将不胜感激。非常感谢

1 个答案:

答案 0 :(得分:0)

只要我不断添加变量,即z = []和z.append(第[2]行)等等,这对我来说没问题。也许我误解了这些问题?

import csv
x,y,z = [],[],[]
csv_reader = csv.reader(open('Data.csv'))
for line in csv_reader:
    x.append(line[0])
    y.append(line[1])
    z.append(line[2])

如果从电子表格复制并粘贴到文本文件,则可以打开('Data.txt')并用\ t分割每一行,如果这是列之间的分隔符。

xx,yy,zz = [],[],[]
fromtextfile = open('Data.txt')
#(append each list) for 
 #item in the line, split by tabs, into a list for line in the file
[(xx.append(item[0]),yy.append(item[1]),zz.append(item[2])) \
 for item in [line[:-1].split('\t') for line in fromtextfile]]

#or

xxx,yyy,zzz = [],[],[]
fromtextfile = open('Data.txt')
temp = []
for line in fromtextfile:
    temp.append(line[:-1])
for item in temp:
    templist = item.split('\t')
    xxx.append(templist[0])
    yyy.append(templist[1])
    zzz.append(templist[2])

fromtextfile.close()