简体   繁体   English

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

[英]How to replace whole string which matches regex in a pandas series

When I try to replace a group of strings according to my regex in pandas series the replacement happens only for the part of string.当我尝试根据 pandas 系列中的正则表达式替换一组字符串时,替换仅发生在字符串的一部分。 I want the whole string to be replaced with my replacement text.我希望用我的替换文本替换整个字符串。 I've attached the images for reference.我附上了图片以供参考。 If someone could help, it will be really helpful如果有人可以提供帮助,那将非常有帮助

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

Try something like this if you not that familiar with regex:如果您对正则表达式不太熟悉,请尝试这样的操作:

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

Try this:尝试这个:

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

If something is inside squre brackets '[ ]', then each of the characters are mapped separately.如果方括号 '[ ]' 中有内容,则每个字符都将单独映射。 Go to python regex documentation for more details. Go 到python 正则表达式文档以获取更多详细信息。

[ ] Used to indicate a set of characters. [ ] 用于表示一组字符。 In a set:在一组中:

Characters can be listed individually, eg [amk] will match 'a', 'm', or 'k'.字符可以单独列出,例如 [amk] 将匹配 'a'、'm' 或 'k'。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM