2017-04-26 157 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