2017-12-27 85 views
2

我的字典是這樣的熊貓:在單獨的列中顯示嵌套的字典中的值

[ 
    { 
    "detail": { 
    "name": "boo", 
    "id": 1 
    }, 
    "other": { 
     "gender": "m", 
     "no": "234" 
    } 
    }, 
    { 
    "detail": { 
     "name": "hoo", 
     "id": 2 
    }, 
    "other": { 
     "gender": "f", 
     "no": "456" 
    } 
    } 
] 

名單,我想在一個Excel文件的格式如下

detail   other 
name id gender no 
boo 1  m  234 
hoo 2  f  456 

打印此數據總之,我想顯示父鍵列下的列中的嵌套值。我如何使用熊貓來實現這個目標?

或者是我們可以達到這個目標的任何其他圖書館,因爲熊貓是安靜的。

回答

1

使用pd.io.json.json_normalize -

df = pd.io.json.json_normalize(data) 

這導致列名看起來像這樣 -

df.columns 
Index(['detail.id', 'detail.name', 'other.gender', 'other.no'], dtype='object') 

我們需要將此轉換爲MultiIndex,使用df.columns.str.split -

i = list(map(tuple, df.columns.str.split('.'))) 

致電pd.MultiIndex.from_tuples並指定結果背 -

df.columns = pd.MultiIndex.from_tuples(i) 
df 

    detail  other  
     id name gender no 
0  1 boo  m 234 
1  2 hoo  f 456 

如果你的數據比較複雜,你可能想使列上額外的sort_index呼叫 -

df = df.sort_index(axis=1) 
+1

Niceee ...謝謝你這麼多。 –