python - Pandas to_sql() 插入索引

标签 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) 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/

相关文章:

python - 为什么不立即释放匿名 (C)Python 对象?

python - 我什么时候应该(不)想在我的代码中使用 pandas apply() ?

memory - Scikit 和 Pandas : Fitting Large Data

python - 根据条件插入索引新行

sql-server - SQLAlchemy 和 mssql+pymssql 密码在一定长度后失败

python - 无法使用 athena 数据库连接到超集

python - SQLAlchemy - 编写子计数的混合方法

python - 如何使 Python 3.4 c_char_array 将字符串读取为两个字节?

python:将特定索引处的行从一个数据帧插入到另一个数据帧

python - 如何将日期与 Pandas 中的字符串进行比较?