Skip to main content
 首页 » 编程设计

python之将一行拆分为多个单元格,并为每个基因保留第二个值的最大值

2025年02月15日8softidea

我是 Python 新手,我准备了一个脚本来修改以下 csv file

因此:

1) 每行包含多个由 /// 分隔的 Gene 条目,例如:

C16orf52 /// LOC102725138 1.00551 

应该转化为:

C16orf52 1.00551   
LOC102725138 1.00551 

2)同一个基因可能有不同的比值

AASDHPPT 0.860705   
AASDHPPT 0.983691   

我们只想保留具有最高比率值的对(删除对 AASDHPPT 0.860705)

这是我写的脚本,但它没有为基因分配正确的比率值:

import csv 
import pandas as pd 
 
with open('2column.csv','rb') as f: 
    reader = csv.reader(f) 
    a = list(reader) 
gene = [] 
ratio = [] 
for t in range(len(a)): 
    if '///' in a[t][0]: 
        s = a[t][0].split('///') 
        gene.append(s[0]) 
        gene.append(s[1]) 
        ratio.append(a[t][1]) 
        ratio.append(a[t][1]) 
    else: 
        gene.append(a[t][0]) 
        ratio.append(a[t][1]) 
    gene[t] = gene[t].strip() 
 
newgene = [] 
newratio = [] 
for i in range(len(gene)): 
    g = gene[i] 
    r = ratio[i] 
    if g not in newgene: 
        newgene.append(g) 
    for j in range(i+1,len(gene)): 
        if g==gene[j]: 
            if ratio[j]>r: 
                r = ratio[j] 
    newratio.append(r) 
 
for i in range(len(newgene)): 
    print newgene[i] + '\t' + newratio[i] 
 
if len(newgene) > len(set(newgene)): 
    print 'missionfailed'    

非常感谢您的任何帮助或建议。

请您参考如下方法:

试试这个:

with open('2column.csv') as f: 
    lines = f.read().splitlines() 
 
new_lines = {} 
for line in lines: 
    cols = line.split(',') 
    for part in cols[0].split('///'): 
        part = part.strip() 
        if not part in new_lines: 
            new_lines[part] = cols[1] 
        else: 
            if float(cols[1]) > float(new_lines[part]): 
                new_lines[part] = cols[1] 
 
 
import csv 
with open('clean_2column.csv', 'wb') as csvfile: 
    writer = csv.writer(csvfile, delimiter=' ', 
                            quotechar='|', quoting=csv.QUOTE_MINIMAL) 
    for k, v in new_lines.items(): 
        writer.writerow([k, v])