蟒蛇熊猫系列。str.findall()

Python是进行数据分析的优秀语言,主要是因为以数据为中心的Python软件包的奇妙生态系统。 熊猫 是这些软件包中的一个,使导入和分析数据变得更加容易。

null

熊猫 str.findall() 方法还用于在序列中的每个字符串中查找子字符串或分隔符。但它不同于 str.find() 方法它不返回索引,而是返回带有子字符串的列表,列表的大小是它发生的次数。

语法: 系列str.findall(pat,flags=0)

参数: 拍打: 要搜索的子字符串 旗帜: 可以传递的正则表达式标志(A、S、L、M、I、X),默认值为0,表示无。对于这个正则表达式模块(re)也必须导入。

返回类型: 列表系列(字符串)。

要下载代码中使用的CSV,请单击 在这里 在以下示例中,使用的数据框包含一些NBA球员的数据。任何操作之前的数据帧图像附在下面。 图片[1]-蟒蛇熊猫系列。str.findall()-yiteyi-C++库

示例#1: 搜索字符串中的字符

在本例中,使用str.findall()方法在name列中搜索“r”,并将输出存储在新列中。在执行任何操作之前,使用删除空行。dropna()以避免错误。

# importing pandas module
import pandas as pd
# making data frame
# removing null values to avoid errors
data.dropna(inplace = True )
# string to be searched for
search = 'r'
# returning values and creating column
data[ "Findall(name)" ] = data[ "Name" ]. str .findall(search)
# display
data.head( 10 )


输出: 如输出图像所示,可以比较返回的“e”的数量是否等于它在字符串中出现的时间。 图片[2]-蟒蛇熊猫系列。str.findall()-yiteyi-C++库 示例2: 搜索字符并传递IGNORECASE标志

在本例中,将在Name列中搜索“a”,并传递IGNORECASE标志。为此,还必须导入re模块。str.findall()方法返回的序列存储在新列中。

# importing pandas module
import pandas as pd
# importing regex module
import re
# making data frame
# removing null values to avoid errors
data.dropna(inplace = True )
# string to be searched for
search = 'a'
# returning values and creating column
data[ "Findall(name)" ] = data[ "Name" ]. str .findall(search, flags = re.I)
# display
data.head( 10 )


输出: 如输出图像所示,在第一行中可以看到,自从传递IGNORECASE标志(re.I)后,“A”和“A”都被返回。 图片[3]-蟒蛇熊猫系列。str.findall()-yiteyi-C++库

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享