Python的csv模块按行处理数据,这是查看此类数据的常用方法。您似乎想要按列的方法。这是一种方法。
假设您的文件已命名
myclone.csv并包含
workers,constant,agew0,7.334,-1.406w1,5.235,-4.936w2,3.2225,-1.478w3,0,0
此代码应该给您一个或两个想法:
>>> import csv>>> f = open('myclone.csv', 'rb')>>> reader = csv.reader(f)>>> headers = next(reader, None)>>> headers['workers', 'constant', 'age']>>> column = {}>>> for h in headers:... column[h] = []...>>> column{'workers': [], 'constant': [], 'age': []}>>> for row in reader:... for h, v in zip(headers, row):... column[h].append(v)...>>> column{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}>>> column['workers']['w0', 'w1', 'w2', 'w3']>>> column['constant']['7.334', '5.235', '3.2225', '0']>>> column['age']['-1.406', '-4.936', '-1.478', '0']>>>
要将数值放入浮点数,请添加此内容
converters = [str.strip] + [float] * (len(headers) - 1)
提前做
for h, v, conv in zip(headers, row, converters): column[h].append(conv(v))
而不是上面类似的两行。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)