python - Pandas to_sql 索引从 1 开始

标签 python pandas

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

相关文章:

python - pymunk 更新了形状过滤器的使用

python - 在至少 'x' 列中包含非零值的最大行集

python - Python 有类似 Java 的匿名内部类的东西吗?

python - 如何重复数据帧的某些行?

python - 如何处理 pandas 数据框中非常小的(-322 阶) float 值?

python - 艰难地学习 Python 练习 48 帮助

python - 运行进程,不要等待

python - 用 Pandas 分块将唯一行写入 CSV

python - 如何在 Pandas 数据框中切换列行

python - 连接两个 Pandas 数据框并生成并排条形图?