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

如何用父行值填充DataFrame中Value列的空值(None)

问题:替换DataFrame中空值为父行对应值

原始DataFrame

+-------+----------+---------+
| Key   | Parent   | Value   |
|-------+----------+---------|
| Key1  | Key10    | 246     |
| Key2  | Key1     | None    |
| Key3  | Key14    | 434     |
+-------+----------+---------+

需求说明

将Value列中的空值(None)替换为其父行(Parent列对应Key的行)的Value值;若父行不存在,则保留原空值。

预期结果

+-------+----------+---------+
| Key   | Parent   | Value   |
|-------+----------+---------|
| Key1  | Key10    | 246     |
| Key2  | Key1     | 246     |
| Key3  | Key14    | 434     |
+-------+----------+---------+

DataFrame准备代码

data = [['Key1', "Key10", 246], ['Key2', "Key1", None], ['Key3', 'Key14', "434"]]
df = pd.DataFrame(data, columns=['Key', 'Parent', 'Value'])

解决方案

先构建Key到Value的映射字典,再通过map匹配父行值,结合fillna完成空值替换:

# 建立Key与对应Value的映射关系
key_value_map = df.set_index('Key')['Value'].to_dict()

# 用父行Value填充空值,父行不存在则保持原空值
df['Value'] = df['Value'].fillna(df['Parent'].map(key_value_map))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:10:03