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

如何在Pandas中按列分组排序并生成Polygon几何对象

解决方案

步骤1:安装并导入依赖库

首先确保安装所需工具库:

pip install pandas geopandas shapely

导入库:

import pandas as pd
import geopandas as gpd
from shapely.geometry import Polygon

步骤2:构建初始DataFrame

还原题目给出的样本数据:

data = {
    'Area': ['A', 'A', 'A', 'B', 'B', 'C', 'C'],
    'Sequence': [2, 1, 3, 2, 1, 1, 2],
    'X': [604582.25, 604590.25, 604579.25, 536584.47, 536570, 509202.13, 509205.3],
    'Y': [320710, 320704.75, 320710, 176977.83, 176996.43, 307995.99, 307951.24]
}

df = pd.DataFrame(data)

步骤3:生成df1(分组排序并拼接坐标字符串)

按Area分组,组内按Sequence升序排列后拼接坐标:

def process_group(group):
    # 组内按Sequence升序排序
    sorted_group = group.sort_values('Sequence')
    # 拼接单条坐标字符串
    coord_strings = sorted_group.apply(lambda row: f"{row['X']} {row['Y']}", axis=1)
    # 连接所有坐标字符串
    return ', '.join(coord_strings)

# 分组处理生成df1
df1 = df.groupby('Area').apply(process_group).reset_index(name='XY_by_sequence')

步骤4:生成df2(转换为Polygon几何对象)

将坐标字符串转换为Polygon类型的几何对象:

def str_to_polygon(coord_str):
    # 拆分坐标字符串为单个坐标对
    coord_pairs = coord_str.split(', ')
    # 转换为浮点型坐标元组列表
    coords = [tuple(map(float, pair.split())) for pair in coord_pairs]
    # 创建Polygon对象
    return Polygon(coords)

# 复制df1并添加Polygon列
df2 = df1.copy()
df2['Polygon_XY_by_sequence'] = df2['XY_by_sequence'].apply(str_to_polygon)

# 可选:转换为GeoDataFrame以支持空间操作
gdf2 = gpd.GeoDataFrame(df2, geometry='Polygon_XY_by_sequence')

验证输出

打印结果即可查看与题目要求一致的结构:

print("df1结果:")
print(df1)

print("\ndf2结果:")
print(df2)

内容的提问来源于stack exchange,提问作者Vivek kanna Jayaprakash

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 09:06:10