首页 > 解决方案 > 从 blob MySql 获取点数据类型

问题描述

我正在使用的 MySQL 表如下所示:

   id       count        point
0   1       1864         BLOB
1   2       6466         BLOB
2   3       4652         BLOB

描述表名;告诉我该点具有数据类型“点”

所以我通常通过使用来提取它的经纬度坐标

select 
  id,
  count,
  ST_AsText(point) as point
from table_name

正确渲染

   id       count        point
0   1       1864         POINT (117.036077 77.490958)
1   2       6466         POINT (157.03103 87.491231)
2   3       4652         POINT (147.030428 17.4925)

但是,当我将此表移动到 python 数据框以使用它时,它会作为字符串返回,
例如:“POINT (117.036077 77.490958)”

我想将它们保留为点对象或将字符串版本转换为点对象

匀称:https ://shapely.readthedocs.io/en/stable/manual.html

现在我正在做:

query = """
select 
  id,
  count,
  ST_AsText(point) as point
from table_name
"""
df = pd.read_sql(query, con=conn)
df["lng"] = df.geocode.apply(lambda row: str(row).split()[0][6:])
df["lat"] = df.geocode.apply(lambda row: str(row).split()[1][:-1])
df = df.astype({"lng": float, "lat":float})

from shapely.geometry import Point, Polygon
df["pt"] = df[['lng', 'lat']].apply(Point, axis=1)

这很乏味。我想直接从 MySQL Point 数据类型转换为 Point 对象。

我想这样做,所以我可以通过创建具有这些边界的多边形来简化下面的代码,并查看点是否在使用 shapely 库的多边形内。

df = df.loc[(129.569968 <= df.lng)&
            (df.lng <= 130.163217)& 
            (37.425664 <= df.lat) &
            (df.lat<= 37.668981)]

注意:我通常不会内联导入库,只是为了便于阅读

如果有什么不清楚的请告诉我,提前谢谢!

标签: pythonmysqlgeometryshapely

解决方案


推荐阅读