![](/img/trans.png)
[英]How to extract entire part of string after certain character in dataframe column?
[英]Python replace entire string if it begin with certain character in dataframe
我有隨機位置包含“無...”字符串的數據。 我試圖只在以'None ..'開頭時用空字符替換數據框中的單元格。 這是我嘗試過的方法,但出現諸如“ KeyError”之類的錯誤。
df = pd.DataFrame({'id': [1,2,3,4,5],
'sub': ['None ... ','None ... test','math None ...','probability','chemistry']})
df.loc[df['sub'].str.replace('None ...','',1), 'sub'] = '' # getting key error
尋找的輸出:(如果'None ...'是起始字符串,我需要替換單元格中的整個值。注意,不應替換第三行,因為'None ...'不是起始字符)
id sub
1
2
3 math None ...
4 probability
5 chemistry
您可以使用以下內容標識要替換的單元格,然后為它們分配一個空值:
df.loc[df['sub'].str.startswith("None"), 'sub'] = ""
df.head()
id sub
0 1
1 2
2 3 math None ...
3 4 probability
4 5 chemistry
df['sub'] = df['sub'].str.replace('[\w\s]*?(None \.\.\.)[\s\w]*?','',1)
日期:
sub
id
1
2 test
3
4 probability
5 chemistry
查看startswith
,然后在發現需要替換的行后,我們使用replace
df['sub']=df['sub'].mask(df['sub'].str.startswith('None ... '),'')
df
Out[338]:
id sub
0 1
1 2
2 3 math None ...
3 4 probability
4 5 chemistry
您可以簡單地替換“ None ...”,並通過使用正則表達式可以僅對以None開頭的字符串應用此替換。
df['sub'] = df['sub'].str.replace(r'^None \.\.\.*','',1)
輸出看起來像這樣:
id sub
0 1
1 2 test
2 3 math None ...
3 4 probability
4 5 chemistry
首先,您將子字符串用作索引,這就是為什么您收到鍵錯誤的原因。
其次,您可以通過以下方法執行此操作:df ['sub'] = df ['sub']。apply(lambda x:``如果x.find('None')== 0否則x)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.