Python Forum

Full Version: Replacing NaN with list of numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
#Here is the question:

### Write a function that takes two columns, 'age' and 'pclass', as input and depending on which pclass, if the age is NaN (command: pd.isnull(age) ) it returns age 40, 30 or 25. For example, if input is [NaN, 1], it returns age = 40

This is titanic data set. It has "age" and "pclass" columns. the "age" column has NaNs. I have to write a code so that when age is NaN and pclass is 1 then replace NaN in age with 40. When age is NaN and pclass is 2, then replace Nan in age with 30. When age is NaN and p class is 3, replace NaN with 25 in age.

Thanks,
What have you tried?
This is what I used but I cannot complete it.

list = [40,30,25]
for Nan in df['age']:
    if df3["pclass"] ==1:
        age=40
    elif df3["pclass"] ==2:
        age=30
    elif df3["pclass"]==3:
        age=25
df["age"]
The question specification is not clear. It sounds like it just takes two values and returns one, as if it was meant to be used with the map method.

Note that a dictionary is going to be very useful here. With age_map = {1: 40, 2:25, 3: 30}, you can just use age_map[pclass].
I am basically trying to fill NaN values in the age column with numbers. If age is NaN and the corresponding pclass column is 1 then replace the NaN with 40. If age is NaN and the corresponding pclass column is 2 then replace NaN with 30 and so on.
Thanks,
Okay. Make a function that takes a key and returns a value from the dictionary I showed you. Send that function to the map method of df['pclass']. That will give you a column with the age replacements. Send that column to the fillna method of the age column.