【问题标题】:How to refer to 2 column names in python?如何在python中引用2个列名?
【发布时间】:2022-01-07 19:09:06
【问题描述】:

我正在尝试使用sqlalchemygeopandas 从Python 中的SQL 服务器检索包含几何信息的数据库。几何格式有 2 列,我想保留两者。我使用的代码是

import geopandas as gpd
from sqlalchemy import create_engine

db_connection_url = "postgresql://username:password@host:5432/database"
con = create_engine(db_connection_url)  
sql = 'SELECT osm_id, way, tags, way_centroid FROM osm.bldg WHERE height IS NOT NULL;'
df = gpd.read_postgis(sql, con, geom_col='way')

我想在 R 中实现类似的东西,即geom_col = c('way', 'way_centroid') 用于函数gpd.real_postgis,但我知道它不会在 python 中以这种方式工作。如何在 python 中实现这一点?

【问题讨论】:

  • FROM 前面的逗号有误。应该是SELECT osm_id, way, tags, way_centroid FROM osm.bldg ...
  • @JimJones 感谢您指出这一点。我完全没有注意到当我试图从 SELECT 子句中删除一些脚本时......
  • 我不认为 geopandas 支持两个主要的几何列,但我认为没有理由不能拥有另一个 GeometryArray 类型的列。也就是说,由于您的第二组几何图形是质心,您是否可以使用 BigQuery 的地理空间指令,例如st_xst_y 提取 x 和 y 值作为附加浮点列?

标签: python postgresql postgis geopandas


【解决方案1】:

在我使用 psycopg2 在 python 中获取数据之前,我设法修改了 sql 查询以将几何图形更改为 WKT...

import psycopg2
import pandas as pd

connection = psycopg2.connect(user="username",
                                  password="password",
                                  host="host",
                                  port="5432",
                                  database="database")
cursor = connection.cursor()
postgreSQL_select_Query = 'SELECT osm_id, ST_ASTEXT(way), tags, ST_ASTEXT(way_centroid) FROM osm.bldg WHERE height IS NOT NULL;'

cursor.execute(postgreSQL_select_Query)
print("Selected rows from database")
records = cursor.fetchall()

df = pd.DataFrame(records)
df.columns=['osm_id', 'way', 'tags', 'way_centroid']
df

【讨论】:

【解决方案2】:

不是存储两个几何图形的直接方法,但您可以使用 st_xst_y 地理函数直接将质心坐标转换为浮点数:

db_connection_url = "postgresql://username:password@host:5432/database"
con = create_engine(db_connection_url)  

sql = '''
SELECT (
    osm_id,
    tags,
    st_x(way_centroid) as centroid_x,
    st_y(way_centroid) as centroid_y,
    way
)
FROM osm.bldg
WHERE height IS NOT NULL;
'''

df = gpd.read_postgis(sql, con, geom_col='way')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2010-10-09
    • 1970-01-01
    • 2019-12-23
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多