python SQL 像运算符需要 return 从 SQL 列表中匹配
python SQL like operator needs to return match from list of SQLs
我有一个类似的数据框。
Animal
------
Cat
Horse
Mouse
我的 SQL 清单是。
["SELECT * FROM df WHERE Animal LIKE '%og'", "SELECT * FROM df WHERE Animal LIKE '%at'", "SELECT * FROM df WHERE Animal LIKE '%ous'"]
我想要的结果需要是。
Animal sql
-----------
Cat %at
Mouse %ous
我尝试了以下方法并尝试添加一个 JOIN/INSERT 但收效甚微。
from pandasql import sqldf
import pandas as pd
df = {'Animal': ['Cat', 'Horse', 'Mouse']}
df = pd.DataFrame(df)
searchStrings = ['%og', '%ouse', '%at']
sqls = []
for i in searchStrings:
j = "SELECT * from df where Animal LIKE '%s'" %(i)
sqls.append(j)
dfNew = [sqldf(k).drop_duplicates() for k in sqls]
dfNew = pd.concat(dfNew)
谢谢!
使用字典代替列表:
sqls = {i: f"SELECT * FROM df WHERE Animal LIKE '{i}'" for i in searchStrings}
out = pd.concat({key: sqldf(qs) for key, qs in sqls.items()}, names=['sql', None]) \
.droplevel(1).reset_index().drop_duplicates()
输出:
>>> out
sql Animal
0 %ouse Mouse
1 %at Cat
我有一个类似的数据框。
Animal
------
Cat
Horse
Mouse
我的 SQL 清单是。
["SELECT * FROM df WHERE Animal LIKE '%og'", "SELECT * FROM df WHERE Animal LIKE '%at'", "SELECT * FROM df WHERE Animal LIKE '%ous'"]
我想要的结果需要是。
Animal sql
-----------
Cat %at
Mouse %ous
我尝试了以下方法并尝试添加一个 JOIN/INSERT 但收效甚微。
from pandasql import sqldf
import pandas as pd
df = {'Animal': ['Cat', 'Horse', 'Mouse']}
df = pd.DataFrame(df)
searchStrings = ['%og', '%ouse', '%at']
sqls = []
for i in searchStrings:
j = "SELECT * from df where Animal LIKE '%s'" %(i)
sqls.append(j)
dfNew = [sqldf(k).drop_duplicates() for k in sqls]
dfNew = pd.concat(dfNew)
谢谢!
使用字典代替列表:
sqls = {i: f"SELECT * FROM df WHERE Animal LIKE '{i}'" for i in searchStrings}
out = pd.concat({key: sqldf(qs) for key, qs in sqls.items()}, names=['sql', None]) \
.droplevel(1).reset_index().drop_duplicates()
输出:
>>> out
sql Animal
0 %ouse Mouse
1 %at Cat