python - 如何在我的代码中使用具有特定值的第一个单元格
问题描述
使用我的 Python 代码,我正在寻找具有特定表名的单元格,在本例中为“质量分布”。在 Excel 文件中有两个具有此名称的表,我只想使用第一个表。
如果只有一个具有特定表名的单元格,我的代码可以正常工作,但现在我的代码正在查找具有“质量分布”的第一个单元格,然后寻找第二个单元格并在第二个表处开始索引。如何调整我的代码以便使用第一个表?
我的 Excel 文件包含 A 列和 B 列中的 12 个表,每个表有 67 到 350 行。在表格上方标明了表格名称。
一个例子(我删除了一些表和行,因为工作表有 2000 行):
摘要
创建日期:Fri Aug 02 13:49:15 CEST 2019
生成者:XXXX
软件:CLC Genomics Workbench 12.0
基于:1 个数据集
XXXXXXX_S7_L001_R1_001(配对):5.102.482 个成对
序列 数据集中的总序列 5.102.482 个序列
数据集中的总核苷酸 558.462.117 个核苷酸
质量分布
平均 PHRED 分数 % 序列:
0 0
1 0
27 0.889841454
28 1.157475911
29 1.472773446
按碱基分析
覆盖率
碱基位置 % 覆盖率:
0 100
1 100
2 100
147 37.30090572
148 36.1365508
149 33.95743483
150 24.3650639
151 0
质量分
布基位置 PHRED 得分:5%ile PHRED 得分:25%ile PHRED 得分:中值 PHRED 得分:75%ile PHRED 得分:95%ile 0 0 0 0 0 0 1 18 32 32 33 34 2 18 32 33 33 34 3 18 32 33 34 34 146 15 37 38 39 39 147 15 37 38 39 39 148 15 37 38 39 39 149 15 37 38 39 39 150 15 36 38 39 39 151 39 33 37 3
#!/usr/bin/python3
import xlrd
kit = ('test_QC_150.xlsx')
wb = xlrd.open_workbook(kit)
sheet = wb.sheet_by_index(0)
def phred_score():
for sheet in wb.sheets():
for rowidx in range(sheet.nrows):
row = sheet.row(rowidx)
for colidx, cell in enumerate(row):
# searching for the quality distribution
if cell.value == "Quality distribution":
index_quality_distribution = rowidx
print('index_quality_distribution: ', index_quality_distribution)
index = index_quality_distribution + 35
index_end = index_quality_distribution + 67
print(index)
print(index_end)
def main():
phred_score()
if __name__ == '__main__':
main()
解决方案
我认为答案很简单。您的代码没有“错误”,只是您还没有考虑到最后:
您的 for 循环遍历您指定范围内的所有单元格,而您之前只有一个单元格验证了以下 if 语句:
for colidx, cell in enumerate(row):
# searching for the quality distribution
if cell.value == "Quality distribution":
index_quality_distribution = rowidx
现在有两个实例,它会找到两个,但是由于您正在覆盖“index_quality_distribution”变量,所以只有它找到的最后一个会被保存在“内存中”。您可以做的是将所有内容包装在一个 while 循环中,并在第一次找到索引时将其中断:
while True:
for sheet in wb.sheets():
for rowidx in range(sheet.nrows):
row = sheet.row(rowidx)
for colidx, cell in enumerate(row):
# searching for the quality distribution
if cell.value == "Quality distribution":
index_quality_distribution = rowidx
print('index_quality_distribution: ', index_quality_distribution)
break #Exits the while-loop and stop iterating
break #failsafe in case no "Quality distribution is found
那应该这样做。
推荐阅读
- c - 我不理解的 strtok() 行为
- jsf - JSF从没有显示的bean中设置inputText值
- kubernetes - Prometheus Alertmanager 是否能够区分事件和条件?
- java - 如何在android studio中从给定的mp3文件中获取音频数据
- android - Android Studio 中 Intentservice/coroutine/workmanager 中的后台数据更新
- r - 在ggplot中绘制多条线的功能
- akka - akka actor 可以在不同的情况下回复消息吗
- sql - 仅在最高组上的 Sql 查询 max/min
- flutter - 发现奇怪的错误:GetX+Provider 相处得不太好
- python-3.x - 如何将 pandas DataFrame 作为 CSV 文件传递到 Django View 的上下文中?