2014-03-31 81 views
1

我的字典裏是這樣轉換嵌套的字典到數據幀

mydict = 
{240594.0: {1322.0: 1.6899999999999999, 1323.0: 1.6900000000000002, 1324.0: 1.6899999999999999, 1325.0: 1.6899999999999999, 1326.0: 1.6899999999999999, 1327.0: 1.6900000000000002, 1328.0: 1.6899999999999999, 1329.0: 1.6899999999999999, 1356.0: 1.6900000000000002, 1357.0: 1.6900000000000002, 1358.0: 1.6899999999999999, 1359.0: 1.6900000000000002, 1360.0: 1.6900000000000002, ...}, 

226918.0: {1322.0: 1.6900000000000002, 1323.0: 1.6899999999999999, 1324.0: 1.6900000000000002, 1325.0: 1.6899999999999999, 1326.0: 1.6900000000000002, 1327.0: 1.6899999999999999, 1328.0: 1.6900000000000002, 1329.0: 1.6899999999999999, 1352.0: 1.6900000000000002, 1353.0: 1.6900000000000002, 1354.0: 1.6899999999999999 ...}} 

這是{iri_key: {week:price, week:price ...}, iri_key: {...}} 真正的價值,我想這本詞典轉換成數據幀,它看起來像

  week week week ... 
irikey: price price price ... 
irikey: ... ... ... 

在上述情況下

  1322.0     ... 
240594.0 1.6899999999999999  ... 
226918.0 1.6900000000000002  ... 

我該怎麼做?

+0

你知道「周」的範圍嗎? – locoyou

+0

是從1322到1373 – JonghoKim

+0

但它們中的一些缺少值因此維度不匹配。仍然最大周是1373和最小值是1322 – JonghoKim

回答

2

正如您可能已經發現的那樣,DataFrame(mydict)是有效的代碼。你可以簡單地拿轉置(.T)來得到你想要的結果。

在代碼可讀性和直接性方面,有更好的方法可用:使用特定的DataFrame構造函數DataFrame.from_dict,它具有關鍵字參數orient

In [2]: DataFrame.from_dict(mydict, orient='index') 
Out[2]: 
     1356 1357 1358 1359 1360 1322 1323 1324 1325 1326 1327 \ 
226918 NaN NaN NaN NaN NaN 1.69 1.69 1.69 1.69 1.69 1.69 
240594 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 1.69 

     1328 1329 1352 1353 1354 
226918 1.69 1.69 1.69 1.69 1.69 
240594 1.69 1.69 NaN NaN NaN 

[2 rows x 16 columns] 

從您提供的示例數據中可以看出,缺失值和可變長度得到正確處理。