[英]Sanitizing input to be used in pandas query with the str.contains method
我如何清理下面代碼中的輸入,以便它可用於查詢數據集df
?
query = f"`{field_name}`.str.contains('''{input()}''', case=False)"
df.query(query)
上面代碼的主要問題是,當輸入包含三重引號或反斜杠時,它會拋出錯誤。 還要記住 dataframe 在某些單元格中也包含反斜杠,因此我希望查詢也能夠執行該搜索(例如,如果輸入是a\s
我希望查詢返回包含a\s
例如aaaa\saaaaa
a\s
一個匹配項)。
假設field_name
已給出並且不會造成麻煩。
如果我理解正確的話,你想要這個:
import pandas as pd
import numpy as np
s1 = pd.Series(['Mouse', 'dog a\s', 'house and parrot', '23', np.NaN, 'aaaa\saaaaa', ' \ """ '])
s2 = s1.str.contains(input('input: '), regex=False)
print(s2)
input: a\s
0 False
1 True
2 False
3 False
4 NaN
5 True
6 False
dtype: object
Process finished with exit code 0
input: """
0 False
1 False
2 False
3 False
4 NaN
5 False
6 True
dtype: object
Process finished with exit code 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.