![](/img/trans.png)
[英]How to replace a string in a dataframe column with another in Python Pandas?
[英]How to partially replace a string in a column pandas Dataframe python
我有一個這樣的 dataframe:
Name Comment
1 Ama Delay with coming home client to provide place he visited
2 Kofi Enquiry on apples client to provide refund
3 Kwame Equiry on tables client advised with enquiry
4 Theo Emotional challenge client to provide details
5 Isaiah Eating on empty stomach client to confirm the issues
但我需要它看起來像這樣:
Name Comment
1 Ama Delay with coming home
2 Kofi Enquiry on apples
3 Kwame Enquiry on tables
4 Theo Emotional challenge
5 Isaiah Eating on empty stomach
看起來您想刪除“client”之后的所有內容,使用帶有str.replace
的正則表達式:
df['Comment'] = df['Comment'].str.replace(r'\s*\bclient\b.*', '',
case=False, regex=True)
Output:
Name Comment
1 Ama Delay with coming home
2 Kofi Enquiry on apples
3 Kwame Equiry on tables
4 Theo Emotional challenge
5 Isaiah Eating on empty stomach
正則表達式:
\s* # match 0 or more spaces
\b # match word boundary
client # match "client"
\b # match word boundary
.* # match anything until the end
使用相同的正則表達式,但添加后視以匹配非空格: (?<=\S)
df['Comment'] = df['Comment'].str.replace(r'(?<=\S)\s*\bclient.*', '',
case=False, regex=True)
例子:
Name Comment
1 Ama Delay with coming home
2 Kofi Enquiry on apples
3 Kwame Equiry on tables
4 Theo Emotional challenge
5 Isaiah Eating on empty stomach
6 Alfred Client starting sentence
例子
data = [['Ama', 'Delay with coming home client to provide place he visited'],
['Kofi', 'Enquiry on apples client to provide refund '],
['Kwame', 'Equiry on tables client advised with enquiry'],
['Theo', 'Emotional challenge client to provide details'],
['Isaiah', 'Eating on empty stomach client to confirm the issues'],
['Amy', 'client is smart']]
df = pd.DataFrame(data, columns=['Name', 'Comment'])
df
Name Comment
0 Ama Delay with coming home client to provide place...
1 Kofi Enquiry on apples client to provide refund
2 Kwame Equiry on tables client advised with enquiry
3 Theo Emotional challenge client to provide details
4 Isaiah Eating on empty stomach client to confirm the ...
5 Amy client is smart
代碼
按“客戶”拆分並先取
df['Comment'] = df['Comment'].str.split(' client').str[0]
df
Name Comment
0 Ama Delay with coming home
1 Kofi Enquiry on apples
2 Kwame Equiry on tables
3 Theo Emotional challenge
4 Isaiah Eating on empty stomach
5 Amy client is smart
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.