簡體   English   中英

如何在DataFrame的字符串列中應用正則表達式替換?

[英]How do I apply a regex substitution in a string column of a DataFrame?

我有一個名為“Animals”的DataFrame,如下所示:

 Words
 The Black Cat
 The Red Dog

我想在每個單詞前添加一個加號,使它看起來像這樣:

 Words
 +The +Black +Cat
 +The +Red +Dog

我使用正則表達式嘗試了這個但它不起作用:

 df = re.sub(r'([a-z]+)', r'+\1', Animals)

您可以使用str.replace與以下正則表達式來進行更改到列的所有行:

df.Words = df.Words.str.replace(r'(\b\S)', r'+\1')

然后,DataFrame看起來像這樣:

>>> df
              Words
0  +The +Black +Cat
1    +The +Red +Dog

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM