gpt4 book ai didi

python - 如何将 Pandas NaT 日期时间值正确插入到我的 postgresql 表中

转载 作者:行者123 更新时间:2023-12-04 00:53:36 25 4
gpt4 key购买 nike

我想将数据帧批量插入到我的 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()
关于我的数据框的信息:对于这种情况,罪魁祸首仅是日期时间列。
enter image description here
这通常是如何解决的?

最佳答案

你在重新发明轮子。只需使用 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/

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