python - 在python中保存cvs文件
问题描述
我无法将数据保存到 csv 文件中。我试图将这个基因中的氨基酸分成四组非极性(np)、极性(p)、阴性(neg)和阳性(pos)。我已经弄清楚如何计算所有单个氨基酸并将它们保存到 cvs 文件中,但无法弄清楚如何以与单个氨基酸相同的方式保存来自四组的数据。
这是保存到 csv 中的单个氨基酸的代码:
from Bio import Entrez, SeqIO
Entrez.email = ""
handle = Entrez.efetch(db="nucleotide", id="KT191142", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()
protein_seq = record.seq.translate()
print(protein_seq)
def count_aa(seq, csv_file):
aa_dict = {} # dictionary to store amino acid counts
for aa in seq:
if aa in aa_dict:
aa_dict[aa] += 1 # increment the count of an amino acid by 1
else:
aa_dict[aa] = 1 # set the count of an amino acid to 1
with open(csv_file, "w") as file:
aa_list=sorted(aa_dict.keys())
file.write("amino_acid,count\n")
for aa in aa_list:
line = str(aa) + ',' + str(aa_dict[aa]) + '\n'
file.write(line)
count_aa(protein_seq, "ebola_aa_count2.csv")`
我想将这个新代码保存到一个 csv 文件中,就像之前的代码一样,这里是新代码:
import re
handle = Entrez.efetch(db="nucleotide", id="KT191142", rettype="gb", retmode="text")
records = SeqIO.read(handle, "genbank")
handle.close()
protein_seq = records.seq.translate()
print(protein_seq)
np_count = 0
p_count = 0
neg_count = 0
pos_count = 0
for aa in protein_seq:
match_np = re.search(r"G|A|V|C|P|L|I|M|W|F", str(aa))
match_p = re.search(r"S|T|Y|N|Q", str(aa))
match_neg = re.search(r"D|E", str(aa))
match_pos = re.search(r"K|R|H", str(aa))
if match_np:
np_count += 1
if match_p:
p_count += 1
if match_neg:
neg_count += 1
if match_pos:
pos_count += 1
handle.close()
print(np_count, p_count, neg_count, pos_count)
提前感谢您的帮助!
解决方案
您绝对应该使用pandas来操作 csv 文件。
import pandas as pd
df = pd.DataFrame(columns = ['np_count', 'p_count', 'neg_count', 'pos_count'], data =[np_count, p_count, neg_count, pos_count])
df.to_csv('output.csv')
推荐阅读
- python - 在 Python 中更新 QuantLib
- blueprism - 元素属性-蓝色棱镜
- r - 如何获取数据关系并根据 R 中的这些关系将数据组合成组?
- node.js - Gulp-Notify 错误 - dest.on 不是函数
- javascript - 如何在 Google 表格中使用 importjson 修复“SyntaxError: Unexpected token: a”
- java - 为什么黄瓜不能创建以')'或'.'结尾的bdd句子的步骤定义?
- c# - 如何一键添加多条记录?
- linux - 用 SED 中的顺序 ID 替换数字
- eclipse - 使用 Java 11 在 Eclipse 中混合模块化和非模块化开发
- cuda - CUDA 中的 FLOP 效率