如何用父行值填充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
相关产品推荐
相关产品推荐

