gpt4 book ai didi

python - Pandas to_sql() 插入索引

转载 作者:太空狗 更新时间:2023-10-29 21:18:07 27 4
gpt4 key购买 nike

我正在使用 Pandas 0.18.1,在摆弄这段代码时,

import pd

def getIndividualDf(item):
var1 = []
# ... populate this list of numbers
var2 = []
# ... populate this other list of numbers

newDf = pd.DataFrame({'var1': var1, 'var2': var2})
newDf['extra_column'] = someIntScalar
yield newDf

dfs = []
for item in someList:
dfs.append(getIndividualDf(item))

resultDf = pd.concat(dfs)
resultDf['segment'] = segmentId # this is an integer scalar

from sqlalchemy import create_engine
engine = create_engine('postgresql://'+user+':'+password+'@'+host+'/'+dbname)
resultDf.reset_index().to_sql('table_name', engine, schema="schema_name", if_exists="append", index=False)

我遇到了这个异常:

(psycopg2.ProgrammingError) column "index" of relation "table_name" does not exist

确实,表中没有这样的列,只是因为数据框中没有这样的显式列。这就是为什么它很奇怪。

运行

print(list(resultDf))

就在 to_sql() 调用之前,产生

['var1', 'var2', 'extra_column', 'segment']

to_sql() 调用中删除 index=False 会将错误更改为:

(psycopg2.ProgrammingError) column "level_0" of relation "table_name" does not exist

我很疑惑。如何删除 index 列?

更新
print(resultDf.head()) 产生了以下信息:

     var1       var2  extra_column  segment
0 8 0.101653 2077869737 201606
1 9 0.303694 2077869737 201606
2 10 0.493210 2077869737 201606
3 11 0.661064 2077869737 201606
4 12 0.820924 2077869737 201606

最佳答案

在写入 sql 之前不需要重置索引,例如:

resultDf.to_sql('table_name', engine, schema="schema_name", if_exists="append", index=False)

关于python - Pandas to_sql() 插入索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942357/

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