Pandas to_sql()插入索引

时间:2017-05-12 16:21:17

标签: python pandas sqlalchemy

我正在使用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)列"索引" of relation" table_name"不存在

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

正在运行

print(list(resultDf))

to_sql()调用之前,产量

  

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

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

  

(psycopg2.ProgrammingError)列" level_0" of relation" table_name"不存在

我很困惑。如何摆脱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

1 个答案:

答案 0 :(得分:13)

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

index = arrDates.findIndex(x => x.elID=="newElement");