gpt4 book ai didi

python - 用 pandas str.replace 替换多个子字符串值

转载 作者:太空狗 更新时间:2023-10-30 01:10:46 26 4
gpt4 key购买 nike

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

# Dataset
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")

有没有办法让 str.replace() 函数接受一个字符串列表而不是一个字符串?

例子:

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

最佳答案

要用列表替换可以使用 Series.replace :

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

关于python - 用 pandas str.replace 替换多个子字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57820150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com