VINAY DM
VINAY DM

Reputation: 21

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. 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

enter image description here

enter image description here

enter image description here

Upvotes: 1

Views: 617

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

Try something like this if you not that familiar with regex:

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

Upvotes: 2

ThePyGuy
ThePyGuy

Reputation: 18406

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.

[ ] Used to indicate a set of characters. In a set:

Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.

Upvotes: 1

Related Questions