如何用正则表达式重新标记数据帧中的行?

2024-04-19 15:12:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我计划访问某个列下的所有条目,并搜索字符串模式。你知道吗

数据框中的数据项示例如下:

https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=kitty+pictures
https://search.yahoo.com/search;_ylc=X3oDMTFiN25laTRvBF9TAzIwMjM1MzgwNzUEaXRjAzEEc2VjA3NyY2hfcWEEc2xrA3NyY2h3ZWI-?p=kitty+pictures&fr=yfp-t-694
https://duckduckgo.com/?q=kitty+pictures
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=cat+pictures

我想用正则表达式来找到网页搜索引擎,并用一个词代替它。因此,使用regex查找google,并用google替换上面的所有url。你知道吗

通常,人们会尝试

import re
string_example = "https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#safe=off&q=cat+pictures"
re.search(r'google', string_example)

然而,这只是返回谷歌,并没有取代它。你知道吗

(1)如何在这个数据框中搜索整个列的条目r'google,然后用“Google”替换这个URL?你知道吗

(2)如何只搜索列条目?我不能每次都传一串。你知道吗


Tags: httpscomwwwgoogle条目chromeieutf
1条回答
网友
1楼 · 发布于 2024-04-19 15:12:39

使用^{}处理生成布尔掩码的各种方法,以传递loc并设置这些行:

In [126]:
df = pd.DataFrame({'url':['google', 'cat', 'google cat', 'dog']})
df

Out[126]:
          url
0      google
1         cat
2  google cat
3         dog

In [127]:    
df['url'].str.contains('google')

Out[127]:
0     True
1    False
2     True
3    False
Name: url, dtype: bool

In [128]:    
df['url'].str.contains('google|cat')

Out[128]:
0     True
1     True
2     True
3    False
Name: url, dtype: bool

In [129]:
(df['url'].str.contains('google')) & (~df['url'].str.contains('cat'))

Out[129]:
0     True
1    False
2    False
3    False
Name: url, dtype: bool

然后您可以将这些条件传递给loc:

In [130]:
df.loc[df['url'].str.contains('google'), 'url'] = 'yahoo'
df

Out[130]:
     url
0  yahoo
1    cat
2  yahoo
3    dog

相关问题 更多 >