我有一个像这样的数据框
df = pd.DataFrame({
'id': ['A','A','B','B','B'],
'x': [1,1,2,2,3],
'y': [1,2,2,3,3]
})
在本例中,我想要的输出是组中每个点的平均距离
A 组:(距离((1,1),(1,2)))/1 = 1
B 组:(距离((2,2),(2,3)) + 距离((2,3),(3,3)) + 距离((2,2),(3 ,3)))/3 = 1.138
我可以使用np.linalg.norm
计算距离,但我很困惑在pandasgroupby
中使用它。谢谢
注意:我的想法是,我首先尝试制作这个数据框(我卡住的地方),它包含我需要计算距离的点对,之后我只需要计算距离和分组平均值
最佳答案
基于numpy广播
的可能解决方案:
def calc_avg_distance(group):
x = group[['x', 'y']].values
dist_matrix = np.sqrt(((x - x[:, np.newaxis])**2).sum(axis=2))
np.fill_diagonal(dist_matrix, np.nan)
avg_distance = np.nanmean(dist_matrix)
return avg_distance
(df.groupby('id').apply(lambda x: calc_avg_distance(x))
.reset_index(name='avg_distance'))
输出:
id avg_distance
0 A 1.000000
1 B 1.138071
关于python - Pandas 群体内的平均距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76261304/