我有以下函數來檢測數據中的字符串,我加入了字典的鍵和值,因為我想找到這兩個值。我添加了 ^ 和 $ 因為我只想要精確匹配。功能import pandas as pddef check_direction(df): # dict for all direction and their abbreviation direction = { '^Northwest$': '^NW$', '^Northeast$': '^NE$', '^Southeast$': '^SE$', '^Southwest$': '^SW$', '^North$': '^N$', '^East$': '^E$', "^South$": '^S$', "^West$": "^W$"} # combining all the dict pairs into one for str match all_direction = direction.keys() | direction.values() all_direction = '|'.join(all_direction) df = df.astype(str) df = pd.DataFrame(df.str.contains(all_direction, case = False)) return df我對以下系列進行了測試,結果按預期工作:tmp = pd.Series(['Monday', 'Tuesday', 'Wednesday', 'Thursday'])check_direction(tmp)0 False1 False2 False3 Falsetmp = pd.Series(['SOUTH', 'NORTHEAST', 'WEST'])check_direction(tmp)0 True1 True2 True但是我在這里遇到了問題:tmp = pd.Series(['32 Street NE', 'Ogden Road SE'])check_direction(tmp)0 False1 False由于 NE 和 SE,當它應該為 True 時,兩者都返回為 false,我該如何修改我的代碼來實現這一點?
1 回答

慕碼人2483693
TA貢獻1860條經驗 獲得超9個贊
我認為您誤解了^
和 的$
意思。
^
匹配整個字符串的開頭,$
匹配整個字符串的結尾。
例如,'Ogden Road SE'
不匹配模式^SE$
,因為字符串不以 開頭SE
。
您可能打算使用單詞邊界,即\b
.
所以你應該改為^SE$
,\bSE\b
等等。
您可以通過編寫來使其不那么乏味且更具可讀性
direction = {
'Northwest': 'NW',
'Northeast': 'NE',
'Southeast': 'SE',
'Southwest': 'SW',
'North': 'N',
'East': 'E',
'South': 'S',
'West': 'W'}
all_direction = direction.keys() | direction.values()
all_direction = '|'.join(r'\b{}\b'.format(d) for d in all_direction)
添加回答
舉報
0/150
提交
取消