【发布时间】:2021-01-16 22:11:55
【问题描述】:
我从一个单独的问题中获得了这个功能:How to apply euclidean distance function to a groupby object in pandas dataframe?。以下函数测量由time 和ids 分组的对象之间的距离。我遇到的问题是没有足够的坐标。运行时出错
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