我想对this question中详述的csv文件执行类似的过程,但我收到一条错误消息:
TypeError: list indices must be integers
我想重新排列的csv文件包含float,text和integer数据类型的组合。我假设这是问题,但无法想出一种方法来修改下面的代码来插入数据。它会将标题信息写入新的CSV文件中。
我使用的是John Machin建议的相同代码,但我的写名称变量使用:
writenames = "ID,average,max,min,median,mode,stddev,skewness,kurtosis".split(",")
reader = csv.reader(open("/home/usrs/chris/Summary.csv", "rb"))
writer = csv.writer(open("/home/usrs/chris/SummaryNEW.csv", "wb"))
readnames = reader.next()
names2indicies = dict((name,index) for index, name in enumerate(readnames))
writeindices = [names2string[name] for name in writenames]
reorderfunct = operator.itemgetter(writeindices)
writer.writerow(writenames)
for row in reader:
writer.writerow(reorderfunct(row))
答案 0 :(得分:2)
operator.itemgetter()就是您所需要的:
inp=csv.reader(open(...))
outp=csv.writer(open(...))
map(outp.writerow,map(operator.itemgetter(x,y,z),inp))
其中x,y,z是您要重新排序的列。
但是,由于Summary.csv中的第一行是标题,因此您可以考虑使用DictReader和DictWriter:
writenames = "ID,average,max,min,median,mode,stddev,skewness,kurtosis".split(",")
reader = csv.DictReader(open("/home/usrs/chris/Summary.csv", "rb"))
writer = csv.DictWriter(open("/home/usrs/chris/SummaryNEW.csv", "wb"), \
fieldnames=writenames)
reorderfunct = lambda r: dict([(col, r[col]) for col in writenames])
writer.writeheader()
for row in reader:
writer.writerow(reorderfunct(row))