如何替换与熊猫系列中的正则表达式匹配的整个字符串

时间:2021-03-13 14:25:55

标签: python regex pandas

当我尝试根据我在 Pandas 系列中的正则表达式替换一组字符串时,替换只发生在字符串的一部分。我希望用我的替换文本替换整个字符串。 我附上了图片以供参考。 如果有人可以提供帮助,那将非常有帮助

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:2)

如果您不熟悉正则表达式,请尝试这样的操作:

df.loc[~df['Gender'].isin(['Man', 'Woman']), 'Gender'] = 'Other'

答案 1 :(得分:1)

试试这个:

df1['Gender'].str.replace(r'(Man)|(Woman)', 'Others')

如果方括号 '[ ]' 内有东西,那么每个字符都被单独映射。 前往 python regex documentation 了解更多详情。

<块引用>

[ ] 用于表示一组字符。一组:

字符可以单独列出,例如[amk] 将匹配“a”、“m”、 或“k”。