【问题标题】:How to relabel rows in a pandas Dataframe with regular expressions?如何使用正则表达式重新标记熊猫数据框中的行?
【发布时间】: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'

标签: python regex r pandas


【解决方案1】:

使用str.contains 处理各种方法以生成布尔掩码以传递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

【讨论】:

  • 最后一个问题:“如果它不包含 Google 并且不包含 cat,则删除行条目”怎么样?我不确定在这种情况下否定波浪号 ~ 将如何工作。
  • 那就是~df['url'].str.contains('google|cat')
  • 我现在已经掌握了窍门。感谢您对 n00b 的耐心等待!
猜你喜欢
  • 2021-07-20
  • 2020-10-23
  • 2021-03-13
  • 1970-01-01
  • 2018-01-11
  • 2014-10-07
  • 1970-01-01
  • 2019-12-29
  • 2021-05-16
相关资源
最近更新 更多