【问题标题】:Check if string coordinates represent a polygon using Pandas使用 Pandas 检查字符串坐标是否表示多边形
【发布时间】:2022-11-10 21:26:26
【问题描述】:

使用 Pandas,如何检查是否可以使用字符串中的坐标创建有效的多边形几何?

输入示例:

import pandas as pd
coord_series = pd.Series([
    '-33, 50, -30, 38, -40, 27, -33.0, 50.5',
    '-xx, xx, -xx, xx, -xx, xx, -xxxx, xxxx',
    '-10, 20, -30, 40',
    '-10, 20, -30, 40, -50, 60, -70',
    '-11, 11, -11, 11, -11, 11, -11.1, 11.1'
])

只有第一个字符串形成有效的多边形。

需要一个函数来接受一个 Series 对象并输出一个 Series 对象。

【问题讨论】:

    标签: python pandas validation geometry polygon


    【解决方案1】:

    下面的代码看起来很多,但我无法创建更短的解决方案。 shapely.geometry.Polygon.is_valid 似乎需要进行评估,但这还不够,因为有时它会引发错误。

    from shapely.geometry import Polygon
    
    def nullify_invalid_polygon(s: pd.Series) -> pd.Series:
        def is_digit(lst):
            return [e.strip().lstrip('-').replace('.', '', 1).isdigit() for e in lst]
        coords = s.str.split(',')
        even_cnt = coords.map(len) % 2 == 0
        point_cnt_ge3 = coords.map(len) >= 6
        all_digits = coords.map(is_digit).map(all)
        s2 = coords.where(even_cnt & point_cnt_ge3 & all_digits, None)
        polygon_shell = s2.map(lambda x: list(zip(*[iter(map(float, x))]*2)) if x else None)
        is_valid = polygon_shell.map(lambda x: Polygon(x).is_valid if x else False)
        return is_valid
    
    print(nullify_invalid_polygon(coord_series))
    # 0     True
    # 1    False
    # 2    False
    # 3    False
    # 4    False
    # dtype: bool
    

    【讨论】:

      猜你喜欢
      • 2020-04-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 2014-03-24
      • 2011-06-17
      • 2018-08-27
      • 2015-12-18
      相关资源
      最近更新 更多