python - 将 Python NumPy 数组插入 PostgreSQL 数据库

标签 python arrays postgresql numpy psycopg2

如何将大量坐标 (x,y) 插入到 postgresSQL 表中?我不想使用 for 循环。它是一个 3601x3601 像素的光栅。

import numpy as np
import psycopg2


# Data example:
east = np.linspace(-180.0,180.0,num=10)
north = np.linspace(-90.0,90.0,num=10)
coor = np.vstack([east, north])

conn = psycopg2.connect("dbname='postgres' user='dbuser' host='localhost' password='dbpass'")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS foobar;")
cur.execute("CREATE TABLE foobar (coordinate   point);")

# Working for an coordinate example:
cur.execute("INSERT INTO foobar VALUES (('12.56,56.43'));")

# Working for 1st coordinate in coor:
tmp = ','.join(str(e) for e in coor[:,0])
cur.execute('INSERT INTO foobar VALUES (point(' + tmp + '));')

# NOT WORKING!!!
# Insert all points in one go:
# cur.execute('INSERT INTO foobar VALUES (coor);')

conn.commit()

最佳答案

使用函数execute_values()您可以使用单个 SQL 语句插入多行。您应该以这种格式为函数准备数据:

[['(-180.0, -90.0)'],
 ['(-140.0, -70.0)'],
 ['(-100.0, -50.0)'],
 ['(-60.0, -30.0)'],
 ['(-20.0, -10.0)'],
 ['(20.0, 10.0)'],
 ['(60.0, 30.0)'],
 ['(100.0, 50.0)'],
 ['(140.0, 70.0)'],
 ['(180.0, 90.0)']]

代码:

from psycopg2.extras import execute_values

# Data example:
east = np.linspace(-180.0,180.0,num=10)
north = np.linspace(-90.0,90.0,num=10)

# get array of pairs [east, north]
coor = np.dstack([east, north])

# convert to array of tuples (east, north) as strings
values = [[str(tuple(i))] for i in coor[0]]

execute_values(cur, 'INSERT INTO foobar VALUES %s', values)

conn.commit()

另见 this answer.

关于python - 将 Python NumPy 数组插入 PostgreSQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53850316/

相关文章:

Python 'while' 有两个条件 : "and" or "or"

python - 新手查询: mocking in python

c - 使用 "new"命令在 C 中动态数组

arrays - 如何将一列以逗号分隔的字符串转换为字符串数组

c++ - C、C++ 与 Python 的接口(interface)

python - 为什么 ElementTree 吃/忽略命名空间(在属性值中)?

java - 将数据读入数组时出现空异常

java - 如何在java中返回一个可由其他对象访问的数组?

python - 使用SQLAlchemy迁移数据库(sqlite到Postgres CloudSQL)

postgresql - 在Docker容器内部运行的Postgres上安装和使用pg_cron扩展