【问题标题】:Python - Pandas - Replace a string from a column based on the value from other columnPython - Pandas - 根据其他列的值替换列中的字符串
【发布时间】:2020-05-29 11:18:41
【问题描述】:

我有一个包含以下数据的数据框:

d = {'col0': ['Table 1', 'Table 2'], 'col1': ['Tablename: Table 1', 'Tablename: Table 2'], 'col2': ['Table A', 'Table B']}

我正在尝试用 col2 中的值替换 col2 上存在的值 col0。

基本上我的输出是这样的:

我试图做一个简单的替换,例如:

df['col3'] = df['col1'].replace(df.col0, df['col2'], regex = True)
print(df)

但它给了我"TypeError: replace() takes no keyword arguments"

然后我试试这个:

df['col3'] = df['col1'].replace(df.col0, str(df['col2']), regex = True)
print(df)

但它给了我一个关于 col3 的列表...

我该怎么做?

谢谢

【问题讨论】:

    标签: python regex pandas replace


    【解决方案1】:

    您必须将一个列表或类似列表的东西传递给replace 的第一个和第二个参数。 .valuesdf['col0']df['col2'] 转换为可以工作的 numpy 数组。

    df['col3'] = df['col1'].replace(df['col0'].values, df['col2'].values, regex = True)
    

    输出:

          col0                col1     col2                col3
    0  Table 1  Tablename: Table 1  Table A  Tablename: Table A
    1  Table 2  Tablename: Table 2  Table B  Tablename: Table B
    

    你可以查看pd.DataFrame.replacehere的完整文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2021-02-20
      相关资源
      最近更新 更多