pandas.Series.str.contains

pandas.Series.str.contains方法用于检查字符串系列中是否包含特定模式或正则表达式,返回布尔值系列。参数包括pat(匹配模式),case(是否区分大小写,默认为True)和regex(是否启用正则,默认True)。文中通过电影题材的例子进行示例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pandas.Series.str.contains用于判断Series的字符串中是否包含待匹配的模式或者正则表达式,返回的是一个boolean Series。

Parameters:

  • pat:str. Character sequence or regular expression.
  • case:bool, default True. If True, case sensitive.
  • regex:bool, default True. If True, assumes the pat is a regular expression. If False, treats the pat as a literal string.

下面以一个电影题材的例子说明:
数据集如图所示:
movies_title_genres
代码:

import pandas as pd


movie = [['Toy Story (1995)', 'Adventure|Animation|Children|Comedy|Fantasy'],
         ['Jumanji (1995)', 'Adventure|Children|Fantasy'],
         ['Grumpier Old Men (1995)', 'Comedy|Romance'],
         ['Waiting to Exhale (1995)', 'Comedy|Drama|Romance'],
         ['Father of the Bride Part II (1995)', 'Comedy'],
         ['Heat (1995)', 'Action|Crime|Thriller'],
         ['Sabrina (1995)', 'Comedy|Romance'],
         ['Tom and Huck (1995)', 'Adventure|Children'],
         ['Sudden Death (1995)', 'Action'],
         ['GoldenEye (1995)', 'Action|Adventure|Thriller'],
         ['American President, The (1995)', 'Comedy|Drama|Romance'],
         ['Dracula: Dead and Loving It (1995)', 'Comedy|Horror'],
         ['Balto (1995)', 'Adventure|Animation|Children'],
         ['Nixon (1995)', 'Drama'],
         ['Cutthroat Island (1995)', 'Action|Adventure|Romance'],
         ['Casino (1995)', 'Crime|Drama'],
         ['Sense and Sensibility (1995)', 'Drama|Romance'],
         ['Four Rooms (1995)', 'Comedy'],
         ['Ace Ventura: When Nature Calls (1995)', 'Comedy'],
         ['Money Train (1995)', 'Action|Comedy|Crime|Drama|Thriller']]

df = pd.DataFrame(data=movie, columns=['title', 'genres'])
movie_with_Action = df[df['genres'].str.contains(pat='Action')]
movie_with_Romance = df[df['genres'].str.contains(pat='Romance')]
movie_with_Action_Romance = df[df['genres'].str.contains(pat='Action|Romance')]

结果:
movie_with_Action:
movie_with_Action
movie_with_Romance:
movie_with_Romance
movie_with_Action_Romance:
movie_with_Action_Romance

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值