0
我有一個嵌套字典,有5個級別masterdict = {a : {b: {c: {d : { e: }}}}}
,我試圖創建一個平坦的數據框架。如何從深度嵌套字典創建數據框?
當我運行下面的代碼:
masterDF = pd.DataFrame()
for a in masterdict:
for b in masterdict[a]:
for c in masterdict[a][b]:
for d in masterdict[a][b][c]:
eDF = pd.DataFrame(masterdict[a][b][c][d])
eDF['level4'] = str(d)
eDF['level3'] = str(c)
eDF['level2'] = str(b)
eDF['level1'] = str(a)
masterDF = masterDF.append(eDF)
我收到以下錯誤:
---------------------------------------------------------------------------
PandasError Traceback (most recent call last)
<ipython-input-13-cc9930935c64> in <module>()
5 for c in masterdict[a][b]:
6 for d in masterdict[a][b][c]:
----> 7 eDF = pd.DataFrame(masterdict[a][b][c][d])
8 eDF['level4'] = str(d)
9 eDF['level3'] = str(c)
C:\Anaconda\lib\site-packages\pandas\core\frame.pyc in __init__(self, data, index, columns, dtype, copy)
275 copy=False)
276 else:
--> 277 raise PandasError('DataFrame constructor not properly called!')
278
279 NDFrame.__init__(self, mgr, fastpath=True)
PandasError: DataFrame constructor not properly called!
我不知道這是否是扁平化嵌套的字典正確的代碼,但如果它是,你能否提出我可能做錯了什麼?
謝謝。
你能否給我們提供一個模擬對象?我懷疑這是一個JSON文件? – biobirdman 2014-11-24 06:15:01