【问题标题】:Replace a specific word with the value from another column用另一列中的值替换特定单词
【发布时间】:2020-06-11 09:52:59
【问题描述】:

我有以下数据框:

我要做的是在“草稿”一词之后添加来自 Col_1 的 vlaue。

基本上,我需要以下输出:

为此,我正在尝试使用以下代码:

df['Col_3'] = df['Col_2'].str.replace(r'Draft', ' Draft' + df['Col_1'].astype(str), regex=True)

但它给了我以下错误:

 raise TypeError("repl must be a string or callable")
TypeError: repl must be a string or callable

我该怎么做?

谢谢!

【问题讨论】:

  • 请不要在您的问题中使用图像来显示数据框!!!

标签: python regex pandas replace


【解决方案1】:

我认为你需要这个:

df['Col2'] = df['Col2'].str[:5] + " " + df['Col1'] + " " + df['Col2'].str[5:]

或使用[str.slice][1]

df['Col2'] = df['Col2'].str.slice(0, 5) + " " + df['Col1'] + " " + df['Col2'].str.slice(5)

【讨论】:

    【解决方案2】:
    df['Col3'] = df.apply(lambda x: x['Col2'].replace("Draft", "Draft {}".format(x['Col1'])), axis=1)
    

    或使用fstrings

    df = pd.DataFrame(
        {
            "val": ["AAA", "BBB"],
            "str": [
                "Draft I promise not to use pictures in my next question",
                "Draft jk ill most likely post more pics"]})
    
    
    df["output"] = df[["str", "val"]].apply(
        lambda x: x["str"].replace("Draft", f"Draft {x['val']} "), axis=1
    )
    
    print(df['output'])
    
    0    Draft AAA  I promise not to use pictures in my...
    1         Draft BBB  jk ill most likely post more pics
    Name: output, dtype: object
    

    【讨论】:

    • @Datanovice 这确实是一个更好的例子! :D
    【解决方案3】:

    你可以试试这个:

    df['Col_3'] = 'Draft ' + df['Col_1'] + df['Col_2'].str.replace('Draft', '')
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2015-03-02
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多