Pandas - 将列转换为分组的数组坐标

时间:2014-09-27 10:11:37

标签: python arrays pandas scipy euclidean-distance

我有一个(x,y)坐标的DataFrame,我想转换成数组来执行成对距离计算。

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]})

所需的输出 - 数组中分组/聚合坐标的新DataFrame,以便我可以为每个数组应用一个函数:

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函数来执行此操作。有什么想法吗?

1 个答案:

答案 0 :(得分: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]
相关问题