【问题标题】:Python pandas: use of DataFrame.replace function with a function as a valuePython pandas:使用带有函数作为值的 DataFrame.replace 函数
【发布时间】:2015-12-12 06:32:22
【问题描述】:

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

因此,我遵循了elsewhere on stackoverflow 提供的指导,但与re.sub 相关,并尝试将其应用于pandas.DataFrame.replace(使用regex=True, inplace=Trueto_replace 设置为嵌套字典(如果指定特定列),否则设置为两个列表(根据其documentation)。我的代码在不使用函数调用的情况下工作正常,但如果我尝试提供一个函数作为替换值之一,尽管这样做的方式与 re.sub 相同(经过测试,并且工作正常)。我意识到该函数应该接受一个匹配对象作为其唯一必需的参数并返回一个字符串。

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

为什么会发生这种情况,我怎样才能让它正常工作(返回并存储函数的结果)?如果这是不可能的,如果可以提出一个可行的“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)。

【问题讨论】:

  • 只是想注意,您似乎没有正确使用 to_replace,来自文档“如果这是真的,那么 to_replace 必须是一个字符串。”,但是您的 to_replace 是一个字典
  • @dermen 我认为你可能是正确的,这里真正的问题是你指出的,关于 to_replace 在使用 regex=True 时是一个字符串。我想我预计它不是指 to_replace 子句的值,但这很可能被误导了......

标签: python pandas


【解决方案1】:

我当前的解决方案(对我来说似乎是次优且临时)如下(省略号表示不相关的附加代码,已省略;使用的具体数据是人为设计的):

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)

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 2021-06-19
    • 2018-10-08
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2012-08-24
    相关资源
    最近更新 更多