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

如何在Python中通过字符串名称访问对应DataFrame以简化函数?

解决方法:根据code匹配对应DataFrame并避免代码重复

你之前的报错原因是传入的code是字符串类型,而loc是DataFrame专属的方法,字符串当然没有这个属性。下面提供两种实用的解决思路:

方法一:用字典建立字符串与DataFrame的映射

先创建一个字典,把code字符串和对应的DataFrame绑定,通过字典快速匹配到目标DataFrame:

# 先定义映射字典,key是你要用的code,value是对应的DataFrame
df_mapping = {
    "champion": champion_league,
    "europe": european_leagues  # 注意你之前拼写的earopean是笔误,修正为european
}

def check_league(t, d, code):
    # 从字典中获取目标DataFrame,不存在则返回0
    target_df = df_mapping.get(code)
    if not target_df:
        return 0
    
    temp = target_df.loc[(target_df['match_date'] == d) & (target_df['kot'] < t)]
    # 简化判断逻辑,一行返回结果
    return 0 if temp.empty else 1

后续如果新增其他DataFrame,只需要在字典里添加新的键值对,函数逻辑完全不用改,扩展性很强。

方法二:直接传入DataFrame对象(更简洁)

如果调用函数时能直接拿到DataFrame,完全不需要传code字符串,直接把DataFrame作为参数传入:

def check_league(t, d, target_df):
    temp = target_df.loc[(target_df['match_date'] == d) & (target_df['kot'] < t)]
    return 0 if temp.empty else 1

# 调用示例
check_league(10, '2024-01-01', champion_league)
check_league(10, '2024-01-01', european_leagues)

这种方式更直接,函数逻辑更纯粹,不需要维护映射关系,适合调用场景允许直接传递DataFrame的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:07:08