pangres python: IndexError: All index levels must be named

Viewed 921

I would like to do an upsert in my sql database using "pangres", however it returns this error

raise IndexError("All index levels must be named!")
IndexError: All index levels must be named!

what should I do?

df = pd.read_excel('personne.xlsx')
upsert(engine=engine,
       df=df,
       table_name='personne',
       if_row_exists='update')
1 Answers

Name the df index or set a column as the index. See the Pangres wiki.

For dfs with df['unique_id'] to use as the primary key:

# create SQL table with first df, set if_exists as needed
df.to_sql('table_name', engine, if_exists = 'fail', index = False)

with engine.connect() as con: # set df['unique_id'] as primary key in SQL
    con.execute("ALTER TABLE table_name ADD PRIMARY KEY (unique_id);")

# set df2['unique_id'] as index
df2.set_index(['unique_id'], inplace = True, drop = False)
pangres.upsert(engine, df2, 'table_name', if_row_exists ='update')
Related