全部,
为了替换一个特定列中的一个字符串,我已经这样做了并且效果很好:
dataUS['sec_type'].str.strip().str.replace("LOCAL","CORP")
我现在想用一个字符串替换多个字符串,比如将 ["LOCAL", "FOREIGN", "HELLO"]
替换为 "CORP"
如何让它发挥作用?下面的代码不起作用
dataUS['sec_type'].str.strip().str.replace(["LOCAL", "FOREIGN", "HELLO"], "CORP")
最佳答案
您可以通过形成一个 | 分隔的字符串来执行此任务。这是有效的,因为 pd.Series.str.replace
接受正则表达式:
Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to str.replace() or re.sub().
这避免了创建字典的需要。
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
关于python - 用一个值替换 Pandas 系列中的多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49413005/