我正在寻找一种方法来进一步简化我的代码:
数据集:
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")
对于replace by list,可以使用^{} :
答案之间的区别在于子字符串替换:
您可以改为使用带有
str.replace
的正则表达式,分隔字符串以与|
匹配,这将替换指定字符串中的任何匹配:相关问题 更多 >
编程相关推荐