基于python中的其他列选择一行

时间:2016-12-17 13:45:49

标签: python

我的csv文件的一小部分如下所示:

481116  ABCF3   466 0   ENSG00000161204 0
485921  ABCF3   466 0   ENSG00000161204 0
489719  ABCF3   466 0   ENSG00000161204 0
498136  ABCF3   466 2   ENSG00000161204 0.0019723866
273359  ABHD10  326 78  ENSG00000144827 0.0301158301
491580  ABHD10  326 0   ENSG00000144827 0
493784  ABHD10  326 0   ENSG00000144827 0
494817  ABHD10  326 1   ENSG00000144827 0.0012484395

文件中的列由","分隔。在第二列中有许多重复的id,我想根据第6列中的值仅选择一个id。换句话说,对于每个id,我想选择第6列中编号最大的id。 上述部分的结果必须是这样的。

498136  ABCF3   466 2   ENSG00000161204 0.0019723866
273359  ABHD10  326 78  ENSG00000144827 0.0301158301

我试图在python中创建它并在以下框架中编写了一些代码,但它们没有工作:

with open('data.csv') as f, open('out.txt', 'w') as out:
    line = [line.split(',')for line in f]
    .
    .
    out.write(','.join(results))

1 个答案:

答案 0 :(得分:1)

you_data.csv:

481116,ABCF3, 466,0, ENSG00000161204,0
485921,ABCF3, 466,0, ENSG00000161204,0
489719,ABCF3, 466,0, ENSG00000161204,0
498136,ABCF3, 466,2, ENSG00000161204,0.0019723866
273359,ABHD10,326,78,ENSG00000144827,0.0301158301
491580,ABHD10,326,0, ENSG00000144827,0
493784,ABHD10,326,0, ENSG00000144827,0
494817,ABHD10,326,1, ENSG00000144827,0.0012484395  

代码:

import csv
from collections import defaultdict

with open('you_data.csv', newline='') as f, open('out.csv', 'w', newline='') as out:
    f_reader = csv.reader(f)
    out_writer = csv.writer(out)
    d = defaultdict(list)
    for line in f_reader:
        d[line[1]].append(line)
    for _,v in d.items():
        new_line = sorted(v, key=lambda i:float(i[5]), reverse=True)[0]
        out_writer.writerow(new_line)

out.csv:

498136,ABCF3, 466,2, ENSG00000161204,0.0019723866
273359,ABHD10,326,78,ENSG00000144827,0.0301158301