Python - Pandas - 根据其他列的值替换列中的字符串 [英] Python - Pandas - Replace a string from a column based on the value from other column

查看:64
本文介绍了Python - Pandas - 根据其他列的值替换列中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a dataframe with the following data:

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

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

What I am trying is to replace on col2 the values that exists on col0 with the values from col2.

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

Basically my output it will be this:

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

I was trying to make a simple replace such as:

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

但它给了我 TypeError:replace() 没有关键字参数"

然后我试试这个:

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

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

But it gives me a list on col3...

我该怎么做?

谢谢

推荐答案

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

You have to pass a list or something list-like to the first and second parameters of replace. .values turns df['col0'] and df['col2'] into numpy arrays which will work.

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.replace的完整文档这里.

You can see the full documentation of pd.DataFrame.replace here.

这篇关于Python - Pandas - 根据其他列的值替换列中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆