在python中可能會遇到,None表示空的對象,空也是一個對象。
Numpy中的缺失數據
a = np.array([1,2,3,None])
b = np.array([5,6,7,8])
print(a.dtype)
print(b.dtype)
object
int32
因爲a中有一個None對象,所以訪問元素類型的時候返回的是一個object類型,這個時候我們Numpy就提供了一個表示空缺數據的方法np.nan
c = np.array([1,np.nan,3,4])
print(c.dtype)
float64
對比a和c發現兩個的結果是完全不同的數據類型,一個是object,另一個是浮點數類型,也因爲這樣np.nan纔可以像數字一樣進行各種運算。
print(1-np.nan)
print(1+np.nan)
print(1*np.nan)
nan
nan
nan
可以發現所以數跟np.nan進行數字運算得到的結果都是nan,假如真的想要計算的話,這裏可以使用到一個方法自動幫我們導入一個數字。
print(np.nansum(c))
print(np.nanmean(c))
8.0
2.6666666666666665
Pandas處理缺失數據
a = pd.Series([1,np.nan,2,None,3])
print(a)
print(a.sum())
0 1.0
1 NaN
2 2.0
3 NaN
4 3.0
dtype: float64
6.0
你會發現Pandas它會把空值缺失值都轉換爲NaN,而且這裏使用數字運算,會默認把NaN當作0相加,這裏Pandas還提供了4個針對缺失數據進行操作的函數,如下:
print(a.isnull())
print(a.notnull())
print(a[a.notnull()])
print(a.dropna())
0 False
1 True
2 False
3 True
4 False
dtype: bool
0 True
1 False
2 True
3 False
4 True
dtype: bool
0 1.0
2 2.0
4 3.0
dtype: float64
0 1.0
2 2.0
4 3.0
dtype: float64
isnull()和notnull()返回的是布爾型數據,用返回的對象作爲下標,可對原有數據進行篩選,dropna()的作用是刪除所有包含NaN數據的行(默認是行,也可以使用axis=1來刪除列),並返回不含NaN的新對象,具體操作可以自行查看幫助文檔。
print(a)
print(a.fillna(123))
print(a.fillna(method='ffill'))
print(a.fillna(method='bfill'))
0 1.0
1 NaN
2 2.0
3 NaN
4 3.0
dtype: float64
0 1.0
1 123.0
2 2.0
3 123.0
4 3.0
dtype: float64
0 1.0
1 1.0
2 2.0
3 2.0
4 3.0
dtype: float64
0 1.0
1 2.0
2 2.0
3 3.0
4 3.0
dtype: float64
可以看出來fillna()的方法是可以把數據中的NaN替換爲自己指定的數據,還可以使用特定的一些方法比如fillna(method=‘ffill’)這個就是把NaN替換 爲上一個值,fillna(method=‘bfill’)則是替換後面的值。