我正在使用Python来读取cvs文件。 CSV文件有两列用','分隔。我只能阅读一列,当我尝试为下一列创建列表时,我得到一个空白列表。
我的代码如下:
import csv
with open('exdata1.csv') as inputData:
data = csv.reader(inputData, delimiter=',')
xVal = [row[0] for row in data]
yVal = [row[1] for row in data]
输出如下:
>>> xVal
['6.1101', '5.5277', '8.5186', '7.0032', '5.8598', '8.3829', '7.4764', '8.5781', '6.4862', '5.0546', '5.7107', '14.164', '5.734', '8.4084', '5.6407', '5.3794', '6.3654', '5.1301', '6.4296', '7.0708', '6.1891', '20.27', '5.4901', '6.3261', '5.5649', '18.945', '12.828', '10.957', '13.176', '22.203', '5.2524', '6.5894', '9.2482', '5.8918', '8.2111', '7.9334', '8.0959', '5.6063', '12.836', '6.3534', '5.4069', '6.8825', '11.708', '5.7737', '7.8247', '7.0931', '5.0702', '5.8014', '11.7', '5.5416', '7.5402', '5.3077', '7.4239', '7.6031', '6.3328', '6.3589', '6.2742', '5.6397', '9.3102', '9.4536', '8.8254', '5.1793', '21.279', '14.908', '18.959', '7.2182', '8.2951', '10.236', '5.4994', '20.341', '10.136', '7.3345', '6.0062', '7.2259', '5.0269', '6.5479', '7.5386', '5.0365', '10.274', '5.1077', '5.7292', '5.1884', '6.3557', '9.7687', '6.5159', '8.5172', '9.1802', '6.002', '5.5204', '5.0594', '5.7077', '7.6366', '5.8707', '5.3054', '8.2934', '13.394', '5.4369']
>>> yVal
[]
我不确定谷歌究竟要解决这个问题。任何处理此问题的教程?
答案 0 :(得分:3)
csv.reader()
个对象从底层文件对象读取数据,文件对象的文件位置在读取时从头到尾移动。如果您想再次阅读 ,则需要将文件指针倒回到开头:
xVal = [row[0] for row in data]
inputData.seek(0)
yVal = [row[1] for row in data]
但是,您最好只阅读一次和transposing the rows to columns:
xVal, yVal = zip(*data)[:2]
答案 1 :(得分:1)
我建议使用Pandas并将CSV作为数据框读取,然后您可以快速访问Numpy数组的列。代码示例
import pandas as pd
import numpy as np
df = pd.read_csv('exdata1.csv', header=None, names=['One', 'Two'])
print(df)
print(df.One)
print(df.Two)
答案 2 :(得分:0)
您可以在代码data = csv.reader(inputData, delimiter=',')
中更改此行data = list(csv.reader(inputData, delimiter=','))
。
这将创建您可以根据需要重复使用的列表。