pd.dropna
刪除缺失的值,過濾數據中的缺失數據,缺失數據在pandas中用NaN標記
DataFrame.dropna(axis = 0,how = 'any',thresh = None,subset = None,inplace = False)
參數:
- axis:{0 or ‘index’, 1 or ‘columns’}, default 0,確定是否刪除包含缺失值的行或列,在1.0.0版中進行了更改:將元組或列表傳遞到多個軸上。只允許一個軸
- how:{‘any’, ‘all’}, default ‘any’,當我們有至少一個NA或全部NA時,確定是否從DataFrame中刪除行或列,'any':如果存在任何NA值,則刪除該行或列,'all':如果所有值均為NA,則刪除該行或列
- thresh:int, optional,需要許多非NA值
- subset:array-like, optional,要考慮的其他軸上的標簽,例如,如果要刪除行,這些標簽將是要包括的列的列表
- inplace:bool, default False
官網例子
df = pd.DataFrame({"name": ['Alfred', 'Batman', 'Catwoman'], "toy": [np.nan, 'Batmobile', 'Bullwhip'], "born": [pd.NaT, pd.Timestamp("1940-04-25"), pd.NaT]}) df
name toy born
0 Alfred NaN NaT 1 Batman Batmobile 1940-04-25 2 Catwoman Bullwhip NaT
過濾掉有缺失數據
df.dropna()
name toy born
1 Batman Batmobile 1940-04-25
刪除有缺失的列
df.dropna(axis='columns')
name
0 Alfred 1 Batman 2 Catwoman
將所有元素都缺失的行刪除
df.dropna(how='all')
name toy born
0 Alfred NaN NaT 1 Batman Batmobile 1940-04-25 2 Catwoman Bullwhip NaT
僅保留至少具有2個非NA值的行
df.dropna(thresh=2)
name toy born
1 Batman Batmobile 1940-04-25 2 Catwoman Bullwhip NaT
在哪些列中查找缺失值
df.dropna(subset=['name', 'born'])
name toy born
1 Batman Batmobile 1940-04-25
是否覆蓋原來的數據
df.dropna(inplace=True) df
name toy born
1 Batman Batmobile 1940-04-25