我有一个 pandas.DataFrame
,其中的列具有不同的数据类型,如 object,int64 等。
我已经创建了一个具有适当数据类型的 postgresql 表。我想将所有数据框中的数据插入到 postgresql 表中。我应该如何处理?
注意:pandas 中的数据来自另一个源,因此数据类型不是由我手动指定的。
我有一个 pandas.DataFrame
,其中的列具有不同的数据类型,如 object,int64 等。
我已经创建了一个具有适当数据类型的 postgresql 表。我想将所有数据框中的数据插入到 postgresql 表中。我应该如何处理?
注意:pandas 中的数据来自另一个源,因此数据类型不是由我手动指定的。
lg.debug('table gets extended with the columns: '+",".join(dataframe.dtypes))
#check whether we have to add a field
df_postgres={'object':'text','int64':'bigint','float64':'numeric','bool':'boolean','datetime64':'timestamp','timedelta':'interval'}
for col in dataframe.columns:
#convert the columns to postgres:
if str(dataframe.dtypes[col]) in df_postgres:
dbo.table_column_if_not_exists(self.table_name,col,df_postgres[str(dataframe.dtypes[col])],original_endpoint)
else:
lg.error('Fieldtype '+str(dataframe.dtypes[col])+' is not configured')
和创建列的函数:
def table_column_if_not_exists(self,table,name,dtype,original_endpoint=''):
self.query(query='ALTER TABLE '+table+' ADD COLUMN IF NOT EXISTS '+name+' '+dtype)
#make a comment when we know which source create this column
if original_endpoint!='':
self.query(query='comment on column '+table+'.'+name+" IS '"+original_endpoint+"'")
sqlalchemy
:from sqlalchemy import create_engine
engine = create_engine('postgresql://abc:def@localhost:5432/database')
df.to_sql('table_name', engine, if_exists='replace')
if_exists
选项选择要执行的操作。if_exists {‘fail’, ‘replace’, ‘append’}, default ‘fail’