簡體   English   中英

將 pandas DataFrame() 插入 MySQL 表會引發 ProgrammingError

[英]Insert pandas DataFrame() into an MySQL table raises ProgrammingError

給定一個 dataframe ( df ),其中 1 列的所有行都包含一個列表,基本上相應的列可以看作是列表的列表。 列的 rest 是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

參考資料

嘗試將其全部轉換為常規字符串。 只需在您的姓名列上應用 lambda function 即可。 例如:

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 配合使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM