pandas转mysql特定列_pandas.DataFrame.to_sql操作mysql 指定数据库表的列类型

to_sql向不存在的表时候,默认创建一个新表,这时新表的列类型可能并不是你期望的。

可以在执行 to_sql 方法时,将映射好列名和指定类型的 dict 赋值给 dtype 参数即可上,其中对于 MySQL 表的列类型可以使用 SQLAlchemy 包中封装好的类型

from sqlalchemy.types import NVARCHAR, Float, Integer

dtypedict = {

‘str’: NVARCHAR(length=255),

‘int’: Integer(),

‘float’ Float()

df.to_sql(name=’test’, con=con, if_exists=’append’, index=False, dtype=dtypedict)

也可以创建映射函数:

def mapping_df_types(df):

dtypedict = {}

for i, j in zip(df.columns, df.dtypes):

if “object” in str(j):

dtypedict.update({i: NVARCHAR(length=255)})

if “float” in str(j):

dtypedict.update({i: Float(precision=2, asdecimal=True)})

if “int” in str(j):

dtypedict.update({i: Integer()})

return dtypedict

df = pd.DataFrame([[‘a’, 1, 1, 2.0, datetime.now(), True]],

columns=[‘str’, ‘int’, ‘float’, ‘datetime’, ‘boolean’])

dtypedict = mapping_df_types(df)

df.to_sql(name=’test’, con=con, if_exists=’append’, index=False, dtype=dtypedict)

Original: https://blog.csdn.net/weixin_34494211/article/details/114906556
Author: ll小喷油
Title: pandas转mysql特定列_pandas.DataFrame.to_sql操作mysql 指定数据库表的列类型

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/743410/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球