[英]removing ? and | symbols in a string in a pandas dataframe column using replace
我已經考慮過逃避角色,但這對我沒有幫助。
我有一個 Pandas 數據框,其中有一列名為 Page。 這是一個網頁名稱列表(不是網址)。
所以目前它們以 3 種格式編寫:
1. home ? home ? pagename1
2. home | home | pagename2
3. home home pagename3
我希望它們都像數字 3 一樣格式化。
我正在嘗試從此列中的字符串對象中刪除字符,但保留代碼的其余部分。
我用過這個:
df.loc[df['Page'].str.replace(('\?|\|'), ''), Regex=True, Inplace=True]
但我得到輸出:
File "<ipython-input-80-2c616b171200>", line 2
df['page']=df.loc[df['Page'].str.replace(('\?|\\'), ''), Regex=True, Inplace=True]
SyntaxError: invalid syntax
如果我使用這個,輸出相同:
df['page']=df.loc[df['Page'].str.replace(('\?|\|'), ''), Regex=True, Inplace=True]
我已經嘗試其他選項,例如:
x=pd.Series['Page']
x.str.replace('\?|\|','',regex = True, inplace=True)
但這給了我:
TypeError Traceback (most recent call last) <ipython-input-70-6563d5fa5d40> in <module> 1 #clean up page names ----> 2 x=pd.Series['Page'] 3 x.str.replace('\?|\|','',regex = True, inplace=True) TypeError: 'type' object is not subscriptable
請問有人可以幫忙嗎?
謝謝你
米茲
數據
df=pd.DataFrame({'text':['home ? home ? pagename1','home | home | pagename2','home home pagename3']})
text
0 home ? home ? pagename1
1 home | home | pagename2
2 home home pagename3
解決方案
使用df.str.replace(regex, replacement)
鏈接
df.text=df.text.str.replace('[\s\?\s]|[\s\|\s]',' ')
text
0 home home pagename1
1 home home pagename2
2 home home pagename3
所以你得到一個語法錯誤,因為regex=True
(是的,全部小寫)部分應該是括號中 str.replace() 參數的一部分。 下面的代碼
#Modifying page
df['page'] = df['page'].str.replace(('\?|\|'), '',regex=True)
print(df)
得到這個結果
0 home home pagename1
1 home home pagename2
2 home home pagename3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.