亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 pandas 的列中刪除字符串列表

從 pandas 的列中刪除字符串列表

慕娘9325324 2023-10-31 14:11:14
我需要刪除字符串列表:list_strings=['describe','include','any']來自 pandas 的專欄:My_Columninclude details about your goaldescribe expected and actual resultsshow some code anywhere我試過df['My_Column']=df['My_Column'].str.replace('|'.join(list_strings), '')但它刪除了部分單詞。例如:My_Columndetails about your goalexpected and actual resultsshow some code where # here it should be anywhere我的預期輸出:My_Columndetails about your goalexpected and actual resultsshow some code anywhere 
查看完整描述

3 回答

?
慕姐4208626

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


查看完整回答
反對 回復 2023-10-31
?
慕的地6264312

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)


查看完整回答
反對 回復 2023-10-31
?
慕神8447489

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


查看完整回答
反對 回復 2023-10-31
  • 3 回答
  • 0 關注
  • 179 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號