熊猫的to_sql索引从1开始

大卫542

我有以下将数据帧转储到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)))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章