Python实现Excel转PostgreSQL时,如何保留NA值而非转为NULL?
解决Excel转PostgreSQL时保留NA值的问题
你的代码里,pandas默认会把Excel中的"NA"识别成缺失值(NaN),写入PostgreSQL时就会自动转换成NULL。要保留"NA"字符串,可通过以下两种方式修改代码:
方法1:读取Excel时阻止"NA"被解析为缺失值
给pd.read_excel添加参数,禁用默认的缺失值识别规则,让"NA"以普通字符串形式保留:
try: # 添加keep_default_na=False,避免"NA"被解析为NaN df = pd.read_excel(r"D:\Projects\MLT\File.xlsx", keep_default_na=False) print(df.shape[0]) except Exception as error: print(error,'Unable to Read the Data') # Create Alchemy Engine to write the data of dataframe on table try: engine = create_engine('params') df.to_sql('table',engine,if_exists='append',schema='schema_name', index=False) except Exception as error: print(error,'Unable to Insert the Data')
方法2:读取后将缺失值替换回"NA"(适用于仅还原"NA"的场景)
如果Excel里还有其他需要保留的缺失值(比如空单元格),只把被识别成NaN的"NA"还原成字符串:
try: df = pd.read_excel(r"D:\Projects\MLT\File.xlsx") # 将所有NaN替换为字符串"NA" df = df.fillna("NA") print(df.shape[0]) except Exception as error: print(error,'Unable to Read the Data') # Create Alchemy Engine to write the data of dataframe on table try: engine = create_engine('params') df.to_sql('table',engine,if_exists='append',schema='schema_name', index=False) except Exception as error: print(error,'Unable to Insert the Data')
关键注意点
- 确保PostgreSQL目标表的对应列是字符串类型(如
varchar/text),不然写入"NA"字符串会因类型不匹配报错。 - 如果目标列是数值型,没法存储字符串"NA",要么把列类型改成字符串,要么用特定数值(比如-999)代替"NA"做标记。
内容的提问来源于stack exchange,提问作者kashif ashraf
相关产品推荐
相关产品推荐

