作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将数据帧批量插入到我的 postgres dB 中。我的数据框中的某些列是带有 NaT
的日期类型作为空值。 PostgreSQL 不支持,我尝试替换 NaT
(使用 Pandas )与其他 NULL 类型标识,但在我的插入过程中不起作用。
我用过 df = df.where(pd.notnull(df), 'None')
替换所有 NaT
s,由于数据类型问题而不断出现的错误示例。
Error: invalid input syntax for type date: "None"
LINE 1: ...0,1.68757,'2022-11-30T00:29:59.679000'::timestamp,'None','20...
我的驱动程序和对 postgresql dB 的插入语句:
def execute_values(conn, df, table):
"""
Using psycopg2.extras.execute_values() to insert the dataframe
"""
# Create a list of tupples from the dataframe values
tuples = [tuple(x) for x in df.to_numpy()]
# Comma-separated dataframe columns
cols = ','.join(list(df.columns))
# SQL quert to execute
query = "INSERT INTO %s(%s) VALUES %%s" % (table, cols)
cursor = conn.cursor()
try:
extras.execute_values(cursor, query, tuples)
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print("Error: %s" % error)
conn.rollback()
cursor.close()
return 1
print("execute_values() done")
cursor.close()
关于我的数据框的信息:对于这种情况,罪魁祸首仅是日期时间列。
最佳答案
你在重新发明轮子。只需使用 Pandas 的 to_sql方法,它会
NaT
值。 method="multi"
为您提供与 psycopg2 相同的效果
execute_values
.
from pprint import pprint
import pandas as pd
import sqlalchemy as sa
table_name = "so64435497"
engine = sa.create_engine("mssql+pyodbc://@mssqlLocal64", echo=False)
with engine.begin() as conn:
# set up test environment
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
conn.execute(
sa.text(
f"CREATE TABLE {table_name} ("
"id int identity primary key, "
"txt nvarchar(50), "
"txt2 nvarchar(50), dt datetime2)"
)
)
df = pd.read_csv(r"C:\Users\Gord\Desktop\so64435497.csv")
df["dt"] = pd.to_datetime(df["dt"])
print(df)
"""console output:
dt txt2 txt
0 2020-01-01 00:00:00 foo2 foo
1 NaT bar2 bar
2 2020-01-02 03:04:05 baz2 baz
"""
# run test
df.to_sql(
table_name, conn, index=False, if_exists="append", method="multi"
)
pprint(
conn.execute(
sa.text(f"SELECT id, txt, txt2, dt FROM {table_name}")
).fetchall()
)
"""console output:
[(1, 'foo', 'foo2', datetime.datetime(2020, 1, 1, 0, 0)),
(2, 'baz', 'baz2', None),
(3, 'bar', 'bar2', datetime.datetime(2020, 1, 2, 3, 4, 5))]
"""
关于python - 如何将 Pandas NaT 日期时间值正确插入到我的 postgresql 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64435497/
我是一名优秀的程序员,十分优秀!