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

Pandas如何根据开关变量筛选DataFrame动态构建目标字典

解决方案

原代码的核心问题是预先将所有键写入字典,仅替换开关关闭项的值为空列表,而非直接排除对应键,导致遍历时报空列表不存在Cost字段的错误。

以下是可直接运行的优化代码:

import pandas as pd

sw_a = True
sw_b = False
sw_c = True

# 初始化空字典
total = {}
# 仅开关开启时才添加对应键值对
if sw_a:
    total["first"] = pd.DataFrame({
        'IDs':[1234,5346,1234,8793,8793],
        'Cost':[1.1,1.2,1.3,1.4,1.5],
        'Names':['APPLE','Orange','STRAWBERRY','Grape','Blue']
    })
if sw_b:
    total["second"] = pd.DataFrame({
        'IDs':[1,2],
        'Cost':[1.1,1.2],
        'Names':['APPLE1','Blue1']
    })
if sw_c:
    total["third"] = pd.DataFrame({
        'IDs':[12],
        'Cost':[1.5],
        'Names':['APPLE2']
    })

# 遍历直接取键和值,代码更简洁
for df_name, df in total.items():
    temp_cost = sum(df['Cost'])
    print(f'The number of fruits for {df_name} is {len(df)} and the cost is {temp_cost}')

运行输出结果:

The number of fruits for first is 5 and the cost is 6.5
The number of fruits for third is 1 and the cost is 1.5

如果后续需要新增更多可控的DataFrame,推荐用配置+字典推导式的写法,可维护性更高:

import pandas as pd

sw_a = True
sw_b = False
sw_c = True

# 所有条目配置统一维护,新增只需要加配置项即可
df_config = [
    ("first", sw_a, {'IDs':[1234,5346,1234,8793,8793], 'Cost':[1.1,1.2,1.3,1.4,1.5], 'Names':['APPLE','Orange','STRAWBERRY','Grape','Blue']}),
    ("second", sw_b, {'IDs':[1,2], 'Cost':[1.1,1.2], 'Names':['APPLE1','Blue1']}),
    ("third", sw_c, {'IDs':[12], 'Cost':[1.5], 'Names':['APPLE2']})
]

# 一行代码生成目标字典
total = {key: pd.DataFrame(data) for key, switch, data in df_config if switch}

# 后续遍历逻辑不变
for df_name, df in total.items():
    temp_cost = sum(df['Cost'])
    print(f'The number of fruits for {df_name} is {len(df)} and the cost is {temp_cost}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:06:08