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

基于Python实现Power BI中经纬度与多边形的归属校验需求

经纬度与多边形匹配的Power BI实现方案

需求说明

  • 本人熟练操作Power BI,但Python经验有限,首次提问若表述不清请见谅。
  • 现有两个数据表:
    • 表A:包含**Longitude(经度)和Latitude(纬度)**两列,存储点位数据
    • 表B:包含WKT格式的Polygon列,存储区域多边形坐标
  • 需实现逻辑:
    1. 检查表A中每条经纬度记录是否落在表B的某一个多边形范围内
    2. 若匹配成功,在表A新增一列,存储对应多边形的WKT坐标
    3. 若该点位未落在任何多边形内,将该点位记录追加至表A末尾

实现方案

Power BI无原生函数支持该空间判断逻辑,可借助Python的pygeodesy库中的isenclosedBy函数实现,具体步骤如下:

1. 准备工作

在Power BI的Python脚本编辑器中,先安装pygeodesy库:

!pip install pygeodesy

2. 完整处理脚本

import pandas as pd
from pygeodesy import LatLon, parseWkt

# 读取Power BI传入的表数据
table_a = dataset['TableA']
table_b = dataset['TableB']

# 解析表B中的多边形,转换为pygeodesy可识别的对象
polygons = []
for wkt in table_b['Polygon']:
    # 处理Power BI中可能的WKT格式冗余(如末尾多余逗号)
    cleaned_wkt = wkt.rstrip(',)') + ')'
    poly = parseWkt(cleaned_wkt)
    polygons.append((poly, wkt))  # 保存多边形对象和原始WKT字符串

# 初始化结果列
table_a['Matched_Polygon'] = None

# 遍历表A的每条点位记录
for idx, row in table_a.iterrows():
    lat = row['Latitude']
    lon = row['Longitude']
    point = LatLon(lat, lon)
    
    # 检查是否落在某个多边形内
    matched = False
    for poly, wkt in polygons:
        if point.isenclosedBy(poly):
            table_a.at[idx, 'Matched_Polygon'] = wkt
            matched = True
            break  # 匹配到第一个多边形后停止检查
    
    # 若未匹配到任何多边形,将该点位记录追加到表A末尾
    if not matched:
        new_row = pd.DataFrame([{'Longitude': lon, 'Latitude': lat, 'Matched_Polygon': None}])
        table_a = pd.concat([table_a, new_row], ignore_index=True)

# 将处理后的表返回给Power BI
output = table_a

3. 注意事项

  • Power BI中传入的Polygon格式示例:Polygon((-0.01 51.52, -0.02 52.03, -0.1 52.03,-0.01 51.52, -0.02 52.03, -0.1 52.03,-0.01 51.52, -0.02 52.03, -0.1 52.03,-0.01 51.52, -0.02 52.03, -0.1 52.03,-0.01 51.52, -0.02 52.03, -0.1 52.03,)),脚本中已处理末尾多余逗号的问题
  • 若表B包含多个多边形,脚本会按顺序匹配第一个包含点位的多边形
  • 若需求是“未匹配时追加多边形而非点位”,可修改new_row的内容为多边形的WKT及对应空经纬度(需根据实际业务调整)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 01:24:30