python - Pandas 群体内的平均距离

标签 python pandas group-by euclidean-distance

我有一个像这样的数据框

df = pd.DataFrame({
    'id': ['A','A','B','B','B'],
    'x': [1,1,2,2,3],
    'y': [1,2,2,3,3]
})

enter image description here

在本例中,我想要的输出是组中每个点的平均距离

A 组:(距离((1,1),(1,2)))/1 = 1

B 组:(距离((2,2),(2,3)) + 距离((2,3),(3,3)) + 距离((2,2),(3 ,3)))/3 = 1.138

enter image description here

我可以使用np.linalg.norm计算距离,但我很困惑在pandasgroupby中使用它。谢谢

注意:我的想法是,我首先尝试制作这个数据框(我卡住的地方),它包含我需要计算距离的点对,之后我只需要计算距离和分组平均值

enter image description here

最佳答案

基于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/

相关文章:

python - Mongo 嵌入式文档查询

python - pandas dataframe dtypes比较相等

python - Seaborn pairplot 使用 anaconda 和 pycharm 无法正常工作。获得自由度警告

mysql - 使用 MySQL 中的 ORDER 和 GROUP 获取每个 GROUP 的最大数字

sql - 按给定数量的行值分组

python - OError : [Errno 26] Text file busy: '/...myvirtualenv/bin/python'

python - 在排序的 Pandas 数据帧上有效搜索范围

python - 重新调整 3d numpy 数组中的值

python - Pandas - 删除 DataFrame 的最后一列

sql-server - 使用 sum 和 group 在 SQL 中查询