python - 用一个值替换 Pandas 系列中的多个子字符串

标签 python string pandas python-2.7 series

全部,

为了替换一个特定列中的一个字符串,我已经这样做了并且效果很好:

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/

相关文章:

具有继承性的 Python 循环导入

java - 为什么我的方法不返回字符串?

Python - 尝试计算时间 t 之前事件的平均时间

Python Anagrams 递归

python - 为什么 var = [0].extend(range(1,10)) 在 python 中不起作用?

python - 如何将此 Python 2.7 代码转换为 Python 3?

java - 相同的字符串比较给我错误

python - 在curl中使用python字符串输出

python - 我如何使用 get_dummies 使用字符串列连接 2 个数据帧并计算字符串中的重复单词

python - Pandas 在日期列问题上合并