简体   繁体   English

用 pandas dataframe 替换 sqlite3 数据库表

[英]replace sqlite3 database table with pandas dataframe

My sqlite3 database look like the following:我的 sqlite3 数据库如下所示:

id     name
1      apple
2      orange
3      pear
4      bananna

Then I query each element from the database into a pandas dataframe.然后我将数据库中的每个元素查询成 pandas dataframe。

After that I merge the dataframe with a list.之后,我将 dataframe 与列表合并。

After that I sort the database element by the list.之后,我按列表对数据库元素进行排序。

conn = sqlite3.connect('db.sqlite3', isolation_level=None, detect_types=sqlite3.PARSE_COLNAMES)
df = pd.read_sql_query('select * from name', conn)

#I am getting the list .....

df["color"] = color #color is a list
df.sort_values(by=['color'], ascending=True, inplace=True)

How could I replace the original sqlite3 table with the sorted dataframe?我如何用排序后的 dataframe 替换原来的 sqlite3 表? I do not want to add the color column to the sqlite3 table.我不想将颜色列添加到 sqlite3 表中。

The correct answer:正确答案:

db.sort_values(by=['color'], ascending=True).drop('color',axis=1).to_sql("name",conn,if_exists='replace',index=False, index_label="id")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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