0

I have the following dataframe:

count   country year    age_group   gender  type
7       Albania 2006    014         f       ep
1       Albania 2007    014         f       ep
3       Albania 2008    014         f       ep
2       Albania 2009    014         f       ep
2       Albania 2010    014         f       ep

I'm trying to make adjustments to the "gender" column so that 'f' becomes 'female' and same for m and male.

I tried the following code:

who3['gender'] = pd.np.where(who3['gender'] == 'f', "female")

But it gives me this error:

enter image description here

Now when I try this code:

who3['gender'] = pd.np.where(who3['gender'] == 'f', "female", 
                 pd.np.where(who3['gender'] == 'm', "male"))

I get error below:

enter image description here

What am I doing wrong?

2 Answers 2

2

You can use also .replace():

df["gender"] = df["gender"].replace({"f": "female", "m": "male"})
print(df)

Prints:

   count  country  year  age_group  gender type
0      7  Albania  2006         14  female   ep
1      1  Albania  2007         14  female   ep
2      3  Albania  2008         14  female   ep
3      2  Albania  2009         14  female   ep
4      2  Albania  2010         14  female   ep
Sign up to request clarification or add additional context in comments.

Comments

0

np.where needs the condition as the first parameter, and then the desire output if the condition is met, and as the third parameter it gets an output when the condition is not met, Try this:

who3['gender'] = np.where(who3['gender'] == 'f', "female", 'male')

Another solution is using replace method:

who3['gender'] = who3['gender'].replace({'f': 'female', 'm': 'male'})

2 Comments

is the pd part of pd.np.where unnecessary then?
Yes. Because np.where is a numpy function not a pandas one. I also added another solution for your question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.