pandas按指定条件关联两个表并设置Result字段优先级的实现问题
pandas 双DataFrame按规则合并实现方案
首先修正原数据创建的语法问题(Algo列的M/T为字符串需加引号),完整实现代码如下:
import pandas as pd # 修正后的df1、df2创建代码 df_1 = pd.DataFrame({ 'Num' : [525, 524, 523, 522], 'Algo' : ['M', 'M', 'M', 'M'], 'Distance' : [25, 28, 30, 75], 'Result' : ['Good', 'Good', 'Good', 'Good'] }) df_2 = pd.DataFrame({ 'Num' : [525, 524, 520], 'Algo' : ['T', 'T', 'T'], 'Distance' : [25, 28, 98], 'Result' : ['Good', 'Bad', 'Good'] }) # 1. 以Num、Distance为键做外连接,保留两边未匹配记录 merge_df = pd.merge(df_1, df_2, on=['Num', 'Distance'], how='outer', suffixes=('_1', '_2')) # 2. 合并Algo字段,非空值用逗号拼接 merge_df['Algo'] = merge_df.apply( lambda x: ', '.join(filter(pd.notna, [x['Algo_1'], x['Algo_2']])), axis=1 ) # 3. Result优先取df1的值,df1无匹配取df2的值 merge_df['Result'] = merge_df['Result_1'].fillna(merge_df['Result_2']) # 4. 筛选需要的列,按Num降序排序和预期输出格式对齐 result = merge_df[['Num', 'Algo', 'Distance', 'Result']].sort_values('Num', ascending=False).reset_index(drop=True) print(result)
运行后输出结果和预期完全一致:
| Num | Algo | Distance | Result |
|---|---|---|---|
| 525 | M, T | 25 | Good |
| 524 | M, T | 28 | Good |
| 523 | M | 30 | Good |
| 522 | M | 75 | Good |
| 520 | T | 98 | Good |
内容的提问来源于stack exchange,提问作者Roman Lents
相关产品推荐
相关产品推荐

