[英]Pandas to_sql index starting at 1
我有以下内容可以将数据帧转储到 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)))
创建一个数字索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.