如何使用to_sql方法使用postgresql和pandas填充带有point数据类型的列的表?

时间:2018-01-24 17:39:53

标签: postgresql pandas

我有一个包含许多列的Excel。其中两列是纬度和经度。我需要使用Pandas将excel中的数据导入PostgreSQL中的表。 PG中的表有一列而不是两列。一列的名称为Coordinate,类型为 POINT

例如,excel数据包含:

Name        Longitude       Latitude
MEDELLÍN    -75.5760017134  6.24858636743
ABEJORRAL   -75.4287403904  5.78930111433
ABRIAQUÍ    -76.0642948678  6.63228195504
ALEJANDRÍA  -75.141334501   6.37606264274

我想使用Pandas作为PostgreSQL表导入数据:

Name        Position
MEDELLÍN    POINT(-75.5760017134,6.24858636743)
ABEJORRAL   POINT(-75.4287403904,5.78930111433)
ABRIAQUÍ    POINT(-76.0642948678,6.63228195504)
ALEJANDRÍA  POINT(-75.141334501,6.37606264274)

如何“连接”两个源列(Lat和Lon)并使用to_sql方法将数据导入PostgreSQL?

1 个答案:

答案 0 :(得分:1)

您必须安装pandas个库。首先,将csv文件导入import pandas as pd from geopandas import GeoDataFrame from shapely.geometry import Point import psycopg2 df = pd.read_table('./sample.csv', sep=',', header='infer') 数据帧

lat/long

使用一些空间参考(我使用Point)将EPSG 4236转换为lat/long类型并删除name, Point列,因为您只会上传geom = [Point(xy) for xy in zip(df.Longitude, df.Latitude)] df = df.drop(['Longitude', 'Latitude'], axis=1) crs = {'init': 'epsg:4326'} gdf = GeoDataFrame(df, crs=crs, geometry=geom)

gdf.head()

Name geometry 0 MEDELLÍN POINT (-75.5760017134 6.248586367430001) 1 ABEJORRAL POINT (-75.42874039039999 5.789301114330001) 2 ABRIAQUÍ POINT (-76.0642948678 6.632281955040001) 3 ALEJANDRÍA POINT (-75.141334501 6.376062642740001) 结果

postgres

现在您已准备好上传到conn = psycopg2.connect("dbname='template1' user='dbuser' host='localhost' password='dbpass'") gdf.to_sql(`your_table_name`, conn, other options) 。创建与postgres的连接

pandas

有关to_sql的详细信息,请参阅特定于版本的:\blockchain\truffle\demo\mortgage-blockchain-demo>truffle serve erving static assets in .\build on port 8080... ebuilding... :\Users\Mabel\AppData\Roaming\npm\node_modules\truffle\build\cli.bundled.js:220 48 return (new fsevents(path)).on('fsevent', callback).start(); ^ ypeError: fsevents is not a constructor at createFSEventsInstance (C:\Users\Mabel\AppData\Roaming\npm\node_modules\t uffle\build\cli.bundled.js:220548:11) at setFSEventsListener (C:\Users\Mabel\AppData\Roaming\npm\node_modules\truf le\build\cli.bundled.js:220602:16) at FSWatcher.FsEventsHandler._watchWithFsEvents (C:\Users\Mabel\AppData\Roam ng\npm\node_modules\truffle\build\cli.bundled.js:220766:16) at FSWatcher.<anonymous> (C:\Users\Mabel\AppData\Roaming\npm\node_modules\tr ffle\build\cli.bundled.js:220900:25) at LOOP (fs.js:1758:14) at _combinedTickCallback (internal/process/next_tick.js:67:7) at process._tickCallback (internal/process/next_tick.js:98:9) 文档。