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

如何基于另一DataFrame匹配填充df中Cup列的NaN值?

问题描述

我有两个DataFrame:df和dfcup。df的Cup列部分行存在NaN值。dfcup是通过执行dfcup = df.groupby(['Height','Weight','Cup']).size().reset_index().rename(columns={0:'count'})得到的,用于统计Height、Weight和Cup组合的出现次数。我的需求是根据Height和Weight进行匹配,用dfcup中对应的首个Cup值填充df中Cup列的NaN值,例如身高65.0、体重130.0的行,将NaN替换为dfcup中的"B"。请问是否可以用for循环或类似方法实现?


解决方案

方法一:使用for循环实现

可以用for循环实现,不过这种方式在处理大数据集时效率较低,适合小数据场景:

  1. 先基于dfcup构建一个匹配字典,键为(Height, Weight)组合,值为对应分组的首个Cup值:
# 按Height、Weight分组,提取每组第一个Cup值并转为字典
cup_mapping = dfcup.groupby(['Height', 'Weight'])['Cup'].first().to_dict()
  1. 遍历df中Cup为NaN的行,通过字典匹配填充:
for idx, row in df[df['Cup'].isna()].iterrows():
    match_key = (row['Height'], row['Weight'])
    if match_key in cup_mapping:
        df.loc[idx, 'Cup'] = cup_mapping[match_key]

方法二:高效的Pandas内置方法(推荐)

更推荐使用Pandas原生的合并与填充方法,避免逐行遍历的性能损耗:

  1. 从dfcup中生成每个(Height, Weight)对应的首个Cup匹配表:
# 分组提取首个Cup值,生成匹配表
cup_match_table = dfcup.groupby(['Height', 'Weight'])['Cup'].first().reset_index(name='Fill_Cup')
  1. 将原df与匹配表左连接,用匹配到的值填充NaN:
# 左连接保留原df所有行
df = df.merge(cup_match_table, on=['Height', 'Weight'], how='left')
# 填充Cup列的NaN值
df['Cup'] = df['Cup'].fillna(df['Fill_Cup'])
# 清理临时列(可选)
df = df.drop(columns=['Fill_Cup'])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:15:33