1
這一個問題,我以前one.it的前 store dictionary in pandas dataframe存儲複雜的字典
的一個孩子的母親字典我有一本字典
dictionary_example={'New York':{1234:{'choice':0,'city':'New York','choice_set':{0:{'A':100,'B':200,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}},
234:{'choice':1,'city':'New York','choice_set':{0:{'A':100,'B':400},1:{'A':100,'B':300,'C':1000}}},
1876:{'choice':2,'city':'New York','choice_set':{0:{'A': 100,'B':400,'C':300},1:{'A':100,'B':300,'C':1000},2:{'A':600,'B':200,'C':100}}
}},
'London':{1534:{'choice':0,'city':'London','choice_set':{0:{'A':100,'B':400,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}},
2134:{'choice':1,'city':'London','choice_set':{0:{'A':100,'B':600},1:{'A':170,'B':300,'C':1000}}},
1776:{'choice':2,'city':'London','choice_set':{0:{'A':100,'B':400,'C':500},1:{'A':100,'B':300},2:{'A':600,'B':200,'C':100}}}},
'Paris':{1534:{'choice':0,'city':'Paris','choice_set':{0:{'A':100,'B':400,'C':300},1:{'A':200,'B':300,'C':300},2:{'A':500,'B':300,'C':300}}},
2134:{'choice':1,'city':'Paris','choice_set':{0:{'A':100,'B':600},1:{'A':170,'B':300,'C':1000}}},
1776:{'choice':1,'city':'Paris','choice_set':{0:{'A': 100,'B':400,'C':500},1:{'A':100,'B':300}}}
}}
我希望它成爲一個熊貓數據(這裏面的一些具體數值可能不完全準確)
id choice A_0 B_0 C_0 A_1 B_1 C_1 A_2 B_2 C_2 New York London Paris
1234 0 100 200 300 200 300 300 500 300 300 1 0 0
234 1 100 400 - 100 300 1000 - - - 1 0 0
1876 2 100 400 300 100 300 1000 600 200 100 1 0 0
1534 0 100 200 300 200 300 300 500 300 300 0 1 0
2134 1 100 400 - 100 300 1000 - - - 0 1 0
2006 2 100 400 300 100 300 1000 600 200 100 0 1 0
1264 0 100 200 300 200 300 300 500 300 300 0 0 1
1454 1 100 400 - 100 300 1000 - - - 0 0 1
1776 1 100 400 300 100 300 - - - - 0 0 1
在老問題中,好人爲子字典提供了一種方法:
df = pd.read_json(json.dumps(dictionary_example)).T
def to_s(r):
return pd.read_json(json.dumps(r)).unstack()
flattened_choice_set = df["choice_set"].apply(to_s)
flattened_choice_set.columns = ['_'.join((str(col[0]), col[1])) for col in flattened_choice_set.columns]
result = pd.merge(df, flattened_choice_set,
left_index=True, right_index=True).drop("choice_set", axis=1)
任何方式來做大字典?
一切順利, 凱文
示例字典的關鍵字是['Paris','London',234,'New York',1876],您是否混淆了括號或是這部分挑戰的一部分? ;) –
應該是紐約和巴黎,我會檢查一下。 –
現在應該還好吧 –