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

Pandas如何按id关联两个DataFrame且仅对animal列为cow的行生效

一步实现方案

你要的效果可以通过「全量左连+条件过滤列值」的方式实现,完全贴合你给出的伪代码逻辑,代码如下:

import pandas as pd
# 方法1:基于merge实现,和你写的伪代码逻辑最接近
df_total = df_animals.merge(df_cow_price, on="id", how="left") \
    .assign(price=lambda x: x["price"].where(x["animal"] == "cow"))

如果你的df_cow_price中id是唯一值,也可以用更高效的映射方案,不需要做表合并:

# 方法2:基于字典映射实现,性能更优
price_map = df_cow_price.set_index("id")["price"]
df_total = df_animals.assign(price=lambda x: x["id"].map(price_map).where(x["animal"] == "cow"))

两种方法最终输出的结果都和你给出的预期完全一致,非牛类的price列会自动填充为None(pandas中实际显示为NaN,效果等价)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:45:07