替换多个旧字符串值结构更换一个新的字符串

2024-10-01 09:19:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种方法来进一步简化我的代码:

数据集:

categorical_data = pd.Series(["dog", "lion", "cat", "crustacean", "dog", "insect", "insect", "cat", "crustacean"])

我想做的是用“动物”来代替狗、狮子和猫。我可以这样写:

categorical_data = categorical_data.str.replace("dog", "animal")
categorical_data = categorical_data.str.replace("cat", "animal")
categorical_data = categorical_data.str.replace("lion", "animal")

有没有一条路可以走结构更换()函数接受字符串列表而不是一个?你知道吗

示例:

categorical_data = categorical_data.str.replace([dog, lion, cat], "animal")

Tags: 数据方法代码datareplacecatseriespd
2条回答

对于replace by list,可以使用^{}

categorical_data = categorical_data.replace(['dog', 'lion', 'cat'], "animal")    
print (categorical_data)
0        animal
1        animal
2        animal
3    crustacean
4        animal
5        insect
6        insect
7        animal
8    crustacean
dtype: object

答案之间的区别在于子字符串替换:

categorical_data = pd.Series(["dog gorilla", "lion", "cat", "crustacean"])

print (categorical_data.replace(['dog', 'lion', 'cat'], "animal"))
0    dog gorilla
1         animal
2         animal
3     crustacean
dtype: object

print (categorical_data.str.replace(r'(dog|cat|lion)', 'animal', regex=True))
0    animal gorilla
1            animal
2            animal
3        crustacean
dtype: object

您可以改为使用带有str.replace的正则表达式,分隔字符串以与|匹配,这将替换指定字符串中的任何匹配:

categorical_data.str.replace(r'(dog|cat|lion)', 'animal', regex=True)

0        animal
1        animal
2        animal
3    crustacean
4        animal
5        insect
6        insect
7        animal
8    crustacean
dtype: object

相关问题 更多 >