![](/img/trans.png)
[英]Pandas: Remove all rows where any of the column contains a certain substring
[英]In Sql Alchemy, how to select rows where any column contains a substring?
我想檢索任何列中包含 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ“h”的表的所有行)
我試過這樣的事情:
list_of_columns = [c for c in my_table.columns] # where my_table is of class Table
with my_engine.connect() as conn:
result = conn.execute(select(my_table).where(
list_of_columns.contains(q),
))
當然這不起作用,因為應該在單個列上調用“ contains() ”......
任何想法?
ps:列的檢索必須是動態的,這是我的代碼必須工作的方式
[編輯]
一個幾乎可行的解決方案:
with my_engine.connect() as conn:
result = conn.execute(select(my_table).where(
or_(
list_of_columns[0].contains(q),
list_of_columns[1].contains(q),
...
)
))
但是,我需要列的列表是動態的
您可以使用列表推導將所有列添加到查詢中:
with my_engine.connect() as conn:
result = conn.execute(select(my_table).where(
or_(*[col.contains(q) for col in list_of_columns])
))
對於這種搜索,您還可以通過使用 postgresql 的全文搜索功能並創建一個組合所有列的 tsvector 來獲得更好的性能和結果: https://stackoverflow.com/a/42390204/16811479
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.