如何根据单元格值是否包含某个字符来遍历excel工作表



我正在尝试编写一个脚本,该脚本将根据第一列中行的相应单元格值是否包含特定字符(在本例中为"#"(来删除行。

我尝试编写以下函数,希望它能遍历工作表,并返回一个包含已删除行的新工作表。LabSample是我正在处理的表格。

def remove_headers():
for rowNum in range(2, LabSample.max_row):
sys_sample_code = LabSample.cell(row=rowNum, column=1).value
if '#' not in sys_sample_code:
continue
else:
LabSample.delete_rows(rowNum, 1)
return LabSample
for row in LabSample.rows:
print(row[0].value)

我目前没有收到任何错误消息,但我收到的输出与输入没有变化。似乎没有删除任何行。

尝试将sys_sample_code转换为str((

#...
sys_sample_code = LabSample.cell(row=rowNum, column=1).value
if '#' not in str(sys_sample_code): # SEE EDIT HERE
# ...

我可能会通过在numpy中导入表,然后对包含"#"的行进行索引,最后使用np.delete删除行,然后将其推回到原来的位置。

这里有一个简短的例子,可以说明我在说什么。只需将起始数组"x"替换为数据数组,并沿着您感兴趣的列进行分析。

import numpy as np
x = np.array(
[1,2,5,'a','#test1', 'b', 7, '#test2', 9]
)
index = {count: pos for count, pos in enumerate(x) if '#' in pos[:]}
x = np.delete(x, list(index.keys()))

In [17]: x
Out[17]: array(['1', '2', '5', 'a', 'b', '7', '9'], dtype='<U11')

最新更新