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

基于Pandas匹配用户country与interest获取对应code的实现问题

解决方案:根据国家与兴趣列表匹配对应Code

前提假设

首先假设你的匹配规则DataFrame包含country(国家)、interest(兴趣)、code(对应编码)三列,示例结构如下:

import pandas as pd

# 示例规则表
rule_df = pd.DataFrame({
    'country': ['Germany', 'Germany', 'Germany', 'Hungary', 'Hungary'],
    'interest': ['Sport', 'Swimming', 'Gaming', 'Sport', 'Swimming'],
    'code': ['01', '02', '03', '11', '12']
})

核心实现函数

以下函数接收目标国家、兴趣列表和规则DataFrame,返回匹配到的编码列表,同时支持保持输入兴趣的顺序:

def get_matching_codes(target_country, target_interests, rule_df):
    codes = []
    for interest in target_interests:
        # 精准匹配国家和兴趣
        match_result = rule_df[(rule_df['country'] == target_country) & 
                              (rule_df['interest'] == interest)]
        if not match_result.empty:
            codes.append(match_result['code'].iloc[0])
        # 可选:如果需要对不存在的兴趣抛出异常,取消下面注释
        # else:
        #     raise ValueError(f"未找到国家{target_country}对应兴趣{interest}的编码")
    return codes

测试验证

  • 测试用例1:输入Germany和['Sport']
    print(get_matching_codes('Germany', ['Sport'], rule_df))  # 输出: ['01']
    
  • 测试用例2:输入Hungary和['Sport','Swimming']
    print(get_matching_codes('Hungary', ['Sport','Swimming'], rule_df))  # 输出: ['11', '12']
    
  • 测试用例3:输入Germany和['Gaming','Swimming']
    print(get_matching_codes('Germany', ['Gaming','Swimming'], rule_df))  # 输出: ['03', '02']
    

注意事项

  • 函数默认会跳过规则表中不存在的兴趣(返回结果不包含对应项),如果需要严格校验,可开启注释中的异常抛出逻辑
  • 确保规则表中每个country+interest组合唯一,避免匹配到多条结果导致取值错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:56:29