2014-09-27 59 views
0

我有一個DataFrame(x,y)座標,我想轉換爲數組來執行成對距離計算。熊貓 - 將列轉換爲分組數組座標

df = pd.DataFrame({'type':  ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c'], 
...      'x': [1, 3, 5, 1, 3, 1, 3, 5], 
...      'y': [2, 4, 6, 2, 4, 2, 4, 6]}) 

所需的輸出 - 分組/彙總座標的陣列中的一個新的數據幀,這樣我可以應用機能的研究,以每個數組:

grp =  coordinates 
    a array([[1, 2], 
       [3, 4], 
       [5, 6]]) 

    b array([[1, 2], 
       [3, 4]]) 

    c array([[1, 2], 
       [3, 4], 
       [5, 6]]) 

距離計算我想申請...

grp['distances'] = grp.apply(lambda x: scipy.spatial.distance.pdist(x['coordinates'], 'euclidean'), axis = 1) 

我似乎無法得到groupby函數來做到這一點。有任何想法嗎?

回答

0

創建對x的新列,Y

df['xy'] = df.apply(lambda x: [x['x'], x['y']], axis=1) 

GROUPBY和聚合成列表

gb = df.groupby('type') 
df2 = gb.aggregate({'xy': lambda x: list(x)}) 

這產生一個列表:

df2 
    xy 
type  
a [[1, 2], [3, 4], [5, 6]] 
b [[1, 2], [3, 4]] 
c [[1, 2], [3, 4], [5, 6]] 

注意,以應用距離功能你必須做的:

from scipy.spatial import distance 
df2['distances'] = df2['xy'].apply(lambda x: distance.pdist(x, 'euclidean')) 

df2 

    xy       distances 
type   
a [[1, 2], [3, 4], [5, 6]] [2.82842712475, 5.65685424949, 2.82842712475] 
b [[1, 2], [3, 4]]   [2.82842712475] 
c [[1, 2], [3, 4], [5, 6]] [2.82842712475, 5.65685424949, 2.82842712475]