pandas将空值入库

如果数据库表中有很多空值,那么pandas在将数据取出来后,在python中会以"None"显示,但是pandas会认为"None"值为字符串,所以当空值所在字段为整数int或bigint类型时,pandas会抛出异常(字符串类型字段则不会),因此需要将取出的DataFrame数据中的空值所在字段进行类型转换后,再赋予空值数值,然后再将填充的数值转换成pandas识别的空值nan(需转换的字段类型为整数,字符串类型的不需要)


import numpy as np
import pandas as pd


for
col in df.columns: if str(df[col].dtypes) == 'float64' or str(df[col].dtypes) == 'int64': # print(col) df[col] = df[col].fillna(-1) df[col] = df[col].astype(int) df[col] = df[col].astype(str) df[col] = df[col].replace('-1', np.nan)

df.to_sql()
原文地址:https://www.cnblogs.com/ttyypjt/p/13954300.html