I've got an "Age" column, but sometimes NaN values are displayed. I know I can use "fillna" for this purposes but I've tried to define my own function (and learning to do this way) and use applymap to dataframe
no success so far.
Age
69
49
NaN
54
NaN
I've tried
def get_rid_of_nulls(value):
if value == np.nan:
return 'Is Null value'
else:
return value
with this not working either
if value == None
if value isnull
if value == np.na
if value ==''
if value == NaN
if value == 'NaN'
None of the comparisons seems to work. I'm wrong for sure but I'm stuck and I'm very stubborn to use fillna
thanks
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With