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

后端 未结 4 473
佛祖请我去吃肉
佛祖请我去吃肉 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:35

    You could also use the itertools package to define your own function as follow:

     import itertools
     import numpy as np
    
     def combinations(series):
            l = list()
            for item in itertools.combinations(series,2):
                l.append(((item[0] - item[1])**2))
            return l
    
    df2 = df.groupby('time').agg(combinations)
    df2['avg_distance'] = [np.mean(np.sqrt(pd.Series(df2.iloc[k,0]) + 
    pd.Series(df2.iloc[k,1]))) for k in range(len(df2))]
    
    df2.avg_distance.to_frame()
    

    Then, the output is:

        avg_distance
    time    
    0   1.550094
    1   10.049876
    2   53.037722
    

提交回复
热议问题