Python:使用DataFrame.replace函数作为值

Python:使用DataFrame.replace函数作为值,python,pandas,Python,Pandas,使用Python pandas,我一直在尝试使用一个函数,作为pandas.DataFrame(即其中一个替换本身应该是函数调用的结果)的几个替换值之一。我的理解是,在内部委托给re.sub,如果regex参数设置为True,则任何与之相关的操作都应该与pandas.DataFrame.replace一起使用 因此,我遵循了stackoverflow上提供的指南,但与re.sub有关,并尝试将其应用于pandas.DataFrame.replace(使用replace withregex=Tru

使用Python pandas,我一直在尝试使用一个函数,作为
pandas.DataFrame
(即其中一个替换本身应该是函数调用的结果)的几个替换值之一。我的理解是,在内部委托给
re.sub
,如果
regex
参数设置为
True
,则任何与之相关的操作都应该与
pandas.DataFrame.replace
一起使用

因此,我遵循了stackoverflow上提供的指南,但与
re.sub
有关,并尝试将其应用于
pandas.DataFrame.replace
(使用replace with
regex=True、inplace=True
替换
设置为嵌套字典(如果指定了特定列),或按其设置为两个列表)。我的代码在不使用函数调用的情况下运行良好,但如果我尝试提供一个函数作为替换值之一,则会失败,尽管这样做的方式与
re.sub
(已测试并正确运行)相同。我意识到该函数应接受匹配对象作为其唯一必需参数并返回字符串

结果
DataFrame
不具有函数调用的结果,而是包含函数本身(即作为一级、未参数化的对象)

为什么会发生这种情况?我如何才能使其正常工作(返回并存储函数的结果)?如果这不可能,我希望能够建议一个可行的“泛达索尼克”替代方案


我在下面提供了一个例子:

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
中“string”的所有值替换从
fn
返回的字符串

但是,
import re;print(re.sub('string',fn,'test string'))
,按预期工作。

我当前的解决方案(对我来说似乎是次优的和特别的)如下所示(省略号表示不相关的附加代码,已省略;使用的特定数据是人为的):


只是想注意一下,从文档“如果这是真的,那么to_replace必须是一个字符串”来看,似乎您没有正确使用to_replace,但您要替换的是dict@dermen我想你可能是对的,这里真正的问题是你所指出的,当使用
regex=True
时,
to\u replace
是一个字符串。我想我想它不是指
to\u replace
子句的值,但这很可能是误导。。。
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)