1、前記
pandas對象上的所有描述統計都排除了缺失數據,使用浮點值NaN表示浮點和非浮點數組中的缺失數據。
string_data = Series(['aa','ar',np.nan,'avo'])
string_data
Out[27]:
0 aa
1 ar
2 NaN
3 avo
dtype: object
string_data.isnull()
Out[28]:
0 False
1 False
2 True
3 False
dtype: bool
string_data[0]=None
string_data.isnull()
Out[30]:
0 True
1 False
2 True
3 False
dtype: bool
dropna | 根據各標籤的值中是否存在缺失數據對軸標籤進行過濾,可通過閾值調節對缺失值的容忍度 |
fillna | 用指定值或插值方法(如ffill或bfill)填充缺失數據 |
isnull | 返回一個含有布爾值的對象,這些布爾值表示哪些值是缺失值/NA,該對象的類型與源類型一樣 |
notnull | isnull的否定式 |
2、濾除缺失數據
(1)對於一個Series,dropna返回一個僅含非空數據和索引值的Series:
from numpy import nan as NA
data = Series([1,NA,3.5,NA,7])
data.dropna()
Out[33]:
0 1.0
2 3.5
4 7.0
dtype: float64
當然,也可以通過布爾型索引達到這個目的:
data[data.notnull()]
Out[34]:
0 1.0
2 3.5
4 7.0
dtype: float64
(2)對於DataFrame對象
①dropna默認丟棄任何含有缺失值的行:
data = DataFrame([[1,6.5,3.],[1.,NA,NA],[NA,NA,NA],[NA,6.5,3.]])
cleaned = data.dropna()
data
Out[37]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0
cleaned
Out[38]:
0 1 2
0 1.0 6.5 3.0
②傳入how='all'將只丟棄全爲NA的那些行:
data.dropna(how='all')
Out[39]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
3 NaN 6.5 3.0
用這種方式丟棄列的話,只需傳入axis=1即可
data.dropna(how='all',axis=1)
Out[40]:
0 1 2
0 1.0 6.5 3.0
1 1.0 NaN NaN
2 NaN NaN NaN
3 NaN 6.5 3.0
另一個濾除DataFrame行的問題涉及時間序列數據。假設只想留下一部分觀測數據,可以用thresh參數實現此目的:
但是,下面這個iloc和loc是不是錯了?效果咋是一樣的?我很迷,有沒有知道的,感激!
df = DataFrame(np.random.randn(7,3))
from numpy import nan as NA
df.iloc[:4,1] = NA
df.loc[:3,2] = NA
df
Out[8]:
0 1 2
0 -2.392721 NaN NaN
1 0.218175 NaN NaN
2 -0.551001 NaN NaN
3 -1.193819 NaN NaN
4 0.251430 NaN 0.165344
5 0.353838 -1.473924 0.120994
6 -1.881549 -2.605414 0.091505
df.dropna(thresh=3)
Out[9]:
0 1 2
5 0.353838 -1.473924 0.120994
6 -1.881549 -2.605414 0.091505
3、填充缺失數據
df.fillna(0)
Out[48]:
0 1 2
0 -0.736398 0.00000 0.000000
1 0.733540 0.00000 0.000000
2 -1.894173 0.00000 0.000000
3 -1.195053 0.00000 0.000000
4 -0.022654 0.00000 0.414124
5 -0.468519 0.00000 -0.176802
6 1.326602 2.33336 0.136677
若是通過一個字典調用fillna,就可以實現對不同的列填充不同的值:
df.fillna({1:0.5,3:-1})
Out[49]:
0 1 2
0 -0.736398 0.50000 NaN
1 0.733540 0.50000 NaN
2 -1.894173 0.50000 NaN
3 -1.195053 0.50000 NaN
4 -0.022654 0.50000 0.414124
5 -0.468519 0.50000 -0.176802
6 1.326602 2.33336 0.136677
fillna默認會返回新對象,但也可以對現有對象進行就地修改:
_=df.fillna(0,inplace=True)
df
Out[51]:
0 1 2
0 -0.736398 0.00000 0.000000
1 0.733540 0.00000 0.000000
2 -1.894173 0.00000 0.000000
3 -1.195053 0.00000 0.000000
4 -0.022654 0.00000 0.414124
5 -0.468519 0.00000 -0.176802
6 1.326602 2.33336 0.136677
對reindex有效的那些插值方法也可用於fillna:
ff.fillna(method='ffill')
df.fillna(method='ffill',limit=2)
傳入Series的平均值或中位數:
data = Series([1.,Na,3.5,NA,7])
data.fillna(data.mean())
value | 用於填充缺失值的標量值或字典對象 |
method | 插值方式。如果函數調用時未指定其他參數的話,默認爲“ffill” |
axis | 待填充的軸,默認axis=0 |
inplace | 修改調用者對象而不產生副本 |
limit | (對於前向和後向填充)可以連續填充的最大數量 |