用一个值替换 Pandas 系列中的多个子字符串 [英] Replace multiple substrings in a Pandas series with a value

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

问题描述

全部,

要替换某一特定列中的一个字符串,我已完成此操作并且效果很好:

To replace one string in one particular column I have done this and it worked fine:

dataUS['sec_type'].str.strip().str.replace("LOCAL","CORP")

我现在想用一个字符串替换多个字符串,比如用 "CORP"["LOCAL", "FOREIGN", "HELLO"]>

I would like now to replace multiple strings with one string say replace ["LOCAL", "FOREIGN", "HELLO"] with "CORP"

如何使它起作用?下面的代码不起作用

How can make it work? the code below didn't work

dataUS['sec_type'].str.strip().str.replace(["LOCAL", "FOREIGN", "HELLO"], "CORP")

推荐答案

您可以通过形成一个 | 分隔的字符串来执行此任务.这是因为 pd.Series.str.replace 接受正则表达式:

You can perform this task by forming a |-separated string. This works because pd.Series.str.replace accepts regex:

用一些替换系列/索引中出现的模式/正则表达式其他字符串.相当于 str.replace() 或 re.sub().

Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to str.replace() or re.sub().

这避免了创建字典的需要.

This avoids the need to create a dictionary.

import pandas as pd

df = pd.DataFrame({'A': ['LOCAL TEST', 'TEST FOREIGN', 'ANOTHER HELLO', 'NOTHING']})

pattern = '|'.join(['LOCAL', 'FOREIGN', 'HELLO'])

df['A'] = df['A'].str.replace(pattern, 'CORP')

#               A
# 0     CORP TEST
# 1     TEST CORP
# 2  ANOTHER CORP
# 3       NOTHING

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

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