2014-12-04 5 views
1

두 개의 탭으로 구분 된 파일 .txt를 읽고 하나의 공통 컬럼으로 함께 매핑하는 방법. ,두 개의 txt 파일을 하나의 공통 컬럼 python으로 병합하십시오.

첫 번째 파일, pathway.txt

Pathway            Protein 
Binding and Uptake of Ligands by Scavenger Receptors P69905           
Erythrocytes take up carbon dioxide and release oxygen P69905           
Metabolism            P69905 
Amyloids            P02647 
Metabolism            P02647 
Hemostasis            P68871 

두 번째 파일

Gene Protein 
Fabp3 P11404 
HBA1 P69905 
APOA1 P02647 
Hbb-b1 P02088 
HBB P68871 
Hba P01942 

출력을 gene.txt :이 두 파일에서 예를 들어

는 경로에 유전자의 매핑을 만들 같을 것이다.

Gene Protein  Pathway 
Fabp3 P11404  
HBA1 P69905  Binding and Uptake of Ligands by Scavenger Receptors, Erythrocytes take up carbon dioxide and release oxygen, Metabolism 
APOA1 P02647  Amyloids, Metabolism 
Hbb-b1 P02088 
HBB P68871  Hemostasis 
Hba P01942 

경로가없는 경우 단백질 ID 정보의 유전자 기반에 해당하는 비워 둡니다.

UPDATE :

import pandas as pd 

file1= pd.read_csv("gene.csv") 
file2= pd.read_csv("pathway.csv") 

output = pd.concat([file1,file2]).fillna(" ") 
output= output[["Gene","Protein"]+list(output.columns[1:-1])] 
output.to_csv("mapping of gene to pathway.csv", index=False) 

그래서 이것은 단지 나에게 내가 예상되지 않는다 병합 된 파일을 제공합니다. `리간드의 통풍 관은 ......... 출처에서

+1

??? – Hackaholic

+0

@Hackaholic은 오타를 수정했습니다. – abs27

+1

@ abs27 몇 가지 코드를 작성하십시오. 오류가 발생하면 도움을 드릴 것입니다. –

답변

0
>>> from collections import defaultdict 
>>> my_dict = defaultdict() 
>>> f = open('pathway.txt') 
>>> for x in f: 
...  x = x.strip().split() 
...  value,key = " ".join(x[:-1]),x[-1] 
...  if my_dict.get(key,0)==0: 
...   my_dict[key] = [value] 
...  else:my_dict[key].append(value) 
... 
>>> my_dict 
defaultdict(None, {'P68871': ['Hemostasis'], 'Protein': ['Pathway'], 'P69905': ['Binding', 'Erythrocytes', 'Metabolism'], 'P02647': ['Amyloids', 'Metabolism']}) 
>>> f1 = open('gene.txt') 
>>> for x in f1: 
...  value,key = x.strip().split() 
...  if my_dict.get(key,0)==0: 
...   print("{:<15}{:<15}".format(value,key)) 
...  else: print("{:<15}{:<15}{}".format(value,key,", ".join(my_dict[key]))) 
... 
Gene   Protein  Pathway 
Fabp3   P11404   
HBA1   P69905   Binding and Uptake of Ligands by Scavenger Receptors, Erythrocytes take up carbon dioxide and release oxygen Metabolism 
APOA1   P02647   Amyloids, Metabolism 
Hbb-b1   P02088   
HBB   P68871   Hemostasis 
Hba   P01942   
0
class Protein: 

    def __init__(self, protein, pathway = None, gene = ""): 
     self.protein = protein 
     self.pathways = [] 
     self.gene = gene 

     if pathway is not None: 
      self.pathways.append(pathway) 
     return 

    def __str__(self): 
     return "%s\t%s\t%s" % (
      self.gene, 
      self.protein, 
      ", ".join([p for p in self.pathways]))  

# protein -> pathway map 
proteins = {} 

# get the pathways 
f1 = file("pathways.txt") 
for line in f1.readlines()[1:]: 
    tokens = line.split() 
    pathway = " ".join(tokens[:-1]) 
    protein = tokens[-1] 

    if protein in proteins: 
     p = proteins[protein] 
     p.pathways.append(pathway) 
    else: 
     p = Protein(protein = protein, pathway = pathway) 
     proteins[protein] = p 

# get the genes 
f2 = file("genes.txt") 
for line in f2.readlines()[1:]: 
    gene, protein = line.split() 

    if protein in proteins: 
     p = proteins[protein]  
     p.gene = gene 
    else: 
     p = Protein(protein = protein, gene = gene) 
     proteins[protein] = p 

# print the results 
print "Gene\tProtein\tPathway" 
for protein in proteins.values(): 
    print protein 
+0

감사합니다! 이것은 도움이됩니다. – abs27

관련 문제