pandas.Series.str.contains(筛选)

本文详细介绍了 Pandas 中 Series.str.contains 函数的使用方法,通过实例演示了如何在数据筛选中应用此函数,特别关注于正则表达式的使用与结果返回的数据类型。

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

https://blog.youkuaiyun.com/weixin_43615654/article/details/103419171
这篇里用到了一个Str的contains函数,查了一下用法。

pandas.Series.str.contains

Returns: Series or Index of boolean values
A Series or Index of boolean values indicating whether the given pattern is contained within the string of each element of the Series or Index.

中文资料:
pandas(3)筛选数据isin(), str.contains()

demo:

s1 = pd.Series(['Mouse', 'dog', 'house and parrot', '23', np.NaN])
print(s1.str.contains('og',regex=False))
0    False
1     True
2    False
3    False
4      NaN
dtype: object
### Pandas `str` 方法详解 在数据科学领域,字符串操作是数据清洗和处理中不可或缺的一部分。Pandas 的 `Series.str` 接口提供了强大的字符串操作功能,能够简化复杂的字符串处理任务[^2]。 #### 基本属性与方法 `Series.str` 属性允许访问一系列用于字符串操作的方法。下面列举了一些常用的字符串处理方法: - **提取子串** 可以使用 `.str.slice()` 或者更直观的方式如 `.str[start:end]` 来获取指定位置的字符或子串。 ```python s = pd.Series(['hello world', 'pandas']) print(s.str[:5]) ``` - **分割字符串** 使用 `.str.split()` 将字符串按照特定分隔符拆分成多个部分,默认情况下返回列表形式的结果;如果只需要前几项,则可以设置参数 `n` 和 `expand=True` 得到 DataFrame 形式的输出。 ```python s = pd.Series(['a_b_c', 'd_e_f', 'g_h_i']) print(s.str.split('_', expand=True)) ``` - **去除空白字符** 提供了多种方式来清理两端多余的空格,比如 `.str.strip()`, `.str.lstrip()`, 和 `.str.rstrip()` 分别对应于移除全部、左侧以及右侧的空白字符。 ```python s = pd.Series([' hello ', '\tworld\n', ' test ']) print(s.str.strip()) ``` - **大小写转换** 支持常见的大小写变换操作,像 `.str.lower()`, `.str.upper()`, 和 `.str.title()` 等等。 ```python s = pd.Series(['HELLO', 'WORLD']) print(s.str.lower()) ``` - **正则表达式匹配** 利用正则表达式来进行模式匹配是一项非常实用的功能。`.str.contains()`, `.str.match()`, `.str.extract()`, 和 `.str.findall()` 都支持 regex 参数以便执行高级查询。 ```python s = pd.Series(['foo', 'bar', 'baz']) print(s[s.str.contains('ba')]) ``` 以上只是对 `Series.str` 功能的一个简单介绍,在实际工作中还有很多其他有用的方法等待探索。对于更加复杂的需求,建议查阅官方文档获得最新最全的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值