【问题标题】:Python replace error: replace() argument 2 must be str, not SeriesPython 替换错误:replace() 参数 2 必须是 str,而不是 Series
【发布时间】:2021-02-14 18:34:13
【问题描述】:

我想用 html 代码更新一个字符串。字符串是这样的:

textHTMLextract = 'Hello, my name is name1 name2'

我有一个包含如下变量的数据框:

import pandas as pd
variables = [{'Var': 'name1', 'Value': '<i>John</i>'}, 
             {'Var':'name2', 'Value': '<i><b>Smith</b></i>'}] 
df_variables = pd.DataFrame(variables) 

这个想法是用一些 html 标记值替换字符串。 我尝试将数据框转换为 dict,然后通过 for 循环替换:

vars_dict = dict(df_variables)

for key, value in vars_dict.items():
   textHTMLextract = textHTMLextract.replace(key, value)

我希望代码返回

'Hello, my name is <i>John</i> <i><b>Smith</b></i>'

最终在 html 解释器中打印为

'你好,我的名字是 John Smith'

但我得到的只是下面的错误消息:

TypeError: replace() argument 2 must be str, not Series

我错过了什么? 提前致谢。

【问题讨论】:

    标签: python pandas dictionary replace


    【解决方案1】:

    由于您在此处使用 pandas,因此您可以利用 Series.replace,它接受替换字典并使用正则表达式:

    mappings = dict(zip(df['Var'], df['Value']))
    pd.Series(textHTMLextract).replace(mappings, regex=True).item()
    # 'Hello, my name is <i>John</i> <i><b>Smith</b></i>'
    

    【讨论】:

    • 太棒了!工作!尽管如此,Python 控制台会警告 item() 的未来弃用:FutureWarning:item 已被弃用,并将在未来的版本中删除。我发现的项目的替代方法是使用 'next(iter(pd.Series(textHTMLextract).replace(mappings, regex=True)))'
    猜你喜欢
    • 2020-10-12
    • 2018-10-11
    • 1970-01-01
    • 2022-11-21
    • 2019-06-28
    • 2020-10-10
    • 2019-05-08
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多