簡體   English   中英

使用 applymap 替換 Pandas Dataframe 中的空值

[英]replacing null values in a Pandas Dataframe using applymap

我有一個“年齡”列,但有時會顯示 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM