replacing null values in a Pandas Dataframe using applymap

You can use pd.isnull():

In [4]:
def get_rid_of_nulls(value):
    if pd.isnull(value):
        return 'Is Null value'
    else:
        return value

df['Age'].apply(get_rid_of_nulls)

Out[4]:
0               69
1               49
2    Is Null value
3               54
4    Is Null value
Name: Age, dtype: object

Similarly you can use the property that NaN does not equal itself:

In [5]:
def get_rid_of_nulls(value):
    if value != value:
        return 'Is Null value'
    else:
        return value

df['Age'].apply(get_rid_of_nulls)

Out[5]:
0               69
1               49
2    Is Null value
3               54
4    Is Null value
Name: Age, dtype: object

As there is "replacing" in your title, and you mentioned fillna but not the replace() method, you can also obtain the same result doing something like that :

df.Age.replace(np.NaN, 'Is Null value', inplace=True)

# Or, depending on your needs:
df['Age'] = df.Age.replace(np.NaN, 'Is Null value')

# Or without `replace` :
df['Age'] = df.Age.apply(lambda x: x if not pd.isnull(x) else 'Is Null value')

Tags:

Python

Pandas