将 Pandas 数据框插入到 SQLite 表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53189071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert a pandas dataframe into a SQLite table
提问by Val10
So I have a dataframe imported from excel and an SQL Table with matching columns. So far I have been updating the table using the columns as lists:
所以我有一个从 excel 导入的数据框和一个带有匹配列的 SQL 表。到目前为止,我一直在使用列作为列表来更新表:
Schedule_Frame = DataFrame(Sheet_Schedule)
Column_ID=Schedule_Frame['ID']
Column_list=list(Column_ID)
for i in range(len(Column_list)):
miCursor.execute("UPDATE SCHEDULE SET ID=? WHERE rowid=?",(Column_list[i],i))
However, since what I have in SQLite is a table that matches my dataframe columns, I am sure that there is a way to update the whole SQLite table using my frame.
但是,由于我在 SQLite 中拥有的是一个与我的数据框列匹配的表,因此我确信有一种方法可以使用我的框架更新整个 SQLite 表。
Any ideas how to do it?
任何想法如何做到?
Thanks a lot!!
非常感谢!!
回答by mremes
I think you're using sqlite3
package to access your SQLite database. How about using SQLAlchemy– which operates well with Pandas' data structures – to access the database?
我认为您正在使用sqlite3
包来访问您的 SQLite 数据库。使用SQLAlchemy(它与 Pandas 的数据结构配合良好)访问数据库怎么样?
from sqlalchemy import create_engine
engine = create_engine('sqlite:///<replace_this_with_path_to_db_file>', echo=False)
Then doing:
然后做:
Schedule_Frame.to_sql('SCHEDULE', con=engine, if_exists='append')
Edit: Example code
编辑:示例代码
from sqlalchemy import create_engine
import pandas as pd
engine = sqlalchemy.create_engine('sqlite:///my.db', echo=False)
df = pd.DataFrame([[1,2],[1,2]], columns=['a', 'b'])
df.to_sql('mytable', con=engine, if_exists='append')
In sqlite3 CLI:
在 sqlite3 CLI 中:
sqlite> select * from 'mytable';
0|1|2
1|1|2
Resources:
资源: