gpt4 book ai didi

python - Postgresql:如何将多个列从一个表复制到另一个表?

转载 作者:行者123 更新时间:2023-11-29 12:54:47 35 4
gpt4 key购买 nike

我正在尝试从名为 temporarytable 的表中复制一些列另一个叫scalingData使用 psycopg2python .

scalingData是 Pandas 数据框。数据框包含来自城市的数据,例如:nameOfCities , population

scalingData = pd.read_csv('myFile.csv')  ## 'myFile.csv' is the datasource

dataframe的每一列都有不同类型的数据,例如'int64' , 'float64''O' .

这里是 Jupyter 的屏幕截图

enter image description here

import psycopg2 as ps
## Populate table scalingData
tmp = scalingData.dtypes
con = None
con = ps.connect(dbname = 'mydb', user='postgres', host='localhost', password='mypd')
con.autocommit = True
cur = con.cursor()
for i in range(0,5):
j = header[i]
stat = """ ALTER TABLE "scalingData" ADD COLUMN "%s" """%j
if tmp[i] == 'int64':
stat = stat+'bigint'
if tmp[i] == 'float64':
stat = stat+'double precision'
if tmp[i] == 'O':
stat = stat+'text'
### Add Column
cur.execute(stat)
stat1 = """INSERT INTO "scalingData" ("%s") SELECT "%s" FROM temporarytable"""%(j,j)
### Copy Column
cur.execute(stat1)
cur.close()
con.close()

我的问题是,如果我查看 scalingData仅复制第一列,其他列为空。

这是来自 pgAdmin 的表格截图查询之后:

此外,例如,如果我将第二列复制为第一列,它可以正常工作,但其他列也会失败。

最佳答案

发生这种情况是因为您向新表添加了 1 个字段,而不是仅在设置该字段的情况下插入数据,并且您执行了 5 次。因此,您实际上应该看到只有 1 个字段设置的原始表的 5 个副本。

您需要先为您的scalingData 表设置结构,然后插入包含所有字段的所有记录。

这是代码(不是 Python 开发人员):

import psycopg2 as ps
## Populate table scalingData
tmp = scalingData.dtypes
con = None
con = ps.connect(dbname = 'mydb', user='postgres', host='localhost', password='mypd')
con.autocommit = True
cur = con.cursor()
for i in range(0,5):
j = header[i]
stat = """ ALTER TABLE "scalingData" ADD COLUMN "%s" """%j
if tmp[i] == 'int64':
stat = stat+'bigint'
if tmp[i] == 'float64':
stat = stat+'double precision'
if tmp[i] == 'O':
stat = stat+'text'
### Add Column
cur.execute(stat)

fieldsStr = '"' + '", "'.join([header]) + '"' ### will return "header1", "header2", ... , "header5"
stat1 = """INSERT INTO "scalingData" (%s) SELECT %s FROM temporarytable"""%(fieldsStr,fieldsStr)
### Copy Table
cur.execute(stat1)

cur.close()
con.close()

关于python - Postgresql:如何将多个列从一个表复制到另一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46224135/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com