【发布时间】:2022-01-02 06:35:44
【问题描述】:
背景:我有一些数据帧可以通过开关打开或关闭。我想用每个打开的数据框填充字典。然后我希望能够遍历数据框。
问题:我不知道如何动态构建我的字典以仅在打开开关时包含数据帧。
我的尝试:
import pandas as pd
sw_a = True
sw_b = False
sw_c = True
a = 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_a == True else []
b = pd.DataFrame({'IDs':[1,2],
'Cost':[1.1,1.2],
'Names':['APPLE1','Blue1']}) if sw_b == True else []
c = pd.DataFrame({'IDs':[12],
'Cost':[1.5],
'Names':['APPLE2']}) if sw_c == True else []
total = {"first":a,"second":b,"third":c}
for df in total:
temp_cost = sum(total[df]['Cost'])
print(f'The number of fruits for {df} is {len(total[df])} and the cost is {temp_cost}')
上述方法不起作用,因为它始终包含数据帧,如果开关关闭,它是一个字符串,而不是完全排除。
【问题讨论】:
标签: python pandas dataframe dictionary for-loop