本文主要是介绍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_itemsreturn pd.DataFrame() # 返回一个空的DataFrame,如果没有找到信息# 使用merge而不是concat来组合信息,以减少不必要的数据复制
departments_info['信息项内容'] = departments_info['链接'].apply(fetch_information_items)
这篇关于pandas apply传递参数进阶 不好用,不是我想的那回事的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!