无法使用密钥lambda函数对csv文件进行排序

2024-09-19 23:34:31 发布

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

我有一个csv文件,我正在尝试使用python对其进行排序

^{tb1}$

我尝试按照“协议”列进行排序,但并没有产生结果

with open(svg.csv,'r') as open_file:
  rdr=csv.reader(open_file)
  sortcsv=sorted(rdr,key=lambda x:x[2])
open_file.close()
with open(svg.csv,'w') as file_out:
  writr=csv.writer(file_out)
  writr.writerows(sortcsv)

我还需要使用python在这个.csv文件上添加一个vlookup。你能告诉我怎么用python做vlookup吗


Tags: 文件csvsvg协议排序aswithopen
1条回答
网友
1楼 · 发布于 2024-09-19 23:34:31

PROTOCOL列使用1而不是2索引,因为它是第二列-即,您需要使用key=lambda x: x[1])对其值进行排序。注意,您不希望对标题行进行排序,因为在执行sort()之后,它可能不再是数据的第一行,因此必须将其删除并单独处理

下面的代码修复了这两个问题。我不知道如何在这个CSV数据上添加vlookup,因为我不知道这个词的意思。我认为这是一个Excel电子表格功能,但您尚未指定它的功能或工作方式

import csv

with open('svg.csv', 'r', newline='') as open_file:
    reader = csv.reader(open_file)
    header = next(reader)
    sortedcsv = sorted(reader, key=lambda x: x[1])
    sortedcsv.insert(0, header)

with open('svg_out.csv', 'w', newline='') as file_out:
    writer = csv.writer(file_out)
    writer.writerows(sortedcsv)

相关问题 更多 >