我正在嘗試輸出 4 個資料表并獲得Expected Output以下內容?我想使用Outcomes字典和 iter 并以這樣的方式格式化它,它使我能夠將所有串列值放入option 1和option 2和所有行值中row 1, row 2...。如何修改代碼中的 for 回圈以便獲得預期輸出?
代碼:
import pandas as pd
def Pandas(infos, title):
display(pd.DataFrame(infos).style.set_caption(title).set_table_styles([{
'selector': 'caption',
'props': [
('color', 'red'),
('font-size', '16px'),
('text-align', 'center')
]
}]))
for id, info in Outcomes.items():
for k in info:
infos = {{f'{x}:': info[k][x]} if isinstance(info[k][x],list) else info[k][x] for x in info[k]}
Pandas(infos, k)
字典:
Outcomes = {
'Values':{
'First': {
'option 1': [12,345,5412],
'option 2': [2315,32,1],
'Additional Option': {'row 1': [232,3,1,3],
'row 2': [3,4,5,11],
'row 3': [15,6,12,34]}
},
'Second': {
'option 1': [1,4,5,6,2],
'option 2': [5,6,3,2,1],
'Additional Option': {'row 1': [-5,3,1,2],
'row 2': [4,4,12,11],
'row 3': [67,6,5,34]}
}
},
'Values 2':{
'First': {
'option 1': [12,345345,512412],
'option 2': [2315,4,3],
'Mega':{'row 1': [-45,12,33,1.3],
'row 2': [3.5,4.8,5,11]}
}
}
}

uj5u.com熱心網友回復:
您可以使用遞回遍歷您的字典并創建一個扁平化的 DataFrame 字典:
def get_nested_df(dic, concat_key="", df_dic=dict()):
rows = {k:v for k,v in dic.items() if not isinstance(v, dict)}
if rows:
df_dic.update({concat_key: pd.DataFrame.from_dict(rows)})
for k,v in dic.items():
if isinstance(v, dict):
get_nested_df(v, f"{concat_key} {k}", df_dic)
return df_dic
df_dic = get_nested_df(Outcomes)
for k,v in df_dic.items():
print(f"{k}\n{v}\n")
輸出:
Values First
option 1 option 2
0 12 2315
1 345 32
2 5412 1
Values First Additional Option
row 1 row 2 row 3
0 232 3 15
1 3 4 6
2 1 5 12
3 3 11 34
Values Second
option 1 option 2
0 1 5
1 4 6
2 5 3
3 6 2
4 2 1
Values Second Additional Option
row 1 row 2 row 3
0 -5 4 67
1 3 4 6
2 1 12 5
3 2 11 34
Values 2 First
option 1 option 2
0 12 2315
1 345345 4
2 512412 3
Values 2 First Mega
row 1 row 2
0 -45.0 3.5
1 12.0 4.8
2 33.0 5.0
3 1.3 11.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362557.html
上一篇:如何在熊貓中按行合并兩個資料幀
下一篇:熊貓資料框
