2017-06-05 124 views
0

我有一個熊貓系列這樣如何拆分Pandas字典?

pd.DataFrame({"name": ['John','Mary','Tommy'], 
       "time": ['"data": [{"t": "16:50"},{"t": "17:05"}]', 
         '"data": [{"t": "16:10"}, {"t": "17:11"}, {"t": "17:12"}]', 
         np.nan]}) 

現在,當涉及到數據會看起來像這樣

name            time 
0 John   "data": [{"t": "16:50"},{"t": "17:05"}] 
1 Mary "data": [{"t": "16:10"}, {"t": "17:11"}, {"t":... 
2 Tommy            NaN 

在列時間是一本字典(字符串格式),它包含一個列表(最多3個項目,有時候是NaN)。由於最大列表大小是已知的,所以我想將我的數據平鋪到以下內容中。

name time1 time2 time3 
0 John 16:50 17:05 NaN 
1 Mary 16:10 17:11 17:12 
2 Tommy NaN NaN NaN 

除了使用for循環,我不知道怎麼做,在熊貓的方式。提前致謝。

+0

[拆分字典/列表一大熊貓柱內部分成單獨的列(的可能的複製https://stackoverflow.com/questions/38231591/splitting-dictionary-list-inside-a-pandas-column-into -separate-columns) –

+0

謝謝@AnubhavSingh。我也看看那個。但是我無法得到我的熊貓物品,因爲我的時間欄是一個字符串。我猜想需要做的是1.在時間列中,將字符串轉換爲json 2.從該JSON中提取列表並將其放入列中。完成這2個步驟後,我可以在該頁面上應用該解決方案。 – Winston

回答

1

您可以將字符串評估爲字典,然後將列表轉換爲列。最後將新列與名稱合併。

pd.concat([data['name'], 
      data.time.apply(lambda x: eval('{'+x+'}')['data'] if pd.notnull(x) else np.nan)\ 
      .apply(pd.Series).applymap(lambda x: x['t'] if pd.notnull(x) else x)],axis=1)\ 
      .rename(columns={0:'time1',1:'time2',2:'time3'}) 
Out[567]: 
    name time1 time2 time3 
0 John 16:50 17:05 NaN 
1 Mary 16:10 17:11 17:12 
2 Tommy NaN NaN NaN