Pandas to_sql写入MSSQL时含空值的int列转为float64问题求助
解决WSL2下Pandas写入MSSQL时含空值整数列转为Float64的问题
问题根源
你的int_col_2列包含None,而Pandas原生int64类型不支持缺失值,因此该列会被自动转为float64。即使通过dtype参数指定SQL类型,读取时Pandas仍会因存在空值默认用float64解析,导致类型不符合预期。
解决方案
1. 将DataFrame列转为Pandas可空整数类型
先把int_col_2转为Pandas的Int64(大写I,支持空值的整数类型),确保DataFrame内的列类型正确,再写入数据库:
# 转换可空整数列 df['int_col_2'] = df['int_col_2'].astype('Int64') # 原有写入代码 connection_string = 'DRIVER={ODBC Driver 18 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password + ';Encrypt=no' connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string}) engine = create_engine(connection_url) df.to_sql('table', engine, if_exists='replace', index=False)
2. 修正dtype参数的拼写错误
你之前指定dtype时存在列名拼写错误(int_col1_1应为int_col_1),修正后结合类型转换使用,可进一步确保SQL端列类型正确:
from sqlalchemy.types import Integer, String df['int_col_2'] = df['int_col_2'].astype('Int64') df.to_sql( 'table', engine, if_exists='replace', index=False, dtype={ 'int_col_1': Integer(), 'int_col_2': Integer(), 'string_col': String() } )
3. 读取时指定可空整数类型(可选)
如果需要确保读取时直接得到Int64类型,可在read_sql中指定dtype:
df_read = pd.read_sql('SELECT * FROM table', engine, dtype={'int_col_2': 'Int64'})
原理说明
Pandas 1.5+已支持Int64类型与SQL的可空整数类型(如MSSQL的INT NULL)正确映射,转换列类型后,to_sql会将其正确写入为SQL端的可空整数列,后续读取时只要指定对应类型,就能避免自动转为float64。
内容的提问来源于stack exchange,提问作者ceej pie
相关产品推荐
相关产品推荐

