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

如何将存储聚类坐标的字典转换为指定格式的Pandas DataFrame?

正确实现代码

你之前使用pd.DataFrame.from_dict的写法会将每个簇对应的整个坐标数组作为单个单元格存储,因此输出结果每行对应一个簇,不符合单坐标点一行的需求。可通过遍历聚类字典+逐簇转换后合并的方式实现需求:

分步实现

import pandas as pd
import numpy as np

# 此处替换为你自己的聚类结果字典
cluster_dict = {
    1: np.array([[31.47671257, 30.0206217 ],
                 [31.49589   , 30.02547   ],
                 [31.474725  , 30.025477  ]]),
    2: np.array([[31.29888   , 29.989722  ],
                 [31.31500756, 29.97498111]])
}

df_list = []
# 遍历每个簇的编号和对应坐标数组
for cluster_id, point_arr in cluster_dict.items():
    # 将坐标数组转为带Lng、Lat列的临时表
    temp_df = pd.DataFrame(point_arr, columns=['Lng', 'Lat'])
    # 新增簇号列
    temp_df['no_of_Cluster'] = cluster_id
    df_list.append(temp_df)

# 合并所有临时表并重置索引
result_df = pd.concat(df_list, ignore_index=True)

简洁版实现(列表推导式)

result_df = pd.concat(
    [pd.DataFrame(points, columns=['Lng', 'Lat']).assign(no_of_Cluster=cid) 
     for cid, points in cluster_dict.items()],
    ignore_index=True
)

运行后result_df就是符合你要求的三列结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 09:24:01