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

如何在Pandas中仅对匹配商品的DataFrame数量列做减法避免NaN?

解决Pandas库存扣除时未匹配行出现NaN的问题

首先注意到你的购物车中商品名称Apples和库存里的Apple拼写不一致,这会导致匹配失败,先修正这个问题:

cart['Items'] = cart['Items'].replace('Apples', 'Apple')

直接执行inventory['Quantity'] = inventory['Quantity'] - cart['Quantity']会出现NaN,是因为Pandas按索引对齐数据,购物车只有2行,库存有5行,未对齐的行运算后会生成NaN。以下两种方法可以解决:

方法一:使用sub方法并设置fill_value=0

sub是Pandas的减法方法,设置fill_value=0后,未匹配到的购物车数量会按0处理,不会影响原库存数量:

# 将购物车转换为以商品名为索引的Series
cart_qty = cart.set_index('Items')['Quantity']
# 执行减法,未匹配项填充0
inventory['Quantity'] = inventory['Quantity'].sub(cart_qty, fill_value=0)

方法二:使用map结合fillna

通过map将库存商品名对应到购物车的数量,未匹配到的用0填充,再做减法:

# 创建商品名到购买数量的映射
qty_map = cart.set_index('Items')['Quantity']
# 映射后填充0,再扣除数量
inventory['Quantity'] -= inventory['Items'].map(qty_map).fillna(0)

执行以上任意一种方法后,未匹配商品的库存数量会保持原值,不会变成NaN,最终库存如下:

ItemsPriceQuantity
Apple1.3080
Banana0.57100
Orange1.3345
Book15.050
Notepad1.0100

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 15:38:32