【问题标题】:Apply euclidean distance function with null values - Scipy应用具有空值的欧几里得距离函数 - Scipy
【发布时间】:2021-01-16 22:11:55
【问题描述】:

我从一个单独的问题中获得了这个功能:How to apply euclidean distance function to a groupby object in pandas dataframe?。以下函数测量由timeids 分组的对象之间的距离。我遇到的问题是没有足够的坐标。运行时出错

RuntimeWarning: Mean of empty slice.(np.array(list(zip(x['x'], x['y']))))

我希望在发生这种情况时传递 0。

import pandas as pd
from scipy import spatial
import numpy as np

time = [0, 0, 0, 0, 1, 1, 1]
x = [216, 218, 217, 280, 290, 130, 132]
y = [13, 12, 12, 110, 109, 3, 56]
car = [1, 2, 3, 1, 3, 4, 5]
ids = ['a', 'b', 'a', 'a', 'b', 'b', 'a']
df = pd.DataFrame({'time': time, 'x': x, 'y': y, 'car': car, 'ids': ids})

df = (df.groupby(['time','ids'])
        .apply(lambda x: spatial.distance.pdist
        (np.array(list(zip(x['x'], x['y']))))
        .mean())
        .reset_index()
        )

预期输出:

   time ids           0
0     0   a   78.042816
1     0   b           0
2     1   a           0
3     1   b  191.927069

【问题讨论】:

    标签: python scipy euclidean-distance


    【解决方案1】:

    在 lambda 函数中添加条件是一种技巧:

    (df.groupby(['time','ids'])
       .apply(lambda x: spatial.distance.pdist
           (np.array(list(zip(x['x'], x['y'])))).mean() if len(x)>1 else 0)
       .reset_index()
    )
    
       time ids           0
    0     0   a   78.042816
    1     0   b    0.000000
    2     1   a    0.000000
    3     1   b  191.927069
    
    

    【讨论】:

    • 干杯@FBruzzesi
    猜你喜欢
    • 1970-01-01
    • 2013-03-02
    • 2020-01-20
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2015-07-15
    相关资源
    最近更新 更多