在python中使用.csv按特定列数据排序

2024-05-15 07:54:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着订购一个.csv文件,它只有300多个条目,然后按照方言下一个特定列中的数值顺序输出。 这是我到目前为止编写的代码,但它似乎只是在数据进入时输出数据

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是第一个)。 任何帮助都将不胜感激。


Tags: 文件csv数据lambdaimportredresultopen
3条回答

groupby不是用于排序,而是用于对iterable进行分块。使用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,将字符数据强制转换为浮点数,以便进行正确的数字排序。

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_csvto_csv,以匹配CSV文件的格式。

通过测试,我发现下面的代码对我拥有的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()

相关问题 更多 >