python - 使用枚举在python中打印上一行
问题描述
我有一个以下格式的文件。
OperonID GI Synonym Start End Strand Length COG_number Product
1132034 397671780 RVBD_0002 2052 3260 + 402 - DNA polymerase III subunit beta
1132034 397671781 RVBD_0003 3280 4437 + 385 - DNA replication and repair protein RecF
1132034 397671782 RVBD_0004 4434 4997 + 187 - hypothetical protein
1132035 397671783 RVBD_0005 5123 7267 + 714 - DNA gyrase subunit B
1132035 397671784 RVBD_0006 7302 9818 + 838 - DNA gyrase subunit A
1132036 397671786 RVBD_0007Ac 11421 11528 - 35 - hypothetical protein
1132036 397671787 RVBD_0007Bc 11555 11692 - 45 - hypothetical protein
1132037 397671792 RVBD_0012 14089 14877 + 262 - hypothetical protein
- 我需要每个 Operon ID 的开始和结束坐标以及它自己的文件/字符串中的链。例如,对于操作子 1132034,起始坐标为 2052,结束坐标为 4997,链为 -。
我知道到目前为止我可能可以使用 enumerate 并拥有以下脚本。
lines = open('operonmap.opr', 'r').read().splitlines()
operon_id = 1132034
start = ''
end = ''
strand = ''
for i,line in enumerate(lines):
if str(operon_id) in line:
start += line[28:33]
else:
end += line[i-1]
operonline += start
operonline += end
operonline += '\n'
然后,如果这种脚本有效,我将编辑字符串“operonline”以仅包含起始端和链信息。不幸的是它不起作用,但我希望你能看到我的逻辑。
我希望有人能够提供帮助!
解决方案
如果你使用熊猫,这很容易,如果你想走那条路..
我能够将您的数据读入pandas DataFrame
然后删除其他列:
Start End Strand OperonID
0 2052 3260 + 1132034
1 3280 4437 + 1132034
2 4434 4997 + 1132034
3 5123 7267 + 1132035
4 7302 9818 + 1132035
5 11421 11528 - 1132036
6 11555 11692 - 1132036
7 14089 14877 + 1132037
然后我将and和value分组OperonID
并存储为列表,并创建了一个新列,其中包含第一个和最后一个per以及唯一值..您可以以任何您认为合适的方式重新组织它Start
End
Strand
Start
End
OperonID
Strand
df2 = df.groupby('OperonID')[['Start', 'End', 'Strand']].agg(list)
df2['result'] = df2.apply(lambda x: (x['Start'][0], x['End'][-1], set(x['Strand'])), axis=1)
df2['result']:
OperonID
1132034 (2052, 4997, {+})
1132035 (5123, 9818, {+})
1132036 (11421, 11692, {-})
1132037 (14089, 14877, {+})
推荐阅读
- graphql - React Apollo 中本地解析器的执行顺序是什么?
- html - 如何在 Font Awesome 5 中水平对齐分层图标?
- c++ - 删除动态内存是如何真正起作用的?
- php - 从 PHP 使用 sqlsrv 时登录失败
- php - Laravel:如何使用 Eloquent 获取关系列的总和
- linux - 根据 bash 中给出的键进行排序
- android - Firebase动态链接同步?
- sql-server - 如何将格式为 MM-DD-YYYY 的日期更改为在 SSIS 中的 MM 和 DD 中没有前导零?
- nginx - 通过 nginx 提供静态文件时如何修复 404 错误
- c# - 为什么 DbContext.Attach 将实体状态设置为 EntityState.Modified?