我正在尝试对一个仅有300多个条目的.csv文件进行排序,并将其全部输出,按方言下某一特定列中的数值排序。以下是我到目前为止编写的代码,但它似乎只是按原样输出数据
import csv
import itertools
from itertools import groupby as gb
reader = csv.DictReader(open('Full_List.csv', 'r'))
groups = gb(reader, lambda d: d['red label'])
result = [max(g, key=lambda d: d['red label']) for k, g in groups]
writer = csv.DictWriter(open('output.csv', 'w'), reader.fieldnames)
writer.writeheader()
writer.writerows(result)
整个文件中只有50行包含方言“红色标签”下的值,其他所有行都留空。它在.csv的Z列中(但不是最后一个),所以我假设该列的索引是25(0是第一个)。任何帮助都将不胜感激。
发布于 2013-03-22 09:54:26
使用pandas怎么样?
import pandas as pd
df = pd.read_csv('Full_List.csv')
df = df.sort('red label')
df.to_csv('Full_List_sorted.csv', index=False)
您可能需要将选项调整为read_csv
和to_csv
,以匹配CSV文件的格式。
发布于 2013-03-22 07:21:03
groupby
不是用来排序的,它是用来分块迭代的。对于排序,请使用sorted
。
import csv
reader = csv.DictReader(open('Full_List.csv', 'r'))
result = sorted(reader, key=lambda d: float(d['red label']))
writer = csv.DictWriter(open('output.csv', 'w'), reader.fieldnames)
writer.writeheader()
writer.writerows(result)
注意:我更改了lambda,将字符数据转换为浮点型,以便进行正确的数字排序。
发布于 2014-01-17 02:00:49
通过测试,我发现以下内容适用于我拥有的csv文件。请注意,该列的所有行都具有有效条目。
from optparse import OptionParser
# Create options.statistic using -s
# Open and set up input file
ifile = open(options.filein, 'rb')
reader = cvs.DictReader(ifile)
# Create the sorted list
try:
print 'Try the float version'
sortedlist = sorted(reader, key = lambda d: float(d[options.statistic]), reverse=options.high)
except ValueError:
print 'Need to use the text version'
ifile.seek(0)
ifile.next()
sortedlist = sorted(reader, key=lambda d: d[options.statistic], reverse=options.high)
# Close the input file. This allows the input file to be the same as the output file
ifile.close()
# Open the output file
ofile = open(options.fileout, 'wb')
writer = csv.DictWriter(ofile, fieldnames=outfields, extrasactions='ignore', restval = '')
# Output the header
writer.writerow(dict((fn, fn) for fn in outfields))
# Output the sorted list
writer.writerows(sortedlist)
ofile.close()
https://stackoverflow.com/questions/15559812
复制相似问题