python - Pandas DataFrame 中 str 计数的奇怪行为
问题描述
我有以下熊猫数据框:
>>> sample_dataframe
P
0 107.35
1 99.35
2 75.85
3 92.34
当我尝试以下操作时,输出如下:
>>> sample_dataframe[sample_dataframe['P'].astype(str).str.count('.') == 1]
Empty DataFrame
Columns: [P]
Index: []
而使用正则表达式转义字符时,会发生以下情况:
>>> sample_dataframe[sample_dataframe['P'].astype(str).str.count('\.') == 1]
P
0 107.35
1 99.35
2 75.85
3 92.34
以下进一步强化了这一点:
>>> sample_dataframe['P'].astype(str).str.count('.')
0 6
1 5
2 5
3 5
Name: P, dtype: int64
对比
sample_dataframe['P'].astype(str).str.count('\.')
0 1
1 1
2 1
3 1
Name: P, dtype: int64
因此,.
表达式实际上将所有字符计为正则表达式通配符,减去换行符,因此计数 6, 5, 5, 5 与转义\.
的 ,它只计算实际字符的出现.
。
但是,从字符串本身调用的常规函数似乎表现不同,不需要 '.' 的正则表达式转义:
>>> '105.35'.count('.')
1
>>> '105.35'.count('\.')
0
编辑:根据一些答案,我将尝试澄清下面的类函数调用(而上面是实例化对象的方法调用):
>>> str.count('105.35', '.')
1
>>> str.count('105.35', '\.')
0
我不确定在底层使用 CPython 的 Pandas 相关方法(由于 NumPy 操作)是否将其实现为正则表达式(包括 df.apply),或者这是否与str
类函数count
(即str.count()
)与类函数的差异有关。实例化对象的str
类方法(在上面的示例中'105.35'
)count
(即'105.35'.count()
)。类与对象函数/方法之间的差异是根本原因(以及它们是如何实现的),还是由如何通过 NumPy 实现 DataFrame 引起的?
我真的很想了解更多关于这方面的信息,以真正了解它是如何工作的
解决方案
那是因为 Pandas.Series.str.count 和字符串计数方法不同。您可以在此处(https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.count.html#pandas.Series.str.count)看到 Pandas.Series.str。 count 将正则表达式作为参数。和 ”。” 正则表达式表示“任何符号”,而 str.count 获取提供的子字符串的计数(不是正则表达式)
推荐阅读
- java - 按下后退按钮时如何获取最后使用的片段
- python-3.x - 导入隐式命名空间包适用于一台机器而不是另一台机器
- sql - 如何使用sql存储过程将数据库表数据导出到excel中
- flutter - Spring Boot Web Flux 和 Flutter
- javascript - 如果没有模板字符串和条件(三元)运算符,但使用 if-else,这个 React 代码会是什么样子?
- spring-data-jpa - 如何按值查询或值是否为空 JpaRepository
- r - 如何过滤掉 tibble 列表列的 NULL 元素
- xamarin.forms - Flexlayout 不适用于命令和命令参数
- python - Pyspark:如何在 HDFS 中并行化多 gz 文件处理
- vb.net - 如何从 vb.net 读取具有区域语言的文本文件