python读取文件csv,先按第4列排序,再按第5列的数值排序

Posted 路随时间

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python读取文件csv,先按第4列排序,再按第5列的数值排序相关的知识,希望对你有一定的参考价值。

插入代码:

from operator import itemgetter

input_file = open("PDBhaemoglobinReport.csv")
output_file = open("PDBhaemoglobinSorted.csv","w")

table = []
header = input_file.readline() #读取并弹出第一行
for line in input_file:
    col = line.split(,) #每行分隔为列表,好处理列格式
    col[3] = float(col[3][1:-1])
    col[4] = int(col[4][1:-2]) #各行没有先strip 末位是\n
    table.append(col) #嵌套列表table[[8,8][*,*],...]

table_sorted = sorted(table, key=itemgetter(3, 4))#先后按列索引3,4排序

output_file.write(header + \t)
for row in table_sorted:                    #遍历读取排序后的嵌套列表
    row = [str(x) for x in row]             #转换为字符串格式,好写入文本
    output_file.write("\t".join(row) + \n)

input_file.close()
output_file.close()

 

附:

PDBhaemoglobinReportcsv内容

PDB ID,Chain ID,Exp. Method,Resolution,Chain Length
"1A4F","A","X-RAY DIFFRACTION","2.00","141"
"1C7C","A","X-RAY DIFFRACTION","1.80","283"
"1CG5","A","X-RAY DIFFRACTION","1.60","141"
"1FAW","A","X-RAY DIFFRACTION","3.09","141"
"1HDA","A","X-RAY DIFFRACTION","2.20","141"
"1IRD","A","X-RAY DIFFRACTION","1.25","141"
"1KFR","A","X-RAY DIFFRACTION","1.85","147"
"1QPW","A","X-RAY DIFFRACTION","1.80","141"
"1SPG","A","X-RAY DIFFRACTION","1.95","144"
"1UX8","A","X-RAY DIFFRACTION","2.15","132"

 

PDBhaemoglobinSorted.csv :

PDB ID,Chain ID,Exp. Method,Resolution,Chain Length
"2W72" "A" "X-RAY DIFFRACTION" 1.07 141
"1IRD" "A" "X-RAY DIFFRACTION" 1.25 141
"2H8F" "A" "X-RAY DIFFRACTION" 1.3 143
"2WY4" "A" "X-RAY DIFFRACTION" 1.35 140
"2D5X" "A" "X-RAY DIFFRACTION" 1.45 141
"4ESA" "A" "X-RAY DIFFRACTION" 1.45 143
"3VRG" "A" "X-RAY DIFFRACTION" 1.5 141
"1CG5" "A" "X-RAY DIFFRACTION" 1.6 141
"4HBI" "A" "X-RAY DIFFRACTION" 1.6 146
"1QPW" "A" "X-RAY DIFFRACTION" 1.8 141





















以上是关于python读取文件csv,先按第4列排序,再按第5列的数值排序的主要内容,如果未能解决你的问题,请参考以下文章

Bash:按前 4 列对 csv 文件进行排序

python 在Numpy中按第n列排序数组

python 在Numpy中按第n列排序数组

如何读取 CSV 并生成 json/avro 文件,其中 pig 按第一列的值分组?

如何在scratch 用猫2 做游戏

Python对多列文件中的数字进行排序[重复]