首页 > 解决方案 > Use DataFrame to add values until certain amount, then store the remainder in a list

问题描述

I'm creating an inventory management system in python.

The goal is to make sure any given order weighs less than 1800g. If it's heavier than 1800g, split the order into multiple shipments.

So far I have:

import pandas as pd

product_info = [{"mass_g": 700, "product_name": "RBC A+ Adult", "product_id": 0}, {"mass_g": 700, "product_name": "RBC B+ Adult", "product_id": 1}, {"mass_g": 750, "product_name": "RBC AB+ Adult", "product_id": 2}, {"mass_g": 680, "product_name": "RBC O- Adult", "product_id": 3}, {"mass_g": 350, "product_name": "RBC A+ Child", "product_id": 4}, {"mass_g": 200, "product_name": "RBC AB+ Child", "product_id": 5}, {"mass_g": 120, "product_name": "PLT AB+", "product_id": 6}, {"mass_g": 80, "product_name": "PLT O+", "product_id": 7}, {"mass_g": 40, "product_name": "CRYO A+", "product_id": 8}, {"mass_g": 80, "product_name": "CRYO AB+", "product_id": 9}, {"mass_g": 300, "product_name": "FFP A+", "product_id": 10}, {"mass_g": 300, "product_name": "FFP B+", "product_id": 11}, {"mass_g": 300, "product_name": "FFP AB+", "product_id": 12}]
order = {"order_id": 123, "requested": [{"product_id": 0, "quantity": 2}, {"product_id": 10, "quantity": 4}]}

def check_weight(order, product_info):
    product_info_df = pd.DataFrame(product_info).set_index("product_id")
    order_df = pd.DataFrame(order["requested"]).set_index("product_id")
    order_weight = order_df.join(product_info_df)[['quantity', 'mass_g']].prod(1).sum()
    if order_weight > 1800:
        #???
    else:
        print('product shipped!')

If the weight is over 1800g, I'd like to split the order.
That is, take the items with less than 1800g total weight and subtract their quantities from order, then run that through the code again (and again) until all quantities of order are 0, and thus, the order would be 100% fulfilled.

How would I write that logic?

标签: pythonpandasdataframe

解决方案


所以你可以做的是,首先有一个订单总数的计数器。然后如果重量> 1800,则从该总数中减去一个。也从你的 else 语句中减去一个,所以这里的总数也会发生变化。做一个 while 循环,让这段代码一直运行,直到总数变为 0。让我知道这是否有意义或者您是否有任何后续问题。


推荐阅读