社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

tidus4400

tidus4400 最近创建的主题
tidus4400 最近回复了
3 年前
回复了 tidus4400 创建的主题 » Python Dataframe通过一个名称来指定满意的行

您可以解决迭代数据帧行并相应分配行李号的问题:

import pandas as pd

df = pd.DataFrame(
    {"parcel": ["a", "b", "c", "d", "e"], "weight": [85, 60, 15, 30, 150]}
)


MIN_BAG = 1
MAX_BAG = 5
bags_range = range(MIN_BAG, MAX_BAG + 1)

# We keep track of the bags and how much weight they hold at any moment
used_bags = {bag_idx: 0 for bag_idx in bags_range}

# Create empty df column
df["bag_num"] = pd.NA

for row in df.itertuples():

    parcel_weight = row.weight

    if parcel_weight > 100:
        continue

    for bag in bags_range:
        temp_weight = used_bags.get(bag) + parcel_weight
        if temp_weight <= 100:
            used_bags[bag] = temp_weight
            df.at[row.Index, "bag_num"] = bag
            break


print(df)

这就产生了这样的结果:

  parcel  weight bag_num
0      a      85       1
1      b      60       2
2      c      15       1
3      d      30       2
4      e     150    <NA>