如何在Python中根据字符串选择对应的Pandas DataFrame?
解决方法:通过字符串获取对应DataFrame对象
推荐方案:字典映射法
这是最安全、易维护的实现方式,把所有汇率表统一存入字典,用表名字符串作为键,对应DataFrame作为值,之后直接通过键取值即可:
# 创建字典存储所有汇率表 fx_tables = {} # 循环读取所有汇率表,避免重复代码 for table_num in range(1, 8): table_name = f"FX_TABLE_{table_num}" fx_tables[table_name] = pd.read_excel(path6, table_name, index_col=0) # 遍历主表获取对应DataFrame for ind in Mainframe.index: fx_table_name = Mainframe['FX_Table'][ind] # 从字典中取出目标DataFrame target_fx_df = fx_tables[fx_table_name] print(type(target_fx_df)) # 输出为pandas.core.frame.DataFrame
优势
- 避免重复的读取代码,新增汇率表只需调整循环范围
- 不会意外访问全局命名空间中的其他变量,安全性高
- 代码结构清晰,便于后续维护
不推荐方案:使用globals()/locals()
可以通过全局命名空间直接获取变量,但这种方式风险较高,不建议在生产代码中使用:
for ind in Mainframe.index: fx_table_name = Mainframe['FX_Table'][ind] # 从全局命名空间中获取对应DataFrame target_fx_df = globals()[fx_table_name] print(type(target_fx_df))
弊端
- 如果主表中的字符串拼写错误或对应变量未定义,会直接抛出KeyError
- 破坏封装性,容易引发意外的变量访问问题
- 代码可读性和可维护性差
内容的提问来源于stack exchange,提问作者Marc Irmler
相关产品推荐
相关产品推荐

