我有以下方法将数据帧转储到 SQL 中:
summary_df.to_sql('table', con=self.avails_conn, if_exists='replace', index_label='id')
但是,id
字段是自动递增的,并且需要从 1
开始(而不是 0
)。有没有办法在 to_sql 方法中做到这一点?或者我需要在转储之前更新索引吗?如果是这样,我该怎么做?
最佳答案
正确,通过在导出到 SQL 之前设置数据帧的索引,您的表的索引将从 1 开始递增。
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)
如果您有不同的索引,您可以使用 df = df.set_index(list(range(1, len(df)+1)))
创建一个数字索引
关于python - Pandas to_sql 索引从 1 开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64472061/