2017-05-02 2 views
2

Wie kann ich das Wörterbuch verschütten und die Informationen in die Zeile im Dataframe hinzufügen? Der Wert ist Liste, die Wörterbuch enthält, und ich möchte den 'Schlüssel' in die 'Spalte' im Datenrahmen und 'Wert' auf den Wert im Datenrahmen verschieben. Zum Beispiel ist der Orignal DatenrahmenPython: Wie kann ich das Wörterbuch verschütten und die Informationen in die Zeile im Dataframe hinzufügen?

Dataframe df: 
    id options 
0 0  [{'a':1 ,'b':2},{'a':3 ,'b':4}] 
1 1  [{'a':5 ,'b':6},{'a':7 ,'b':8}] 
2 2  [{'a':9 ,'b':10},{'a':11,'b':12}] 

ich die Struktur wie unten

 id a b 
0 0  1 2 
1 0  3 4 
2 1  5 6 
3 1  7 8 
4 2  9 10  
5 2  11 12 

Antwort

0
# Produce Example DataFrame 
options = pd.Series([[{'a':1 ,'b':2},{'a':3 ,'b':4}], 
        [{'a':5 ,'b':6},{'a':7 ,'b':8}], 
        [{'a':9 ,'b':10},{'a':11,'b':12}] 
        ]) 

df = pd.DataFrame({'id': [0,1,2], 'options': options}) 

# Initialize df to hold results 
final_df = pd.DataFrame() 

# Iterate through df. We will use 'row' but not 'index' 
for index, row in df.iterrows(): 

    # row is a series with two elements. first is id, second is list of dicts 
    list_of_dicts = row['options'] 
    row_as_df  = pd.DataFrame(list_of_dicts) 

    # Add back id column and append as new rows in final df of results 
    row_as_df['id'] = row['id']    
    final_df  = pd.concat([final_df, row_as_df], axis=0) 


final_df.reset_index(drop=True) 

Ausgabe

a b id 
0 1 2 0 
1 3 4 0 
2 5 6 1 
3 7 8 1 
4 9 10 2 
5 11 12 2 
0

versuchen, diese chage will:

lst_cols = ['options'] 

pd.DataFrame({ 
    col:np.repeat(df[col].values, df[lst_cols[0]].str.len()) 
    for col in df.columns.drop(['options']) 
}).join(pd.DataFrame.from_records(np.concatenate(df.options.values))) 

Ausgang:

Out[45]: 
    id a b 
0 0 1 2 
1 0 3 4 
2 1 5 6 
3 1 7 8 
4 2 9 10 
5 2 11 12 
Verwandte Themen