Python 通过sqlquery比较pandas dataframe和sqlite表
我有一个包含以下列和1000行的sqlite数据库Python 通过sqlquery比较pandas dataframe和sqlite表,python,sqlite,pandas,Python,Sqlite,Pandas,我有一个包含以下列和1000行的sqlite数据库 con.execute('CREATE TABLE "table" (Fruit TEXT, Texture TEXT, Code TEXT, Buy TEXT )' 我想将一个pandas.Dataframe与这个表进行比较,如果sqlite“code”列中的值不在df['code']中,那么用“Yes”一词更新sqlite“Buy” 最初我尝试使用下面的代码查看是否可以从df['code']获取所有结果以打印它是否存在,然后我可以在sql
con.execute('CREATE TABLE "table" (Fruit TEXT, Texture TEXT, Code TEXT, Buy TEXT )'
我想将一个pandas.Dataframe
与这个表进行比较,如果sqlite“code”
列中的值不在df['code']
中,那么用“Yes”一词更新sqlite“Buy”
最初我尝试使用下面的代码查看是否可以从df['code']
获取所有结果以打印它是否存在,然后我可以在sqlite查询中添加NOT
以翻转结果,但目前,下面的代码打印出1000行空列表,偶尔打印出一些代码
for each_code in df['Code']:
z = con.execute('SELECT EXISTS(SELECT 1 FROM "table" WHERE Code IN ({c}))'
.format(c=each_code)).fetchall()
print(z)
不知道我的错误在哪里?我考虑在数据库级别这样做,因为这样可能会更快 假设我们有以下SQLite表:
sqlite> select * from tab;
Fruit Texture Code Buy
---------- ---------- ---------- ----------
apple code1
orange code2
mango code3
banana code4
peach code5
以及以下各项:
In [37]: df
Out[37]:
Code
0 code1
1 code3
2 code5
3 code7
我会用以下方法来做:
首先将DF保存到具有不同表名的同一SQLite文件中:
import sqlite3
con = sqlite3.connect('d:/temp/a.db')
df.to_sql('tmp', con, index=False)
结果(SQLite):
现在,我们可以直接在SQLite中高效地更新选项卡表:
sqlite> update tab set buy='Yes' where not exists (select 1 from tmp where tmp.code=tab.code);
sqlite> select * from tab;
Fruit Texture Code Buy
---------- ---------- ---------- ----------
apple code1
orange code2 Yes
mango code3
banana code4 Yes
peach code5
当然,您可以在Python中执行最后一步:
con.execute("update tab set buy='Yes' where not exists (select 1 from tmp where tmp.code=tab.code)")
# optional clean up
con.execute("drop table tmp")
con.commit()
假设我们有以下SQLite表:
sqlite> select * from tab;
Fruit Texture Code Buy
---------- ---------- ---------- ----------
apple code1
orange code2
mango code3
banana code4
peach code5
以及以下各项:
In [37]: df
Out[37]:
Code
0 code1
1 code3
2 code5
3 code7
我会用以下方法来做:
首先将DF保存到具有不同表名的同一SQLite文件中:
import sqlite3
con = sqlite3.connect('d:/temp/a.db')
df.to_sql('tmp', con, index=False)
结果(SQLite):
现在,我们可以直接在SQLite中高效地更新选项卡表:
sqlite> update tab set buy='Yes' where not exists (select 1 from tmp where tmp.code=tab.code);
sqlite> select * from tab;
Fruit Texture Code Buy
---------- ---------- ---------- ----------
apple code1
orange code2 Yes
mango code3
banana code4 Yes
peach code5
当然,您可以在Python中执行最后一步:
con.execute("update tab set buy='Yes' where not exists (select 1 from tmp where tmp.code=tab.code)")
# optional clean up
con.execute("drop table tmp")
con.commit()