Home > Enterprise >  Why is pandas inserting index to my to_sql even if i drop it?
Why is pandas inserting index to my to_sql even if i drop it?

Time:11-27

I'm not sure what I'm doing wrong. I have a dataframe:

    ticker  year    GHG         provided
0   SECO.AB 2020    190748000   True
1   MT.NA   2020    182300000   True
2   HOLN.SW 2020    129000000   True

but when I try to insert into my DB I get the index as a table:

df[['ticker', 'year', 'GHG','provided']].to_sql('tmp_GHG', engine, if_exists='replace', method='multi')

I have tried:

df.reset_index(drop=True)

but it didn't make a difference and as you can see above I specified the column names to insert but it still didn't work.

Basically when I insert, in my DB I see a column called index with 0,1,2... In theory, I could drop it but I don't want it inserted there to begin with.

what can I do?

CodePudding user response:

Set one of the columns as index before upload.

Try

df= df.set_index('ticker')

An alternative would be hiding the index before upload.

Can also try Try

df.style.hide_index()

CodePudding user response:

You can use df.to_sql(name,conn,index=False), and the index=False there will make it so it doesn't import any index.

  • Related