3 回答

TA貢獻1852條經驗 獲得超7個贊
使用“詞邊界”\b之類的表達方式。
In [46]: df.My_Column.str.replace(r'\b{}\b'.format('|'.join(list_strings)), '')
Out[46]:
0 details about your goal
1 expected and actual results
2 show some code anywhere
Name: My_Column, dtype: object

TA貢獻1817條經驗 獲得超6個贊
您的問題是pandas看不到單詞,它只看到字符列表。因此,當你要求 pandas 刪除“any”時,它并不是從描繪單詞開始的。所以一種選擇是你自己做,也許是這樣的:
# Your data
df = pd.DataFrame({'My_Column':
['Include details about your goal',
'Describe expected and actual results',
'Show some code anywhere']})
list_strings=['describe','include','any'] # make sure it's lower case
def remove_words(s):
if s is not None:
return ' '.join(x for x in s.split() if x.lower() not in list_strings)
# Apply the function to your column
df.My_Column = df.My_Column.map(remove_words)

TA貢獻1780條經驗 獲得超1個贊
方法的第一個參數.str.replace()必須是字符串或編譯后的正則表達式;不是像你這樣的列表。
你可能想要
list_strings=['Describe','Include','any'] # Note capital D and capital I
for s in [f"\\b{s}\\b" for s in list_strings]: # surrounded word boundaries (\b)
df['My_Column'] = df['My_Column'].str.replace(s, '')
獲得
My_Column
0 details about your goal
1 expected and actual results
2 Show some code anywhere
添加回答
舉報