import pandas as pd from openpyxl import load_workbook # 读取Excel文件 df = pd.read_excel(output_file_paths, sheet_name=sheet_name) # 选择特定的列,筛选不为空的行 filtered_df = df[df['请求分类'].notnull()] # 创建列表保存接口名称和所在行数 interface_info = [] # 遍历筛选后的DataFrame,获取接口名称和行号 for index, row in filtered_df.iterrows(): interface_name = row['接口名称'] interface_rows = row['请求分类'] row_number = index + 2 # 行号从2开始(索引从0开始) interface_info.append((interface_name, row_number,interface_rows)) 优化这段代码 提升性能
时间: 2024-04-16 14:24:09 浏览: 20
要优化这段代码以提升性能,您可以尝试以下几个方面的改进:
1. 使用 `openpyxl` 库直接读取 Excel 文件,而不是先使用 `pandas` 库读取再转换为 DataFrame。这样可以减少数据转换的开销,提高读取速度。
```python
from openpyxl import load_workbook
# 读取Excel文件
workbook = load_workbook(output_file_paths)
sheet = workbook[sheet_name]
# 创建列表保存接口名称和所在行数
interface_info = []
# 遍历筛选后的sheet页,获取接口名称和行号
for index, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
interface_name = row[1] # 假设接口名称在第2列(索引为1)
interface_rows = row[0] # 假设请求分类在第1列(索引为0)
interface_info.append((interface_name, index, interface_rows))
```
2. 尽量使用向量化操作替代循环遍历。在上述代码中,筛选不为空的行可以使用向量化操作实现。
```python
import pandas as pd
# 读取Excel文件
df = pd.read_excel(output_file_paths, sheet_name=sheet_name)
# 筛选不为空的行
filtered_df = df[df['请求分类'].notnull()]
# 创建列表保存接口名称和所在行数
interface_info = list(zip(filtered_df['接口名称'], filtered_df.index + 2, filtered_df['请求分类']))
```
通过这些优化,您可以减少不必要的数据转换和循环遍历,从而提高性能。根据实际情况,您可以选择适合您需求的优化方式。
希望这些优化建议对您有所帮助。如果您还有其他问题,请随时提问。