Python psycopg2在PostgreSQL表的某些行中插入NULL [英] Python psycopg2 insert NULL in some rows in postgresql table
本文介绍了Python psycopg2在PostgreSQL表的某些行中插入NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在某些行中有一个带有NULL值的Python数据帧,当插入到postgresql中时,datetype列中的一些null变成了'NaT'字符串或'NaN',我喜欢它是一个真正的NULL,这没什么细胞。
I have a Python dataframe with NULL value in some rows, while inserting to postgresql, some null in datetype column turns into 'NaT' string or 'NaN', I like it to be a real NULL , which is nothing in that cell.
插入前的示例数据帧
import psycopg2
import pandas as pd
import numpy as np
conn=psycopg2.connect(dbname= 'myDB', host='amazonaws.com',
port= '2222', user= 'mysuser', password= 'mypass')
cur = conn.cursor()
df= pd.DataFrame({ 'zipcode':[1,np.nan,22,88],'city':['A','h','B',np.nan]})
subset = df[['zipcode', 'city']]
data = [tuple(x) for x in subset.values]
records_list_template = ','.join(['%s'] * len(data))
insert_query = 'insert into public.MyTable (zipcode, city) values {}'.format(records_list_template)
cur.execute(insert_query, data)
conn.commit()
postgresql中的结果表
result in postgresql table
以下预期结果
推荐答案
您可以按以下方式将 NaN
转换为 None
:
You can convert NaN
to None
in this way:
df= pd.DataFrame({
'zipcode':[1,np.nan,22,88],
'city':['A','h','B',np.nan],
'date':['2019-01-01','2019-01-02',pd.NaT,pd.NaT]})
df['date'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else None for d in df['date']]
subset = df.where((pd.notnull(df)), None)
请参见 DataFrame。
这篇关于Python psycopg2在PostgreSQL表的某些行中插入NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文