2017-04-26 2 views
1

Ich habe eine Liste der Wörterbücher a die wie folgt aussieht:Liste der Wörterbücher Arrays und Matrizen enthalten, Datenrahmen Pandas

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]]) 

Wie Sie einige Tasten enthalten eine Reihe sehen können, andere eine Matrix ...

dieses Wörterbuch Da würde Ich mag einen Datenrahmen schaffen, ... dh unter den Namen in einer automatischen Art und Weise getan werden, wie dies sollte von der diese

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]) 

sieht Wörterbuch Schlüssel und im Falle einer Matrix add col1, col2, etc ... Ich sollte auch eine column (möglicherweise in der ersten Position) in der Pandas Dataframe, die mir den Index des ursprünglichen Wörterbuchs .. in diesem Fall die Spalte heißt dictionary

Können Sie mir helfen? Dank

Antwort

0

Sie könnten auf eine Liste von Datenrahmen iterieren und hängen wie so:

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) 

Das funktioniert aber nicht die Spaltennamen Problem zu lösen.

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 
Verwandte Themen