2017-04-26 6 views
0

Ich habe ein Wörterbuch a die wie folgt aussieht:Wörterbuch enthalten Arrays und Matrizen Pandas Datenrahmen

a = {} 
a['first_variable']=np.array([1,2,3,4,5]) 
a['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 ...

diese Gegeben Wörterbuch, würde Ich mag einen Datenrahmen zu schaffen, wie diese Diese

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

sieht sollte in einer automatischen Art und Weise durchgeführt werden ... dh die Namen aus dem Wörterbuchschlüssel nimmt eine d im Falle einer Matrix addieren Sie col1, col2, etc ...

Können Sie mir helfen? Dank

+1

Können Sie bitte Ihre Seite Problem in einer anderen Frage stellen? – Allen

+0

sicher! es ist hier: http://stackoverflow.com/questions/43635629/list-of-dictionaries-containing-arrays-and-matrices-to-pandas-dataframe – gabboshow

Antwort

2

Sie concat mit Liste Verständnis und DataFrame Konstruktor verwenden können, zuletzt columns von MultiIndex in Spalten erstellen:

df = pd.concat([pd.DataFrame(a[x]) for x in a], keys=a.keys(), axis=1) 
df.columns = ['{}{}'.format(x[0], x[1]) for x in df.columns] 
print (df) 
    second_variable0 second_variable1 first_variable0 
0     1     2    1 
1     3     4    2 
2     5     6    3 
3     7     8    4 
4     9    10    5 
+0

danke! Ich habe zu meiner Frage ein Seitenproblem hinzugefügt, dh was ist, wenn das ursprüngliche Wörterbuch eine Liste von Wörterbüchern ist ... – gabboshow

+0

@ScottBoston - Danke dir. – jezrael

+0

@gabboshow - Sekunde nicht so einfach :( – jezrael

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

#Use a double list comprehension to construct both data and column names in one go. 
df = pd.DataFrame({'{}_col{}'.format(k,i):e for k,v in a.items() 
         for i,e in enumerate(np.asarray(v).T.reshape(-1,5))}) 
print(df) 
    first_variable_col0 second_variable_col0 second_variable_col1 
0     1      1      2 
1     2      3      4 
2     3      5      6 
3     4      7      8 
4     5      9     10 
Verwandte Themen