我有数千万行从多维数组文件传输到PostgreSQL数据库.我的工具是Python和psycopg2.批量处理数据的最有效方法是使用copy_from.但是,我的数据大多是32位浮点数(real或float4),所以我宁愿不转换为real→text→real.这是一个示例数据库DDL:
CREATE TABLE num_data
(
id serial PRIMARY KEY NOT NULL,
node integer NOT NULL,
ts smallint NOT NULL,
val1 real,
val2 double precision
);
Run Code Online (Sandbox Code Playgroud)
这是我使用字符串(文本)使用Python的地方:
# Just one row of data
num_row = [23253, 342, -15.336734, 2494627.949375]
import psycopg2
# Python3:
from io import StringIO
# Python2, use: from cStringIO import StringIO
conn = psycopg2.connect("dbname=mydb user=postgres")
curs = conn.cursor()
# Convert floating point numbers to text, write to COPY input
cpy = StringIO()
cpy.write('\t'.join([repr(x) for x in …Run Code Online (Sandbox Code Playgroud) 如果我有一个包含字符串的iterable,是否有一种简单的方法可以将其转换为流?我想做这样的事情:
def make_file():
yield "hello\n"
yield "world\n"
output = tarfile.TarFile(…)
stream = iterable_to_stream(make_file())
output.addfile(…, stream)
Run Code Online (Sandbox Code Playgroud) 我想知道从pandas DataFrame到postges DB中的数据写入数据的最快方法.
1)我尝试过pandas.to_sql,但由于某种原因需要实体来复制数据,
2)除了我试过以下:
import io
f = io.StringIO()
pd.DataFrame({'a':[1,2], 'b':[3,4]}).to_csv(f)
cursor = conn.cursor()
cursor.execute('create table bbbb (a int, b int);COMMIT; ')
cursor.copy_from(f, 'bbbb', columns=('a', 'b'), sep=',')
cursor.execute("select * from bbbb;")
a = cursor.fetchall()
print(a)
cursor.close()
Run Code Online (Sandbox Code Playgroud)
但它返回空列表[].
所以我有两个问题:将数据从python代码(数据帧)复制到postgres DB的最快方法是什么?我试过的第二种方法有什么不对?
python ×3
postgresql ×2
binary-data ×1
bulkinsert ×1
copy ×1
dataframe ×1
iterator ×1
psycopg2 ×1
stream ×1