How to apply euclidean distance function to a groupby object in pandas dataframe?

后端 未结 4 477
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-20 06:03

I have a set of objects and their positions over time. I would like to get the average distance between objects for each time point. An example dataframe is as follows:

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 06:58

    You could pass an array of the points to scipy.spatial.distaince.pdist and it will calculate all pair-wise distances between Xi and Xj for i>j. Then take the mean.

    import numpy as np
    from scipy import spatial
    
    df.groupby('time').apply(lambda x: spatial.distance.pdist(np.array(list(zip(x.x, x.y)))).mean())
    

    Outputs:

    time
    0     1.550094
    1    10.049876
    2    53.037722
    dtype: float64
    

提交回复
热议问题