

查询请单和返回结果均是dataframe, 指定查询产品是一个Series数据。
关注🕖上午好,题主!目前:🟢[在线]
📢参考通义千问、由郭老师整理提供!
📣今日诗号:曾经沧海难为水,除却巫山不是云。
import pandas as pd
def bom_explosion(bom_df, parts_to_explode):
"""
在多层 BOM 中查询指定产品,返回爆炸后的物料清单。
Args:
bom_df (pd.DataFrame): 包含物料清单的 DataFrame,列名为 '父物料' 和 '子物料'。
parts_to_explode (pd.Series): 要查询的物料清单。
Returns:
pd.DataFrame: 爆炸后的物料清单,包含 '父物料', '子物料', '层级' 三列。
"""
bom_df['层级'] = 1 # 初始化所有物料的层级为 1
result_df = pd.DataFrame(columns=['父物料', '子物料', '层级'])
for part in parts_to_explode:
current_level = 1
temp_df = bom_df[bom_df['父物料'] == part].copy()
result_df = pd.concat([result_df, temp_df], ignore_index=True)
while not temp_df.empty:
current_level += 1
children = temp_df['子物料'].tolist()
temp_df = bom_df[bom_df['父物料'].isin(children)].copy()
temp_df['层级'] = current_level
result_df = pd.concat([result_df, temp_df], ignore_index=True)
return result_df
# 示例数据
bom_data = {
'父物料': ['A', 'A1', 'A11', 'A1', 'A', 'A2', 'B', 'B1'],
'子物料': ['A1', 'A11', 'A111', 'A12', 'A2', 'A22', 'B1', 'B11']
}
bom_df = pd.DataFrame(bom_data)
# 指定查询产品
parts_to_explode = pd.Series(['A', 'B'])
# 执行查询
result_df = bom_explosion(bom_df, parts_to_explode)
# 打印结果
print(result_df)
代码说明:
bom_explosion(bom_df, parts_to_explode) 函数:
bom_df 和要查询的物料清单 parts_to_explode 作为参数。result_df 用于存储结果,并为所有物料添加初始层级 1。parts_to_explode 中的每个物料:
temp_df。while 循环逐层查找子物料,并将结果添加到 result_df 中:
current_level 跟踪当前层级。temp_df 中获取子物料列表。bom_df 中查找以这些子物料作为父物料的记录,更新 temp_df。temp_df 中物料的层级。result_df。示例数据:
bom_df。parts_to_explode。执行查询并打印结果:
bom_explosion 函数执行查询,并将结果存储在 result_df 中。result_df,显示爆炸后的物料清单。这段代码实现了在多层 BOM 中查询指定产品并返回爆炸后的物料清单的功能。它使用了 DataFrame 和 Series 数据结构,并通过循环和条件判断实现了 BOM 的层级遍历和数据提取。