【发布时间】:2016-05-12 23:40:58
【问题描述】:
我打算访问某个列下的所有条目,并搜索字符串模式。
pandas DataFrame 中的数据条目示例如下:
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
我想用正则表达式找到网络搜索引擎,并用一个词替换它。因此,您使用正则表达式查找 google 并将上面的所有 URL 替换为 google。
通常情况下,人们会尝试
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)
但是,这只会返回 google,而不是替换它。
(1) 如何在此 DataFrame 中的整个列条目中搜索 r'google,然后将该 URL 替换为“Google”?
(2) 如何只搜索列条目?我不能每次都传入一个字符串。
【问题讨论】:
-
IIUC 然后
df.loc[df['url'].str.contains('google'), 'url'] = 'google'应该可以工作 -
@EdChum 当然!我是一个傻瓜。 “字符串包含谷歌和猫”怎么样?或者“字符串包含谷歌而不是猫”?也就是如何搜索多个词?
-
df.loc[df['url'].str.contains('google|cats'), 'url'] = 'google',df.loc[(df['url'].str.contains('google')) & (~df['url'].str.contains('cat'), 'url'] = 'google'