![](/img/trans.png)
[英]Python - Pandas - Replace a string from a column based on the value from other column - Dealing with substrings
[英]Python - Pandas - Replace a string from a column based on the value from other column
我有一个包含以下数据的数据框:
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 的列表......
我怎样才能做到这一点?
谢谢
您必须将列表或类似列表的内容传递给replace
的第一个和第二个参数。 .values
将df['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.replace
的完整文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.