0

I got the following dataframe:

Contact Gender Title
1 M
2 F Dear Ms
3 Female Dear Ms
4 F. Dear Ms
5 M
6 M
7 M. Dear Mr

How can I change contact 2,3,4 and 7 based on the Title column.

Ms is F and Mr is M

The other contacts who don't have a Title, must nothing happen to it. It must be the same.

So i want this:

Contact Gender Title
1 M
2 F Dear Ms
3 F Dear Ms
4 F Dear Ms
5 M
6 M
7 M Dear Mr
0

2 Answers 2

1

Try the following:

df.loc[df.Title.str.contains('Mr'), 'Gender']='M'
df.loc[df.Title.str.contains('Ms'), 'Gender']='F'
Sign up to request clarification or add additional context in comments.

Comments

0

Well In your sample dataframe Gender is correct according to Title:

If that's the case then you can simply do:

df['Gender']=df['Gender'].str[0]

IF that is not the case then use np.select():

#import numpy as np

conditions = [
    df["Title"].str.contains("Ms",case=False).fillna(False),
    df["Title"].str.contains("Mr",case=False).fillna(False)
]
choices = ["F", "M"]

df["Gender"] =pd.Series(np.select(conditions, choices)).replace('0',np.nan).fillna(df['Gender'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.