Pandas将数据插入MySQL

2024-04-24 20:41:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Pandas(Python)将从.csv文件提取的数据列插入到MySQL中。

这是我到目前为止的代码。

import pandas as pd
from pandas.io import sql
from sqlalchemy import create_engine
engine = create_engine('mysql://username:password@localhost/dbname')
with engine.connect() as conn, conn.begin():

df = pd.read_csv('File.csv', usercols=['ID', 'START_DATE'], skiprows=skip)
print(df)

df.to_sql(con=con, name='Table1', if_exists='replace', flavor='mysql')

但是,它没有提到表1中的特定列名。。

我们怎么表达?


Tags: 文件csvfromimportpandasdfsqlas
2条回答

我觉得你的代码应该这样读

import pandas as pd
from pandas.io import sql
from sqlalchemy import create_engine

df = pd.read_csv('File.csv', usercols=['ID', 'START_DATE'], skiprows=skip)
print(df)

engine = create_engine('mysql://username:password@localhost/dbname')
with engine.connect() as conn, conn.begin():
    df.to_sql('Table1', conn, if_exists='replace')

但是,关于您的问题,除非我对panda的理解有误,否则无论目前有什么列,这些列都将被写入mysql表的同名列中。

如果需要不同的列名,则需要重命名数据框中的列名

或者使用the parameters, as mentioned

index : boolean, default True
Write DataFrame index as a column.

index_label : string or sequence, default None
Column label for index column(s). If None is given (default) and index is True, then the index names are used

这就是我在我的项目中所做的

 import pandas as pd
 import sqlalchemy
 engine = sqlalchemy.create_engine('mysql+pymysql://root:@localhost/pd_test')

 ratings = pd.read_csv('ratings2.csv', sep='\t', encoding='latin-1',
                  usecols=['user_id', 'movie_id', 'user_emb_id', 
 'movie_emb_id','rating'])

 ratings.to_sql('test', con=engine, if_exists='append',index=False,chunksize=1)

希望能帮上忙!!

相关问题 更多 >