使用 Python pandas,我一直在尝试使用一个函数,作为 pandas.DataFrame 的几个替换值之一。 (即其中一个替换本身应该是函数调用的结果)。我的理解是 pandas.DataFrame.replace 内部委托(delegate)给 re.sub并且任何适用于它的东西也应该适用于 pandas.DataFrame.replace ,前提是 regex参数设置为 True .
因此,我遵循了提供的指导 elsewhere堆栈溢出,但属于re.sub ,并试图将其应用于 pandas.DataFrame.replace (使用替换为 regex=True, inplace=True 和 to_replace 设置为嵌套字典,如果指定特定列,或者根据其 documentation 设置为两个列表)。我的代码在不使用函数调用的情况下工作正常,但如果我尝试提供一个函数作为替换值之一则会失败,尽管这样做的方式与 re.sub 相同(已经过测试,并且工作正常)。我意识到该函数应该接受一个匹配对象作为其唯一必需的参数并返回一个字符串。
而不是生成的 DataFrame具有函数调用的结果,它包含函数本身(即作为一流的、未参数化的对象)。
为什么会发生这种情况,我怎样才能让它正常工作(返回并存储函数的结果)?如果这不可能,如果可以建议一个可行的“Pandasonic”替代方案,我将不胜感激。
我在下面提供了一个例子:
def fn(match):
id = match.group(1)
result = None
with open(file_name, 'r') as file:
for line in file:
if 'string' in line:
result = line.split()[-1]
return (result or id)
data.replace(to_replace={'col1': {'string': fn}},
regex=True, inplace=True)
以上不起作用,因为它替换了正确的搜索字符串,而是替换为:
<function fn at 0x3ad4398>
对于上面的(人为的)示例,预期输出将是 col1 中“字符串”的所有值被替换为从 fn 返回的字符串.
然而,import re; print(re.sub('string', fn, 'test string')) ,按预期工作(和 previously depicted )。
请您参考如下方法:
我目前的解决方案(对我来说这似乎不是最佳的和临时的)如下(省略号表示不相关的附加代码,已被省略;使用的特定数据是人为设计的):
def _fn(match):
...
return ...
def _multiple_replace(text, repl_dictionary):
"""Adapted from: http://stackoverflow.com/a/15175239
Returns the result for the first regex that matches
the provided text."""
for pattern in repl_dictionary.keys():
regex = re.compile(pattern)
res, num_subs = regex.subn(repl_dictionary[pattern], text)
if num_subs > 0:
break
return res
repl_dict = {'ABC.*(\w\w\w)': _fn, 'XYZ': 'replacement_string'}
data['col1'] = data['col1'].apply(_multiple_replace,
repl_dictionary=repl_dict)
