gpt4 book ai didi

python - 使用 psycopg2 复制到带有 ARRAY INT 列的表

转载 作者:行者123 更新时间:2023-11-29 11:58:06 25 4
gpt4 key购买 nike

我创建了一个结构类似于以下的表:

create table some_table (
id serial,
numbers int []
);

我想以一种高效的方式复制 pandas 数据帧,所以我不想使用缓慢的 to_sql 方法,所以,遵循 https://stackoverflow.com/a/41876462/754176https://stackoverflow.com/a/29125940/754176我尝试了以下方法:

import pandas as pd
import psycopg2

# Create the connection, and the cursor (ommited)

# Function from the second link
def lst2pgarr(alist):
return '{' + ','.join(alist) + '}'


df = pd.DataFrame({'numbers': [[1,2,3], [4,5,6], [7,8,9]]})

df['numbers'] = df.numbers.apply(lambda x: lst2pgarr([str(y) for y in x]))

import io
f = io.StringIO()
df.to_csv(f, index=False, header=False, sep="|")
f.seek(0)

cursor.copy_from(f, 'some_table', columns=["numbers"], sep='|')

cursor.close()

此代码不会抛出错误,但不会向表中写入任何内容。

所以,我将代码修改为

import csv

df = pd.DataFrame({'numbers': [[1,2,3], [4,5,6], [7,8,9]]})

df['numbers'] = df.numbers.apply(lambda x: lst2pgarr([str(y) for y in x]))


f = io.StringIO()
df.to_csv(f, index=False, header=False, sep="|", quoting=csv.QUOTE_ALL, quotechar="'"))
f.seek(0)

cursor.copy_from(f, 'some_table', columns=["numbers"], sep='|')

cursor.close()

此代码抛出以下错误:

---------------------------------------------------------------------------
DataError Traceback (most recent call last)
<ipython-input-40-3c58c4a64abc> in <module>
----> 1 cursor.copy_from(f, 'some_table', columns=["numbers"], sep='|')

DataError: malformed array literal: "'{1,2,3}'"
DETAIL: Array value must start with "{" or dimension information.
CONTEXT: COPY some_table, line 1, column numbers: "'{1,2,3}'"

我该怎么办?

此外,了解为什么第一个代码不会引发错误也很有趣。

最佳答案

This code doesn't throw an error, but It doesn't write anything to the table.

如果您提交交易,代码运行良好:

cursor.close()
connection.commit()

关于python - 使用 psycopg2 复制到带有 ARRAY INT 列的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53492660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com