首页 > 解决方案 > 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 引起的?

我真的很想了解更多关于这方面的信息,以真正了解它是如何工作的

标签: pythonregexstringpandas

解决方案


那是因为 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 获取提供的子字符串的计数(不是正则表达式)


推荐阅读