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

基于Country和Sex双条件在Pandas中合并DataFrame并填充NaN值

解决Pandas中基于多条件填充NaN的问题

刚好碰到过类似的场景!你需要用df1里对应country和sex组合的cancer值,去填补df2中该列的缺失值,这里有两种实用的方法可以实现:

方法一:构建映射字典快速填充

首先从df1生成一个以(country, sex)为组合键的映射字典,这样就能精准匹配对应的值来填充缺失:

import pandas as pd

# 先构造示例数据
df1 = pd.DataFrame({
    'country': ['Albania', 'Albania', 'Antigua', 'Antigua', 'Argen', 'Argen'],
    'sex': ['female', 'male', 'female', 'male', 'female', 'male'],
    'year': [2000]*6,
    'cancer': [32, 58, 2, 5, 591, 2061]
})

df2 = pd.DataFrame({
    'country': ['Albania', 'Albania', 'Albania', 'Albania', 'Albania', 'Antigua', 'Antigua'],
    'year': [1985, 1985, 1986, 1986, 1987, 1992, 1985],
    'sex': ['female', 'male', 'female', 'male', 'female', 'male', 'female'],
    'cancer': [pd.NA, pd.NA, pd.NA, pd.NA, 25.0, pd.NA, pd.NA]
})

# 生成country+sex到cancer的映射字典
cancer_map = df1.set_index(['country', 'sex'])['cancer'].to_dict()

# 遍历df2填充缺失值:仅当cancer为NaN时,用映射字典匹配的值替换
df2['cancer'] = df2.apply(
    lambda row: cancer_map[(row['country'], row['sex'])] if pd.isna(row['cancer']) else row['cancer'],
    axis=1
)

print(df2)

方法二:用Merge合并后填充(更适合大数据集)

如果你的数据量比较大,推荐用这种更符合Pandas原生风格的方法,效率会更高:

# 从df1中提取用于匹配的参考列,并重命名避免冲突
df1_ref = df1[['country', 'sex', 'cancer']].rename(columns={'cancer': 'cancer_fill'})

# 左合并df2和参考表,保留df2的所有行
merged_df = df2.merge(df1_ref, on=['country', 'sex'], how='left')

# 用参考值填充原列的缺失值
merged_df['cancer'] = merged_df['cancer'].fillna(merged_df['cancer_fill'])

# 移除临时辅助列,得到最终结果
final_df = merged_df.drop('cancer_fill', axis=1)

print(final_df)

两种方法都能得到你期望的结果:

country year sex cancer
0 Albania 1985 female 32
1 Albania 1985 male 58
2 Albania 1986 female 32
3 Albania 1986 male 58
4 Albania 1987 female 25
5 Antigua 1992 male 5
6 Antigua 1985 female 2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:27:37