pandas to_sql すべての列を nvarchar として 質問する

pandas to_sql すべての列を nvarchar として 質問する

さまざまな列名で動的に作成される pandas データフレームがあります。それらを sql にプッシュしようとしていますが、デフォルトのデータ型「テキスト」として mssqlserver にプッシュしたくありません (なぜこれがデフォルトなのか説明できる人はいますか? より一般的なデータ型を使用する方が理にかなっているのではないでしょうか?)

すべての列のデータ型を指定する方法をご存知の方はいらっしゃいますか?

column_errors.to_sql('load_errors',push_conn, if_exists = 'append', index = False, dtype = #Data type for all columns#)

dtype引数は辞書を受け取りますが、列が何になるかわからないため、すべてを「sqlalchemy.types.NVARCHAR」に設定するのは困難です。

私がやりたいことはこれです:

column_errors.to_sql('load_errors',push_conn, if_exists = 'append', index = False, dtype = 'sqlalchemy.types.NVARCHAR')

すべての列タイプを最も適切に指定する方法についての助言や理解をいただければ幸いです。

ベストアンサー1

使用するにはdタイプ、各データフレームの列に対応するキーを持つ辞書を渡しますsqlalchemy 型キーを実際のデータフレームの列名に変更します。

import sqlalchemy
import pandas as pd
...

column_errors.to_sql('load_errors',push_conn, 
                      if_exists = 'append', 
                      index = False, 
                      dtype={'datefld': sqlalchemy.DateTime(), 
                             'intfld':  sqlalchemy.types.INTEGER(),
                             'strfld': sqlalchemy.types.NVARCHAR(length=255)
                             'floatfld': sqlalchemy.types.Float(precision=3, asdecimal=True)
                             'booleanfld': sqlalchemy.types.Boolean})

dtype事前に列名や型がわからない場合でも、この辞書を動的に作成できる場合があります。

def sqlcol(dfparam):    
    
    dtypedict = {}
    for i,j in zip(dfparam.columns, dfparam.dtypes):
        if "object" in str(j):
            dtypedict.update({i: sqlalchemy.types.NVARCHAR(length=255)})
                                 
        if "datetime" in str(j):
            dtypedict.update({i: sqlalchemy.types.DateTime()})

        if "float" in str(j):
            dtypedict.update({i: sqlalchemy.types.Float(precision=3, asdecimal=True)})

        if "int" in str(j):
            dtypedict.update({i: sqlalchemy.types.INT()})

    return dtypedict

outputdict = sqlcol(df)    
column_errors.to_sql('load_errors', 
                     push_conn, 
                     if_exists = 'append', 
                     index = False, 
                     dtype = outputdict)

おすすめ記事