You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas DataFrame值除以对应数据集值求解CVRP所需车辆数

错误原因

两次报错的核心原因是列名匹配错误,同时缺少向上取整逻辑:

  • 第一次写法中data["transportation_data"]["vehicle_capacity"][x]的x是按行遍历的整行Series,不能直接作为字典的key,所以报unhashable type: 'Series'错误
  • 第二次写法尝试调用x.Vehicles和x.Quantity_Employed,但你的实际列名是Vehicle(无末尾s)和Quantity of Goods,对应属性不存在,因此报错

解决方案

首先提前提取车辆容量字典,避免重复索引提升效率,两种实现方式可选:

方式1:apply写法(逻辑直观,适合小数据量)

import math

capacity_dict = data["transportation_data"]["vehicle_capacity"]
df["required_vehicles"] = df.apply(
    lambda row: math.ceil(row["Quantity of Goods"] / capacity_dict[row["Vehicle"]]),
    axis=1
)

方式2:向量化写法(性能更高,适合万行以上大数据量)

import numpy as np

capacity_dict = data["transportation_data"]["vehicle_capacity"]
# 先匹配每个车型对应的容量
df["vehicle_capacity"] = df["Vehicle"].map(capacity_dict)
# 计算后向上取整转整数
df["required_vehicles"] = np.ceil(df["Quantity of Goods"] / df["vehicle_capacity"]).astype(int)

运行后得到的required_vehicles列结果如下:

VehicleQuantity of Goodsrequired_vehicles
v18.01
v212.02
v316.04
v412.04

内容的提问来源于stack exchange,提问作者Stephen Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:15:03