使用 copy_from 从 StringIO 加载数据帧到 Postgresql psycopg
Loading dataframe using copy_from from StringIO into Postgresql psycopg
我不知道如何解决这个问题。
我的代码看起来像
import pandas
import psycopg2
import io
from sqlalchemy import create_engine
#engine works
cursor = engine.raw_connection()
output = io.StringIO()
df.to_csv(output, sep=',', header=False, index=False)
output.seek(0)
contents = output.getvalue()
print(contents)
cursor.copy_from(output, table_name, sep=",", null="NULL")
connection.commit()
我的整数似乎被错误地解释了:
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "180.0" CONTEXT: COPY athletes, line 1, column height: "180.0"
这是内容示例:
135552,Jan (Johann-) Zybert (Siebert-),M,1908-01-01,NULL,NULL
135553,Galina Ivanovna Zybina (-Fyodorova),F,1931-01-01,168.0,80.0
135554,Bogusaw Zych,M,1952-01-01,182.0,82.0
135556,Bogusaw Stanisaw Zychowicz,M,1961-01-01,189.0,80.0
我该如何解决这个问题?
正如@Frank Heikens 所说,它与数据库中的字段有关,您可以将它们更改为十进制,或者像我所做的那样,您也可以调整数据框中的数据类型列。
Python pandas: output dataframe to csv with integers
def convert(x):
try:
return x.astype(int)
except:
return x
df = df.apply(convert)
谢谢大家
我不知道如何解决这个问题。
我的代码看起来像
import pandas
import psycopg2
import io
from sqlalchemy import create_engine
#engine works
cursor = engine.raw_connection()
output = io.StringIO()
df.to_csv(output, sep=',', header=False, index=False)
output.seek(0)
contents = output.getvalue()
print(contents)
cursor.copy_from(output, table_name, sep=",", null="NULL")
connection.commit()
我的整数似乎被错误地解释了:
psycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "180.0" CONTEXT: COPY athletes, line 1, column height: "180.0"
这是内容示例:
135552,Jan (Johann-) Zybert (Siebert-),M,1908-01-01,NULL,NULL
135553,Galina Ivanovna Zybina (-Fyodorova),F,1931-01-01,168.0,80.0
135554,Bogusaw Zych,M,1952-01-01,182.0,82.0
135556,Bogusaw Stanisaw Zychowicz,M,1961-01-01,189.0,80.0
我该如何解决这个问题?
正如@Frank Heikens 所说,它与数据库中的字段有关,您可以将它们更改为十进制,或者像我所做的那样,您也可以调整数据框中的数据类型列。
Python pandas: output dataframe to csv with integers
def convert(x):
try:
return x.astype(int)
except:
return x
df = df.apply(convert)
谢谢大家