You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将OpenPyXL实现的餐厅数据获取代码转换为Pandas?

OpenPyXL转Pandas餐厅数据获取代码方案

调研显示Pandas性能优于OpenPyXL,现将基于OpenPyXL的餐厅数据获取逻辑转换为Pandas实现,具体方案如下:

原OpenPyXL代码

def get_restaurant_data(self, res: Restaurant, sf_id: int) -> RestaurantSchema:
    sheet = self.workbook["VendorInfo"]
    for row in sheet.iter_rows(min_row=2):
        if row[0].value == sf_id:
            res.address = self.check_data(row[1].value, res.address)
            if self.check_data(row[2].value) and self.check_data(row[3].value):
                res.loc = Point(row[3].value, row[2].value)
            res.phone = self.check_data(row[4].value, res.manager_phone)

            logo = self.download_file(row[5].value)
            cover = self.download_file(row[6].value)
            if logo:
                res.logo.save(self.check_data(row[5].value), logo, save=False)
            if cover:
                res.cover.save(self.check_data(row[6].value), cover, save=False)
            return RestaurantSchema(**res.__dict__)

已编写的Pandas初始代码片段

df = pd.read_excel(self.path,index_col=None)
print(f'>>> {df}')

转换后的完整Pandas实现代码

def get_restaurant_data(self, res: Restaurant, sf_id: int) -> RestaurantSchema:
    # 读取指定工作表,第一行为表头(对应原代码从第2行开始遍历数据)
    df = pd.read_excel(self.path, sheet_name="VendorInfo", header=0)
    
    # 筛选匹配sf_id的行,替代原代码循环查找逻辑
    target_rows = df[df.iloc[:, 0] == sf_id]
    
    # 无匹配行时返回原res实例(可根据业务需求调整为抛出异常)
    if target_rows.empty:
        return RestaurantSchema(**res.__dict__)
    
    # 提取第一组匹配数据(若存在重复sf_id,需根据业务规则处理)
    row_data = target_rows.iloc[0]
    
    # 处理地址字段
    res.address = self.check_data(row_data.iloc[1], res.address)
    
    # 处理坐标字段
    if self.check_data(row_data.iloc[2]) and self.check_data(row_data.iloc[3]):
        res.loc = Point(row_data.iloc[3], row_data.iloc[2])
    
    # 处理电话字段
    res.phone = self.check_data(row_data.iloc[4], res.manager_phone)
    
    # 处理logo下载与保存
    logo_url = row_data.iloc[5]
    logo = self.download_file(logo_url)
    if logo:
        res.logo.save(self.check_data(logo_url), logo, save=False)
    
    # 处理cover下载与保存
    cover_url = row_data.iloc[6]
    cover = self.download_file(cover_url)
    if cover:
        res.cover.save(self.check_data(cover_url), cover, save=False)
    
    return RestaurantSchema(**res.__dict__)

关键逻辑说明

  • 用pd.read_excel直接读取指定工作表,通过header=0明确表头行,对应原代码从第2行开始遍历数据的逻辑
  • 通过布尔索引快速定位匹配sf_id的行,替代原代码逐行循环,大幅提升大数据量下的性能
  • 用iloc按位置提取列数据,完全对应原代码中row[n].value的字段定位逻辑
  • 保留原代码中所有自定义方法(check_data、download_file、save)的调用逻辑,确保业务行为一致
  • 增加空行判断,避免无匹配数据时出现索引错误,可根据实际业务调整异常处理规则

内容的提问来源于stack exchange,提问作者mehdi aria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:50:29