使用applymap替换Pandas Dataframe中的空值 [英] replacing null values in a Pandas Dataframe using applymap
问题描述
我有一个年龄"(Age)列,但有时会显示NaN值. 我知道我可以为此目的使用"fillna",但是我尝试定义了自己的函数(并学习了这种方法)并将applymap应用于数据框
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
到目前为止没有成功.
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
None of the comparisons seems to work. I'm wrong for sure but I'm stuck and I'm very stubborn to use fillna
谢谢
推荐答案
由于标题中存在替换",并且您提到了fillna
而不是replace()
方法,因此您也可以通过执行某些操作来获得相同的结果像这样:
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')
这篇关于使用applymap替换Pandas Dataframe中的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!