如何基于另一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循环实现,不过这种方式在处理大数据集时效率较低,适合小数据场景:
- 先基于
dfcup构建一个匹配字典,键为(Height, Weight)组合,值为对应分组的首个Cup值:
# 按Height、Weight分组,提取每组第一个Cup值并转为字典 cup_mapping = dfcup.groupby(['Height', 'Weight'])['Cup'].first().to_dict()
- 遍历
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原生的合并与填充方法,避免逐行遍历的性能损耗:
- 从
dfcup中生成每个(Height, Weight)对应的首个Cup匹配表:
# 分组提取首个Cup值,生成匹配表 cup_match_table = dfcup.groupby(['Height', 'Weight'])['Cup'].first().reset_index(name='Fill_Cup')
- 将原
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
相关产品推荐
相关产品推荐

