简体   繁体   中英

Pandas to_sql index starting at 1

I have the following to dump a dataframe into SQL:

summary_df.to_sql('table', con=self.avails_conn, if_exists='replace', index_label='id')

However, the id field is autoincrementing and needs to start at 1 (not 0 ). Is there a way to do this in the to_sql method? Or do I need to update the index before dumping it? If so, how would I do that?

Correct, by setting the index of your dataframe prior to exporting to SQL your table will have an index incrementing from one.

import pandas as pd
import sqlite3

conn = sqlite3.connect('example.db')
df = pd.DataFrame({'month': [1, 4, 7, 10],
                   'year': [2012, 2014, 2013, 2014],
                   'sale': [55, 40, 84, 31]})

df.index += 1  # <- increment default index by 1
df.to_sql("second_table", conn)
c = conn.cursor()
for row in c.execute("SELECT * FROM second_table"):
    print(row)

conn.close()

#  (1, 1, 2012, 55)
#  (2, 4, 2014, 40)
#  (3, 7, 2013, 84)
#  (4, 10, 2014, 31)

If you have a different index you can create a numeric one using df = df.set_index(list(range(1, len(df)+1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM