如何将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列结果如下:
| Vehicle | Quantity of Goods | required_vehicles |
|---|---|---|
| v1 | 8.0 | 1 |
| v2 | 12.0 | 2 |
| v3 | 16.0 | 4 |
| v4 | 12.0 | 4 |
内容的提问来源于stack exchange,提问作者Stephen Smith
相关产品推荐
相关产品推荐

