2017-04-26 154 views
1

我的字典a的列表,看起來像這樣:列表大熊貓數據幀

a = {} 
a[0]={} 
a[0]['first_variable']=np.array([1,2,3,4,5]) 
a[0]['second_variable']=np.array([[1,2],[3,4],[5,6],[7,8],[9,10]]) 
a[1]={} 
a[1]['first_variable']=np.array([1,2,3,4,5]) 
a[1]['second_variable']=np.array([[1,2],[3,4],[5,6],[7,8],[9,10]]) 

正如你可以看到一些關鍵字包含一個數組,其他矩陣...

鑑於本字典,我想創建一個數據幀,看起來像這樣

a_dataframe = pd.DataFrame(columns=['dictionary','first_variable','second_variable_col1','second_variable_col2']) 
a_dataframe['dictionary'] = np.array([1,1,1,1,1,2,2,2,2,2]) 
a_dataframe['first_variable']=np.array([1,2,3,4,5,1,2,3,4,5]) 
a_dataframe['second_variable_col1']=np.array([1,3,5,7,9,1,3,5,7,9]) 
a_dataframe['second_variable_col2']=np.array([2,4,6,8,10,2,4,6,8,10]) 

這應該以自動的方式來完成...即從取名字字典鍵和矩陣的情況下添加col1,col2等... 我還應該在熊貓數據框中介紹column(可能位於第一個位置),它告訴我原始字典的索引..在這種情況下,列被稱爲dictionary

你能幫助我嗎? 感謝

回答

0

你可以遍歷並追加到dataframes的名單像這樣:

lodf = [] 
for k in a.keys(): 
    tmp_df = pd.concat([pd.DataFrame(x) for x in a[k].values()],1) 
    tmp_df.insert(0,'dictionary',k) 
    lodf.append(tmp_df) 

pd.concat(lodf) 

這工作,但它並沒有解決列名的問題。

1
dfs = [] 
for c, d in a.items(): 
    #iterate the outer dict and reconstruct the records to handle array and matrix 
    temp_dict = ({'{}_col{}'.format(k,i):e for k,v in d.items() 
         for i,e in enumerate(np.asarray(v).T.reshape(-1,5))}) 
    #append the dict indicator 
    temp_dict['dictionary'] = c+1 
    #append the df to the df list   
    dfs.append(pd.DataFrame(temp_dict)) 
df = pd.concat(dfs,axis=0,ignore_index=True) 
print(df) 

    dictionary first_variable_col0 second_variable_col0 second_variable_col1 
0   1     1      1      2 
1   1     2      3      4 
2   1     3      5      6 
3   1     4      7      8 
4   1     5      9     10 
5   2     1      1      2 
6   2     2      3      4 
7   2     3      5      6 
8   2     4      7      8 
9   2     5      9     10