Python中监控变量变化,实时计算商品及品类总价并优化
解决方案
一、关联商品与品类(预处理)
先确保你的库存DataFrame(命名为inventory_df)包含product_id(商品ID/名称)、category(品类)、stock(库存)字段;价格流DataFrame(命名为price_stream_df)包含product_id、current_price(当前价格)字段。
通过merge将两个表关联,让价格流中的每个商品直接匹配到所属品类和库存数据:
# 关联两个DataFrame,保留价格流所有商品 merged_df = price_stream_df.merge(inventory_df, on='product_id', how='left')
用how='left'是为了避免遗漏价格流中可能存在的、库存表未记录的商品(这类商品可后续跳过或标记)。
二、基础实现:遍历计算单个与品类总价
用字典实时维护品类总价,同时记录每个商品的上一次价格,避免重复计算:
# 初始化品类总价字典,所有品类初始值为0 category_total = {cat: 0 for cat in inventory_df['category'].unique()} # 初始化商品上一次价格字典,初始值为0 last_price = {prod: 0 for prod in inventory_df['product_id'].unique()} # 遍历价格流的每一行(按更新顺序) for idx, row in merged_df.iterrows(): product_id = row['product_id'] category = row['category'] stock = row['stock'] current_price = row['current_price'] # 计算单个商品总价并输出 product_total = stock * current_price print(f"商品 {product_id} 总价: {product_total:.2f}") # 计算价格变化带来的品类总价调整量 price_diff = current_price - last_price[product_id] category_total[category] += stock * price_diff # 更新该商品的上一次价格记录 last_price[product_id] = current_price # 输出当前品类总价 print(f"品类 {category} 当前总价: {category_total[category]:.2f}")
三、优化思路:用价格变化量更新品类总价
核心逻辑是避免每次重新计算整个品类的所有商品总价:
- 预先记录每个商品的上一次价格,当价格更新时,计算
库存×(新价格-旧价格)的差值 - 直接将差值加到对应品类的总价中,每次操作仅需O(1)时间,远快于重新遍历品类求和的O(n)操作
四、实时流场景优化
如果价格流是持续实时流入(比如从消息队列/API逐行获取),可将初始化逻辑放在循环外,同时把库存表转成字典提升查询效率:
# 仅初始化一次 category_total = {cat: 0 for cat in inventory_df['category'].unique()} last_price = {prod: 0 for prod in inventory_df['product_id'].unique()} # 提前构建商品-品类/库存映射字典,加速查询 product_info = inventory_df.set_index('product_id')[['category', 'stock']].to_dict('index') # 模拟实时价格流处理 for new_price_row in real_time_price_stream(): product_id = new_price_row['product_id'] current_price = new_price_row['current_price'] # 跳过无库存记录的商品 if product_id not in product_info: print(f"商品 {product_id} 无库存记录,跳过") continue category = product_info[product_id]['category'] stock = product_info[product_id]['stock'] # 计算并输出单个商品总价 product_total = stock * current_price print(f"商品 {product_id} 总价: {product_total:.2f}") # 更新品类总价 price_diff = current_price - last_price[product_id] category_total[category] += stock * price_diff last_price[product_id] = current_price print(f"品类 {category} 当前总价: {category_total[category]:.2f}")
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

