Pandas缺失值處理

2022-07-13 17:26 更新

在一些數(shù)據(jù)分析業(yè)務中,數(shù)據(jù)缺失是我們經(jīng)常遇見的問題,缺失值會導致數(shù)據(jù)質(zhì)量的下降,從而影響模型預測的準確性,這對于機器學習和數(shù)據(jù)挖掘影響尤為嚴重。因此妥善的處理缺失值能夠使模型預測更為準確和有效。

為什么會存在缺失值?

前面章節(jié)的示例中,我們遇到過很多 NaN 值,關于缺失值您可能會有很多疑問,數(shù)據(jù)為什么會丟失數(shù)據(jù)呢,又是從什么時候丟失的呢?通過下面場景,您會得到答案。

其實在很多時候,人們往往不愿意過多透露自己的信息。假如您正在對用戶的產(chǎn)品體驗做調(diào)查,在這個過程中您會發(fā)現(xiàn),一些用戶很樂意分享自己使用產(chǎn)品的體驗,但他是不愿意透露自己的姓名和聯(lián)系方式;還有一些用戶愿意分享他們使用產(chǎn)品的全部經(jīng)過,包括自己的姓名和聯(lián)系方式。因此,總有一些數(shù)據(jù)會因為某些不可抗力的因素丟失,這種情況在現(xiàn)實生活中會經(jīng)常遇到。

什么是稀疏數(shù)據(jù)?

稀疏數(shù)據(jù),指的是在數(shù)據(jù)庫或者數(shù)據(jù)集中存在大量缺失數(shù)據(jù)或者空值,我們把這樣的數(shù)據(jù)集稱為稀疏數(shù)據(jù)集。稀疏數(shù)據(jù)不是無效數(shù)據(jù),只不過是信息不全而已,只要通過適當?shù)姆椒ň涂梢浴白儚U為寶”。

稀疏數(shù)據(jù)的來源與產(chǎn)生原因有很多種,大致歸為以下幾種:

  • 由于調(diào)查不當產(chǎn)生的稀疏數(shù)據(jù);
  • 由于天然限制產(chǎn)生的稀疏數(shù)據(jù);
  • 文本挖掘中產(chǎn)生的稀疏數(shù)據(jù)。

缺失值處理

那么 Pandas 是如何處理缺失值的呢,下面讓我們一起看一下。

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df)

輸出結果:

          0         1         2
a  0.187208 -0.951407  0.316340
b       NaN       NaN       NaN
c -0.365741 -1.983977 -1.052170
d       NaN       NaN       NaN
e -1.024180  1.550515  0.317156
f -0.799921 -0.686590  1.383229
g       NaN       NaN       NaN
h -0.207958  0.426733 -0.325951

上述示例,通過使用 reindex(重構索引),我們創(chuàng)建了一個存在缺少值的 DataFrame 對象。

檢查缺失值

為了使檢測缺失值變得更容易,Pandas 提供了 isnull() 和 notnull() 兩個函數(shù),它們同時適用于 Series 和 DataFrame 對象。

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df['noe'].isnull())

輸出結果:

a    False
b     True
c    False
d     True
e    False
f    False
g     True
h    False
Name: 1, dtype: bool

notnull() 函數(shù),使用示例:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print df['one'].notnull()

輸出結果:

a     True
b    False
c     True
d    False
e     True
f     True
g    False
h     True
Name: 1, dtype: bool

缺失數(shù)據(jù)計算

計算缺失數(shù)據(jù)時,需要注意兩點:首先數(shù)據(jù)求和時,將 NA 值視為 0 ,其次,如果要計算的數(shù)據(jù)為 NA,那么結果就是 NA。示例如下:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'],columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print (df['one'].sum())
print()

輸出結果:

3.4516595395128

清理并填充缺失值

Pandas 提供了多種方法來清除缺失值。fillna() 函數(shù)可以實現(xiàn)用非空數(shù)據(jù)“填充”NaN 值。

1) 用標量值替換NaN值

下列程序?qū)?NaN 值 替換為了 0,如下所示:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one',
'two', 'three'])
df = df.reindex(['a', 'b', 'c'])
print(df)
#用 0 填充 NaN
print (df.fillna(0))

輸出結果:

        one       two     three
a  1.497185 -0.703897 -0.050513
b       NaN       NaN       NaN
c  2.008315  1.342690 -0.255855

        one       two     three
a  1.497185 -0.703897 -0.050513
b  0.000000  0.000000  0.000000
c  2.008315  1.342690 -0.255855

當然根據(jù)您自己的需求,您也可以用其他值進行填充。

2) 向前和向后填充NA

在《Pandas reindex重置索引》一節(jié),我們介紹了 ffill() 向前填充和 bfill() 向后填充,使用這兩個函數(shù)也可以處理 NA 值。示例如下:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'],columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print df.fillna(method='ffill')

輸出結果:

        one       two     three
a  0.871741  0.311057  0.091005
b  0.871741  0.311057  0.091005
c  0.107345 -0.662864  0.826716
d  0.107345 -0.662864  0.826716
e  1.630221  0.482504 -0.728767
f  1.283206 -0.145178  0.109155
g  1.283206 -0.145178  0.109155
h  0.222176  0.886768  0.347820

或者您也可以采用向后填充的方法。

3) 使用replace替換通用值

在某些情況下,您需要使用 replace() 將 DataFrame 中的通用值替換成特定值,這和使用 fillna() 函數(shù)替換 NaN 值是類似的。示例如下:

import pandas as pd
import numpy as np
df = pd.DataFrame({'one':[10,20,30,40,50,666], 'two':[99,0,30,40,50,60]})
#使用replace()方法
print (df.replace({99:10,666:60,0:20}))

輸出結果:

   one  two
0   10   10
1   20   20
2   30   30
3   40   40
4   50   50
5   60   60

刪除缺失值

如果想刪除缺失值,那么使用 dropna() 函數(shù)與參數(shù) axis 可以實現(xiàn)。在默認情況下,按照 axis=0 來按行處理,這意味著如果某一行中存在 NaN 值將會刪除整行數(shù)據(jù)。示例如下:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f','h'],columns=['one', 'two', 'three'])
df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
print(df)
#刪除缺失值
print (df.dropna())

輸出結果:

        one       two     three
a -2.025435  0.617616  0.862096
b       NaN       NaN       NaN
c -1.710705  1.780539 -2.313227
d       NaN       NaN       NaN
e -2.347188 -0.498857 -1.070605
f -0.159588  1.205773 -0.046752
g       NaN       NaN       NaN
h -0.549372 -1.740350  0.444356

        one       two     three
a -2.025435  0.617616  0.862096
c -1.710705  1.780539 -2.313227
e -2.347188 -0.498857 -1.070605
f -0.159588  1.205773 -0.046752
h -0.549372 -1.740350  0.444356

axis = 1 表示按列處理,處理結果是一個空的 DataFrame 對象。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號