2017-06-13 107 views
0

產生大熊貓據幀我試圖創建一個嵌套的數據結構(分類)的字典如下:手動從嵌套的字典結構

pd.DataFrame({'genus': ['Unknown', 'External Metal'], 
       'species':['Other Feature/Anomaly', 
         ['Close External Metal', 'Touching Metal Object']]}) 

我得到以下的輸出:

  genus          species 
0   Unknown       Other Feature/Anomaly 
1 External Metal [Close External Metal, Touching Metal Object] 

這是我想要的東西:

  genus          species 
0   Unknown       Other Feature/Anomaly 
1 External Metal       Close External Metal 
2 External Metal       Touching Metal Object 

也許有考慮結構的THES更好的辦法用熊貓來分類?我不反對讓輸出的結構與上面指出的不同,只要層次結構得到適當維護,並且我可以輕鬆導航該層次結構謝謝!

回答

1

讓我們用applypd.Series,並stack

df.set_index('genus').species.apply(pd.Series).stack().reset_index(name='Species').drop('level_1', axis=1) 

輸出:

  genus    Species 
0   Unknown Other Feature/Anomaly 
1 External Metal Close External Metal 
2 External Metal Touching Metal Object 
+0

偉大的答案!謝謝。 – tubuliferous