【问题标题】:With Pandas, how do I use to_sql to insert a cell with lists into a Postgresql database?使用 Pandas,如何使用 to_sql 将带有列表的单元格插入 Postgresql 数据库?
【发布时间】:2021-09-29 06:38:41
【问题描述】:

我不知道如何将包含列表的列插入 Postgresql 数据库。我知道这在理论上是可行的,因为存在像 BIGINT[] 这样的数据类型,而其他 SQL 变体则不存在。

这是我的代码:

import datetime
import json
import pandas as pd
import pymysql.cursors

from sqlalchemy import create_engine
                            
mock_data = {}
mock_data['a'] = 'HELLO'
mock_data['b'] = {
    'c' : {
        'd' : True,
# NOTE: If you replace this with 'e' : '', instead of the list, it works fine.
        'e' : []
    },
    'f' : 'TESTING'
}

df = pd.json_normalize(mock_data)

engine = create_engine("postgresql://postgres:ABCDEFG@localhost:5432/testing")
con = engine.connect()

table_name = 'testing-db'

try:
    frame = df.to_sql(con=con, name=table_name, index=False, if_exists='replace')
    display(frame)
except ValueError as vx:
    print(vx)
except Exception as ex:   
    print(ex)
else:
    print("Table %s created successfully."%table_name);   
finally:
    connection.close()

上面的代码失败了,因为 'e' : []。 Python/Pandas 不报告失败,但我看不到在 Postgres 中更新的表。但是,如果您将列表更改为空字符串,如下所示: 'e' : '' postgres 数据库已更新。我不知道如何使用 Pandas 将列表插入 Postgres 数据库。任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas postgresql


    【解决方案1】:

    您不能在 SQL 数据库单元中插入列表,因为它会破坏规范化参数。

    你可以做的是:

    1. 将您的列表转换为 json 字符串对象(或 XML)
    2. 创建一个新表格,其中包含单个单元格中的元素并引用原始表格。

    例如:如果您有一个长度固定的列表字段

    list_field = [Element_A, Element_B, Element_C]
    

    您可以创建另一个具有 4 列(1 个主列和 3 个列)的表 list_data。在此处存储您的列表数据并使用它来引用您的原始表。这使您可以更有效地处理数据值,并且是这样做的传统方式。

    但是,如果您有可变长度的 list_data,则将其转储到 json 中并将其存储为 json 或字符串对象会更有效。但请记住,这样做意味着您必须在每次提取时预处理响应以获取所需的数据。

    【讨论】:

      【解决方案2】:

      我想出了解决办法。我必须使用dtypes 字段才能使其工作。所以这是我必须做出的改变:

      dtypes = {
          'a' : types.TEXT(),
          'b.c.d' : types.BOOLEAN(),
          'b.c.e' : types.ARRAY(types.BIGINT()),
          'b.f' : types.TEXT() 
      }
      ...
          frame = df.to_sql(con=con, 
                            name=table_name, 
                            index=False, 
                            dtype=dtypes,
                            if_exists='replace')
      

      【讨论】:

        猜你喜欢
        • 2018-05-12
        • 2017-04-01
        • 2020-10-21
        • 2015-08-18
        • 2019-05-24
        • 2021-12-14
        • 1970-01-01
        • 2020-12-01
        • 2020-02-10
        相关资源
        最近更新 更多