相当于 R 的 grepl 的最简单的 python [英] simplest python equivalent to R's grepl

查看:91
本文介绍了相当于 R 的 grepl 的最简单的 python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个简单的/一行 Python 等价于 R 的 grepl 函数?

Is there a simple/one-line python equivalent to R's grepl function?

strings = c("aString", "yetAnotherString", "evenAnotherOne") 
grepl(pattern = "String", x =  strings) #[1]  TRUE  TRUE FALSE

推荐答案

您可以使用列表推导式:

You can use list comprehension:

strings = ["aString", "yetAnotherString", "evenAnotherOne"]

["String" in i for i in strings]
#Out[76]: [True, True, False]

或者使用re模块:

import re

[bool(re.search("String", i)) for i in strings]
#Out[77]: [True, True, False]

或者使用 Pandas(R 用户可能对此库感兴趣,使用类似"结构的数据框):

Or with Pandas (R user may be interested in this library, using a dataframe "similar" structure):

import pandas as pd

pd.Series(strings).str.contains('String').tolist()
#Out[78]: [True, True, False]

这篇关于相当于 R 的 grepl 的最简单的 python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆