2015-10-05 74 views
0

我有一個數據集,第一列有一個系列,第二列有一個ndarray。 ndarray是由「,」分隔值組成的。 如何將值分成不同的列?將ndarray劃分爲不同的列

data sample: 


      id        values 
    0  390725715     (service-selection-page, 1, 3) 
    1  682669054     (mobile-apps full-page, 1, 12) 
    2  770810604    (service-selection-page, 2, 41) 
    3  1009039867    (list-property full-page, 1, 7) 
    4  1523526830     (service-selection-page, 2, 1) 
    5  1495892895     (mobile-apps full-page, 1, 24) 
    6  975125144    (service-selection-page, 1, 37) 

這裏,id是一系列值是ndarray。

Expected output: 
      id      values    0  1 
0  390725715   service-selection-page  1  3 
1  682669054   mobile-apps full-page  1  12 
2  770810604   service-selection-page  2  41 
3  1009039867   list-property full-page 1  7 
4  1523526830   service-selection-page  2  1 
5  1495892895   mobile-apps full-page  1  24 
6  975125144   service-selection-page  1  37 

在此先感謝!

回答

0

df['values'].apply(lambda x: pd.Series(x))是你想要做的。

例如,如果你的df就像

In [38]: df = pd.DataFrame([[390 , pd.np.array(('service-selection-page', 1, 3))], 
          [110 , pd.np.array(('page', 1, 3))]], 
          columns=['id', 'values']) 
In [39]: df 
Out[39]: 
    id       values 
0 390 [service-selection-page, 1, 3] 
1 110     [page, 1, 3] 

其中,values包含numpy的陣列,applylambda x: pd.Series(x)df['values']

In [40]: df['values'].apply(lambda x: pd.Series(x)) 
Out[40]: 
         0 1 2 
0 service-selection-page 1 3 
1     page 1 3 

而且,你可以使用聯接來擴展列。

In [41]: df.join(df['values'].apply(lambda x: pd.Series(x))) 
Out[41]: 
    id       values      0 1 2 
0 390 [service-selection-page, 1, 3] service-selection-page 1 3 
1 110     [page, 1, 3]     page 1 3 
+0

太好了,謝謝!該解決方案非常有用... – eclairs