如何在Pandas中使用classPython中的函数?
How to use function from class Python in Pandas?
我有一个 Python class 里面有方法。其中之一是 public.
如何应用此方法过滤 Pandas 中的行数据?
我的意思是这样的:
class Math:
def isTrue(value):
return True
Pandas 规则:
df[df["name"].apply(Math.isTrue)]
如果列名称中的值为 True
,则在结果数据框中显示它们。
数据为:
Number Name Country
1 Vasila US
1212 oLGA AU
6 Fors RE
我需要使用来自 class 的自定义方法和正则表达式过滤所有 Number 具有双对的行,例如 1212
。
结果应该是:
Number Name Country
1212 oLGA AU
import re
class Matcher:
pattern = re.compile('^(?P<num_pair>\d\d)(?(num_pair)(?P=num_pair))$')
@classmethod
def has_num_pair(cls, n: int) -> bool:
if cls.pattern.match(str(n)) is None:
return False
return True
df[df['Number'].apply(Matcher.has_num_pair)]
正则表达式解释:
pattern = re.compile(
'^' # at the beginning of the string
'(?P<num_pair>' # create a capturing group named "num_pair" ...
'\d\d)' # ... that captures two digits
'(?(num_pair)' # if the group "num_pair" captures something ...
'(?P=num_pair))' # try to match the captured content again
'$' # the string must end after that
)
此模式将匹配由一对重复数字组成的数字,例如 1212
、9898
或 3535
,但它 不会 匹配 包括 这样的一对数字以及其他数字,例如 14343
。如果你也想匹配这些,请像这样更改你的正则表达式:
pattern = re.compile('.*(?P<num_pair>\d\d)(?(num_pair)(?P=num_pair)).*')
此变体也将匹配 14343
、767689
等。
我有一个 Python class 里面有方法。其中之一是 public.
如何应用此方法过滤 Pandas 中的行数据?
我的意思是这样的:
class Math:
def isTrue(value):
return True
Pandas 规则:
df[df["name"].apply(Math.isTrue)]
如果列名称中的值为 True
,则在结果数据框中显示它们。
数据为:
Number Name Country
1 Vasila US
1212 oLGA AU
6 Fors RE
我需要使用来自 class 的自定义方法和正则表达式过滤所有 Number 具有双对的行,例如 1212
。
结果应该是:
Number Name Country
1212 oLGA AU
import re
class Matcher:
pattern = re.compile('^(?P<num_pair>\d\d)(?(num_pair)(?P=num_pair))$')
@classmethod
def has_num_pair(cls, n: int) -> bool:
if cls.pattern.match(str(n)) is None:
return False
return True
df[df['Number'].apply(Matcher.has_num_pair)]
正则表达式解释:
pattern = re.compile(
'^' # at the beginning of the string
'(?P<num_pair>' # create a capturing group named "num_pair" ...
'\d\d)' # ... that captures two digits
'(?(num_pair)' # if the group "num_pair" captures something ...
'(?P=num_pair))' # try to match the captured content again
'$' # the string must end after that
)
此模式将匹配由一对重复数字组成的数字,例如 1212
、9898
或 3535
,但它 不会 匹配 包括 这样的一对数字以及其他数字,例如 14343
。如果你也想匹配这些,请像这样更改你的正则表达式:
pattern = re.compile('.*(?P<num_pair>\d\d)(?(num_pair)(?P=num_pair)).*')
此变体也将匹配 14343
、767689
等。