【问题标题】:Insert pandas DataFrame() into an MySQL table raises ProgrammingError将 pandas DataFrame() 插入 MySQL 表会引发 ProgrammingError
【发布时间】:2021-06-27 23:22:15
【问题描述】:

给定一个数据框 (df),其中 1 列的所有行都包含一个列表,基本上相应的列可以看作是一个列表列表。其余列是strintbool。第一行 (df.iloc[0]) 打印以下内容:

name                                  John
isMale                                True
age                                     30
hobbies  ['hiking', 'gaming', 'reading', …
Name: 0, dtype: object

这是我的代码:

engine = create_engine('mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}'.format(**config))
df.to_sql(name='test', con=engine, if_exists='append', index=True)

上面执行:

[SQL: INSERT INTO test(`name`, `isMale`, age, hobbies) VALUES (%(name)s, %(isMale)s, %(age)s, %(hobbies)s)]
[parameters: {'index': 0, 'name': 'John', 'isMale': 1, 'age': 50, 'hobbies': ['hiking', 'gaming', 'reading', ... (84 characters truncated) ...  ]}]

我想将df 插入到 mysql 表中,但 sqlalchemy 引发以下异常:

Traceback (most recent call last):
        return getattr(self, "_{0}_to_mysql".format(type_name))(value)
    AttributeError: 'MySQLConverter' object has no attribute '_list_to_mysql'

The above exception was the direct cause of the following exception:
    sqlalchemy.exc.ProgrammingError: (mysql.connector.errors.ProgrammingError) Failed processing pyformat-parameters; Python 'list' cannot be converted to a MySQL type

  • 有没有办法将 python 列表作为单元格值插入?
  • 如何将 python 列表转换为有效的 MySQL 类型?

注意

  • hobbies 列的格式为text utf8_general_ci

参考文献

【问题讨论】:

    标签: python mysql pandas dataframe sqlalchemy


    【解决方案1】:

    尝试将其全部转换为常规字符串。只需在您的姓名列上应用 lambda 函数。例如:

    df = pd.DataFrame({'a':[1,2,3,4], 'b':[['a', 'b','v'], ['s', 'e','r'], ['a', 'j','k'], ['f','g','d']]})
    
    df.b.apply(lambda x: ", ".join(x))
    Out[31]: 
    0    a, b, v
    1    s, e, r
    2    a, j, k
    3    f, g, d
    Name: b, dtype: object
    

    字符串肯定可以在 sql 中正常工作。

    【讨论】:

    • 感谢您指出@pavel 我完全跳过了将列表转换为有效的str 类型。这对我有用df['hobbies'] = df['hobbies'].apply(lambda x: str(x))
    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 2020-08-05
    • 2020-10-04
    • 2018-08-13
    • 2017-06-04
    • 2013-07-22
    • 2014-08-29
    • 2020-02-21
    相关资源
    最近更新 更多