我有一个“年龄”列,但有时会显示NaN值。我知道我可以为此目的使用“ fillna”,但是我尝试定义了自己的函数(并学习了这种方法),并在数据框中使用了applymap
到目前为止没有成功。
Age
69
49
NaN
54
NaN
我已经尝试过
def get_rid_of_nulls(value):
if value == np.nan:
return 'Is Null value'
else:
return value
这都不起作用
if value == None
if value isnull
if value == np.na
if value ==''
if value == NaN
if value == 'NaN'
似乎没有一个比较可行。我肯定是错的,但是我被卡住了,我非常固执地使用fillna
谢谢
由于标题中有“替换”,而您提到的是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')
您可以使用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
类似地,您可以使用NaN
不等于自身的属性:
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