簡體   English   中英

從pandas Dataframe插入幾何點mysql

[英]Insert geometry point mysql from pandas Dataframe

我正在使用熊貓和一個數據框來處理一些數據。 我想將數據加載到其中一個字段是Point的mySQL數據庫中。

在我用python解析的文件中,我有點的經度和緯度。

我用點信息(id和coords)創建了一個數據框(df):

id   coords
 A  GeomFromText( ' POINT(40.87 3.80) ' )

我已經保存了mySQL中從文本創建Point所需的命令。 但是,執行時:

from sqlalchemy import create_engine
engine = create_engine(dbconnection)

df.to_sql("point_test",engine, index=False, if_exists="append")

我收到以下錯誤:

DataError:(mysql.connector.errors.DataError)1416(22003):無法從發送到GEOMETRY字段的數據中獲取幾何對象

由於df.to_sql在應執行mySQL中的GeomFromText函數時,將GeomFromText('POINT(40.87 3.80)')轉換為“ GeomFromText('POINT(40.87 3.80)')”字符串而被觸發。

有沒有人建議如何使用pandas數據框以文本形式在mySQL幾何字段中插入信息?

解決方法是使用需要添加的幾何信息的字符串創建臨時表,然后通過從臨時表中調用ST_GeomFromText來更新point_test表。

假設數據庫的表point_test具有ID(VARCHAR(5))和coords(POINT):

a。以“ A”和“ B”為例創建數據幀df

dfd = np.array([['id','geomText'],
            ["A","POINT( 50.2 5.6 )"],
            ["B","POINT( 50.2 50.4 )"]])

df=pd.DataFrame(data=dfd[1:,:], columns=dfd[0,:])

b。將point“ A”和“ B”添加到point_test中,但僅添加ID,並將字符串“ geomText”添加到表temp_point_test中

df[['id']].to_sql("point_test",engine, index=False, if_exists="append")

df[['id', 'geomText']].to_sql("temp_point_test",engine, index=False, if_exists="append")

C。 將表temp_point_test中的點應用於ST_GeomFromText(),以更新表point_test。 最后,刪除temp_point_test:

conn = engine.connect()

conn.execute("update point_test pt set pt.coords=(select ST_GeomFromText(geomText) from temp_point_test tpt "+
                     "where pt.id=tpt.id)")

conn.execute("drop table temp_point_test")   

conn.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM