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

2024-10-02 00:39:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用python中的psycopg2将一些列从名为temporarytable的表复制到另一个名为scalingData的列。在

scalingData是熊猫数据帧。数据帧包含来自城市的数据,例如:nameOfCitiespopulation,等等

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

dataframe的每一列都有不同种类的数据,例如'int64''float64'或{}。在

这里是Jupyter的屏幕截图

enter image description here

^{pr2}$

我的问题是,如果我查看scalingData,那么只复制第一列,而其他列是空的。在

下面是查询后pgAdmin中表的屏幕截图:

另外,如果我复制第二列作为第一列,它可以工作,但是其他列也会失败。在


Tags: csvthe数据dataframeread屏幕ismyfile
2条回答

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

您需要首先为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,但只是猜测一下问题的来源:

"""INSERT INTO "scalingData" ("%s") SELECT "%s" FROM temporarytable"""

。。。将"%s"位转换为"foo, bar, baz",而不是"foo", "bar", "baz"。在

换言之,您应该删除语句中不需要的双引号,改为转义各个列名。在

在PG中使用双引号来引用标识符。实际上,可以有一个名为"foo, bar, baz"的表或列,如果在语句中使用PG总是在双引号之间,那么PG就可以正常工作了。在

相关问题 更多 >

    热门问题