使用CSV Python将处理过的数据写入excel

我正在尝试使用CSV将一些数据写入Excel电子表格。 我正在写一个graphics取景器,读取来自fasta的input和输出到excel。 但是我很难用正确的格式写数据。

我在Excel中的预期结果如下所示。

SeqName M1 Hits M2 Hits Seq1 MN[AZ] 3 V[AZ]R[ML] 2 Seq2 MN[AZ] 0 V[AZ]R[ML] 5 Seq3 MN[AZ] 1 V[AZ]R[ML] 0 

我已经产生了正确的结果,但我不知道如何把它们放在正确的格式,如上所述。

这是迄今为止的代码。

 import re from Bio import SeqIO import csv import collections def SearchMotif(f1, motif, f2="motifs.xls"): with open(f1, 'r') as fin, open(f2,'wb') as fout: # This makes SeqName static and everything else mutable thus, when more than 1 motifs are searched, # they can be correctly placed into excel. writer = csv.writer(fout, delimiter = '\t') motif_fieldnames = ['SeqName'] writer_dict = csv.DictWriter(fout,delimiter = '\t' ,fieldnames=motif_fieldnames) for i in range(0,len(motif),1): motif_fieldnames.append('M%d' %(i+1)) motif_fieldnames.append('Hits') writer_dict.writeheader() # Reading input fasta file for processing. fasta_name = [] for seq_record in SeqIO.parse(f1,'fasta'): sequence = repr(seq_record.seq) # re-module only takes string fasta_name.append(seq_record.name) print sequence ********** for j in motif: motif_name = j print motif_name ********** number_count = len(re.findall(j,sequence)) print number_count ********** writer.writerow([motif_name]) for i in fasta_name: writer.writerow([i]) # [] makes it fit into one column instead of characters taking each columns 

具有星号的打印语句**********生成这个…其中number是Hits的数量和差别序列是seq1,seq2 …等等。

 Seq('QIKDLLVSSSTDLDTTLVLVNAIYFKGMWKTAFNAEDTREMPFHVTKQESKPVQ...LTS', SingleLetterAlphabet()) PA[AZ] 0 Y[AZ]L[AZ] 0 Seq('SFNVATLPAESSSTDLDTTVLLPDEPAEVSDLERIETEWTNMKILELPFAPQMK...VSS', SingleLetterAlphabet()) PA[AZ] 2 Y[AZ]L[AZ] 0 Seq('PAESIYFKIEKTYNLT', SingleLetterAlphabet()) PA[AZ] 1 Y[AZ]L[AZ] 1 

您可以将数据写入Pandas DataFrame,然后使用DataFrame的to_csv方法将其导出为CSV。 还有一个to_excel方法。 pandas不会让你有多个同名的列,就像你的“点击”列。 但是,您可以通过在第一行中放置所需列名称并在导出时使用header = False选项来解决此问题。

“将pandas导入为pd”,然后用“fasta_name = []”replace你的代码:

 column_names = ['SeqName'] for i, m in enumerate(motif): column_names += ['M'+str(i), 'Hits'+str(i)] df = pd.DataFrame(columns=column_names) for row, seq_record in enumerate(SeqIO.parse(f1, 'fasta')): sequence = repr(seq_record.name) df.loc[row, 'SeqName'] = sequence for i, j in enumerate(motif): df.loc[row, 'M'+str(i)] = j df.loc[row, 'Hits'+str(i)] = len(re.findall(j, sequence)) df.to_csv(index=False)