You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas中同空间坐标行的邻近集群迁移后处理需求

解决方案

1. 标记需要迁移的目标行

首先给每个集群内的重复坐标行分配序号,精准筛选出同一集群同坐标中超过2条的多余行:

import pandas as pd
import numpy as np
from scipy.spatial.distance import cdist

# 假设你的数据集存储在df中,包含latitude、longitude、cluster(聚类标签列)
# 生成坐标组合列,用于分组统计
df['coord'] = df.apply(lambda x: (x['latitude'], x['longitude']), axis=1)
# 按集群+坐标分组,给每组内的行从1开始编号
df['dup_rank'] = df.groupby(['cluster', 'coord']).cumcount() + 1

# 筛选出需要迁移的行:同一集群同坐标中序号>2的部分
to_move = df[df['dup_rank'] > 2].copy()

2. 预计算各集群中心坐标

提前算出所有集群的空间中心,方便后续计算距离:

# 计算每个集群的纬度、经度均值作为中心
cluster_centers = df.groupby('cluster')[['latitude', 'longitude']].mean().reset_index()
# 转成数组格式,提升距离计算效率
center_array = cluster_centers[['latitude', 'longitude']].values

3. 为待迁移行分配最优目标集群

对每一行,计算到其他集群中心的距离,选择**最近且仍有剩余容量(行数<9)**的集群完成迁移:

# 统计当前各集群的行数
cluster_counts = df['cluster'].value_counts().to_dict()

for idx, row in to_move.iterrows():
    original_cluster = row['cluster']
    # 计算当前行到所有集群中心的欧式距离
    coords = np.array([[row['latitude'], row['longitude']]])
    distances = cdist(coords, center_array)[0]
    
    # 生成候选集群:排除原集群,且当前行数未达9的上限
    candidates = cluster_centers[
        (cluster_centers['cluster'] != original_cluster) & 
        (cluster_centers['cluster'].map(cluster_counts) < 9)
    ].copy()
    candidates['distance'] = distances[candidates.index]
    
    # 按距离排序,选择最近的可用集群
    if not candidates.empty:
        target_cluster = candidates.sort_values('distance').iloc[0]['cluster']
        # 更新原数据集的聚类标签
        df.loc[idx, 'cluster'] = target_cluster
        # 更新集群计数,保证后续分配准确
        cluster_counts[original_cluster] -= 1
        cluster_counts[target_cluster] += 1

4. 清理临时字段

最后移除过程中生成的辅助列:

df.drop(['coord', 'dup_rank'], axis=1, inplace=True)

核心逻辑说明

  • 仅处理同一集群内同坐标行数超过2的行,保留前2条在原集群,完全匹配需求,不会改动其他正常重复坐标行
  • 迁移时优先选择空间最近的集群,同时严格遵守9行/集群的容量限制,最大程度保留原聚类的空间最优分配
  • 极端情况下(所有其他集群已满),可根据实际需求添加兜底逻辑(如保留在原集群、调整集群容量等)

内容的提问来源于stack exchange,提问作者PParker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 01:30:15