gpt4 book ai didi

mysql - 将特定 Dataframe 列插入到多个 MySQL 表中

转载 作者:行者123 更新时间:2023-11-29 15:53:37 24 4
gpt4 key购买 nike

希望有人能解答这个问题。我正在使用 Python 3.7 和 pandas 以及 MySQL 8.0 CE(使用 sqlalchemy 和 MySQLdb)。

我不确定如何从单个数据帧插入特定列并将其插入到同一数据库内的多个 MySQL 表中。

原始数据框(df.head):

      date      time    price   discount
0 11/6/2019 7:10 4.56 0.25
1 11/6/2019 7:15 5.01 0.26
2 11/6/2019 7:20 4.87 0.25
3 11/6/2019 7:25 4.54 0.23

当我使用我的代码(如下所示)时,它会发送到“摘要”MySQL 表:

  date      time    price   discount
11/6/2019 7:10 4.56 0.25
11/6/2019 7:15 5.01 0.26
11/6/2019 7:20 4.87 0.25
11/6/2019 7:25 4.54 0.23

最终目标 - 在同一数据库内的单独 MySQL 表中插入价格和折扣,例如:

MySQL 表 1 - '价格'

  date      time    price   
11/6/2019 7:10 4.56
11/6/2019 7:15 5.01
11/6/2019 7:20 4.87
11/6/2019 7:25 4.54

MySQL 表 2 - “折扣”

  date      time   discount
11/6/2019 7:10 0.25
11/6/2019 7:15 0.26
11/6/2019 7:20 0.25
11/6/2019 7:25 0.23

这是我原来的 .py 代码,如果我需要将整个数据帧插入到一个名为“summary”的表中,它就可以工作:

import pandas as pd
import numpy as np
import MySQLdb
from sqlalchemy import create_engine

df = pd.read_csv('pricing_1.csv')
engine = create_engine('mysql+mysqldb://root:python@localhost:3306/testdb2', echo = False)

df.to_sql(name = 'summary', con=engine, if_exists = 'append', index = True)

在在这里发布这个问题之前,我已经尝试过 Google,但不幸的是找不到任何有用的东西 - 也许这与我对 MySQL 工作原理的理解有关?

非常感谢有人用一些 URL 文章或理论来指导我!谢谢!

最佳答案

  1. 单独的折扣和价格数据框。
  2. discount_df = df[['日期','时间','折扣']]
  3. price_df = df[['日期','时间','价格']]
  4. discount_df.to_sql(name = 'discount', con=engine, if_exists = 'append', index = True)
  5. price_df.to_sql(name = 'price', con=engine, if_exists = 'append', index = True)

这样就可以向两个表中插入数据了。

关于mysql - 将特定 Dataframe 列插入到多个 MySQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617033/

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