将特定的数据框列插入多个MySQL表

时间:2019-06-16 07:41:20

标签: mysql python-3.x pandas

希望有人可以启发我这个问题。我正在将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 个答案:

答案 0 :(得分:0)

  1. 分别折扣和价格数据框。
  2. discount_df = df[['date','time','discount']]
  3. price_df = df[['date','time','price']]
  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)

通过这种方式,您可以将数据插入两个表中。