背景:我有一些資料幀可以通過開關打開或關閉。我想用每個打開的資料框填充字典。然后我希望能夠遍歷資料幀。
問題:我不知道如何動態構建我的字典以僅在打開開關時包含資料幀。
我試過的:
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}')
以上不起作用,因為它總是包含資料幀,如果開關關閉,它是一個字串而不是完全排除。
uj5u.com熱心網友回復:
我的設定與您的類似,但我不關心每個資料幀分配上的開關:
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']})
b = pd.DataFrame({'IDs':[1,2],
'Cost':[1.1,1.2],
'Names':['APPLE1','Blue1']})
c = pd.DataFrame({'IDs':[12],
'Cost':[1.5],
'Names':['APPLE2']})
total = {"first":a,"second":b,"third":c} # don't worry about the switches yet.
現在我們才過濾:
list_switches = [sw_a, sw_b, sw_c] # the switches! finally!
total_filtered = {tup[1]:total[tup[1]] for tup in zip(list_switches, total) if tup[0]}
并繼續像你所做的那樣。
for df in total_filtered:
temp_cost = sum(total[df]['Cost'])
print(f'The number of fruits for {df} is {len(total[df])} and the cost is {temp_cost}')
輸出:

編輯
您可以稍微喜歡這個zip功能,例如,如果您正在動態構建資料框、資料框名稱和開關的串列,并且可以確保它們的長度始終相同,您可以執行以下操作:
# pretend these three lists are coming from somewhere else and can have variable length, rather than being hard-coded.
list_dfs = [a,b,c]
list_switches = [sw_a, sw_b, sw_c]
list_names = ["first", "second", "third"]
# use a zip object over the three lists.
zipped = zip(list_dfs, list_switches, list_names)
total = {tup[2] : tup[0] for tup in zipped if tup[1]}
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}')
uj5u.com熱心網友回復:
考慮這樣的事情。
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']})
b = pd.DataFrame({'IDs':[1,2],
'Cost':[1.1,1.2],
'Names':['APPLE1','Blue1']})
c = pd.DataFrame({'IDs':[12],
'Cost':[1.5],
'Names':['APPLE2']})
total = {}
if sw_a == True:
total['sw_a'] = a
if sw_b == True:
total['sw_b'] = b
if sw_c == True:
total['sw_c'] = c
print(total)
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}')
The number of fruits for sw_a is 5 and the cost is 6.5
The number of fruits for sw_c is 1 and the cost is 1.5
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/365732.html
上一篇:在Cerberus(Python)中,有沒有辦法創建允許字典中的任何鍵名的模式?
下一篇:按字典串列中的鍵對值進行分組
