8

我正在尝试订购一个包含 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 是第一个)。任何帮助将不胜感激。

4

3 回答 3

10

使用熊猫怎么样?

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)

您可能需要调整选项以匹配 CSV 文件read_csvto_csv格式。

于 2013-03-22T01:54:26.437 回答
7

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 以将您的字符数据转换为浮点数以进行正确的数字排序。

于 2013-03-21T23:21:03.200 回答
2

我通过测试发现以下内容适用于我拥有的 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()
于 2014-01-16T18:00:49.383 回答