使用applymap替换Pandas Dataframe中的空值

use*_*eRj 7 python pandas

我有一个"年龄"列,但有时会显示NaN值.我知道我可以使用"fillna"来实现这个目的,但我试图定义自己的函数(并学习这样做)并使用applymap来实现数据帧

到目前为止没有成功.

Age
69
49
NaN
54
NaN
Run Code Online (Sandbox Code Playgroud)

我试过了

   def get_rid_of_nulls(value):
     if value == np.nan:
        return 'Is Null value'
     else:
        return value
Run Code Online (Sandbox Code Playgroud)

这不起作用

 if value == None
   if value isnull
   if value == np.na
   if value ==''
   if value == NaN
   if value == 'NaN'
Run Code Online (Sandbox Code Playgroud)

这些比较似乎都不起作用.我当然错了,但是我被困住了,我很顽固地使用fillna

谢谢

mgc*_*mgc 7

由于你的标题中有"替换",并且你提到fillna但不是replace()方法,你也可以获得相同的结果:

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')
Run Code Online (Sandbox Code Playgroud)