[英]How to iterate through an excel sheet based on whether the cell value contains a certain character
I am trying to write a script that will delete rows based on whether or not the row's corresponding cell value in the first column contains a specific character, in this case a '#'.我正在尝试编写一个脚本,该脚本将根据第一列中行的相应单元格值是否包含特定字符(在本例中为“#”)来删除行。
I have tried writing the following function that would hopefully iterate through the sheet and return a new sheet with the deleted rows.我已经尝试编写以下 function ,它有望遍历工作表并返回包含已删除行的新工作表。 LabSample is the sheet that I am working in.
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)
I currently am not getting any error messages, but the output I am getting is unchanged from the input.我目前没有收到任何错误消息,但我收到的 output 与输入相比没有变化。 It appears that no rows have been deleted.
似乎没有删除任何行。
Try casting sys_sample_code as a str()尝试将 sys_sample_code 转换为 str()
#...
sys_sample_code = LabSample.cell(row=rowNum, column=1).value
if '#' not in str(sys_sample_code): # SEE EDIT HERE
# ...
I'd probably do this through importing the table in numpy and then index the rows which contain the '#', and finally use np.delete to remove the rows before pushing it back to where it came.我可能会通过在 numpy 中导入表然后索引包含“#”的行,最后使用 np.delete 删除行,然后再将其推回原处。
Here's a short example which kinda demonstrates what I'm talking about.这是一个简短的示例,可以说明我在说什么。 just replace the starting array 'x' with your data array and analyze along the column you're interested in.
只需将起始数组“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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.