pandas apply传递参数进阶 不好用,不是我想的那回事

代码对比

原代码

 总表 = pd.DataFrame(columns = ['部门名称','接口个数','表名','链接'])
 # 遍历每个部门,获取相关的API详情
 for department_title in departments_info['部门名称'].to_list():
     部门表 = departments_info[departments_info['部门名称'] == department_title ].copy()
     print(department_title)  # 打印部门名称
     # 获取每个部门的API详情
     api_details = get_api_details(department_title)
     # print(f"部门API详情{api_details}")
     if not api_details.empty:
         # 如果找到了API详情,则进行合并
         部门表 = 部门表.merge(api_details, on='部门名称', how='left')
     else:
         print(f"没有找到部门 {department_title} 的API详情。")
     总表 = pd.concat( [总表,部门表],axis=0)
# 总表.to_csv('test.csv',index=False)
# 添加表信息的总表 = pd.DataFrame( columns = ['部门名称','接口个数','表名','链接','字段序号','字段英文描述','字段中文描述'])
# 然后对每个API的链接进行遍历,抓取每个API的字段信息
 for url in 总表['链接'].to_list():
     单个url表 = 总表[总表['链接'] == url ].copy()
     # 确保URL是有效的
     if isinstance(url, str) and url.startswith("http"):
         # 获取信息项内容
         information_items = get_information_items(url)
         if not information_items.empty:
             # 如果找到了信息项,进行合并
             单个url表 = 单个url表.merge(information_items, on=['链接'], how='left')
     添加表信息的总表 = pd.concat([添加表信息的总表,单个url表],axis=0)

# 清理和退出浏览器驱动
driver.quit()
writer = pd.ExcelWriter('20240324.xlsx')
添加表信息的总表.to_excel(writer,index=False)
writer.save()

升级后代码

# 定义一个函数,它接受DataFrame中的一行作为输入
# 这个函数的目的是,基于该行中某个特定的列(在这个例子中是'部门名称'),
# 来获取相关的API详情,并将这些详情作为新的列值返回
def enrich_department_info(row):
    # 调用get_api_details函数,传入'部门名称'列的值,
    # 以获取该部门的API详细信息。这假设get_api_details函数返回一个字典,
    # 其中包含关于API的各种信息,如接口个数、表名和链接
    api_details = get_api_details(row['部门名称'])
    
    # 从api_details字典中提取'接口个数'、'表名'和'链接'的值,
    # 并将这些值封装成一个pandas Series对象返回。
    # 如果字典中没有这些键,则相应的值将被设置为None。
    return pd.Series({
        '接口个数': api_details.get('接口个数', None),
        '表名': api_details.get('表名', None),
        '链接': api_details.get('链接', None),
    })

# 调用.apply()方法,并传入enrich_department_info函数作为参数,
# 指定axis=1使其按行应用该函数。
# 这将对departments_info DataFrame的每一行调用enrich_department_info函数,
# 并将返回的Series对象中的值分别填充到'接口个数'、'表名'和'链接'这三个新列中。
# 结果是,departments_info DataFrame将被扩展,包含了这三个新列,
# 其中填充了根据每行中'部门名称'列的值获取的API详细信息。
departments_info[['接口个数', '表名', '链接']] = departments_info.apply(enrich_department_info, axis=1)

def fetch_information_items(url):
    # 此函数根据给定的URL获取信息项内容
    if pd.notna(url) and url.startswith("http"):
        information_items = get_information_items(url)
        return information_items
    return pd.DataFrame()  # 返回一个空的DataFrame,如果没有找到信息

# 使用merge而不是concat来组合信息,以减少不必要的数据复制
departments_info['信息项内容'] = departments_info['链接'].apply(fetch_information_items)
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值