使用dropna()函數就可以去掉dataframe中的空值。這裏就直接用的官方文檔裏面的例子。
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
- 1. dropna()函數有一個axis參數,用來指明是刪除有空值的維度(行或列)。默認的是刪除行。參數的值可以爲{0 or ‘index’, 1 or ‘columns’}
df.dropna()
name toy born
1 Batman Batmobile 1940-04-25
刪除有空值的列。
df.dropna(axis='columns')/df.dropna(axis=1)
name
0 Alfred
1 Batman
2 Catwoman
- 2. dropna()函數默認(how='any')的是隻要行或列出現了空值,就刪除行或列。可以通過how參數設置爲行或列的所有值都爲空值時才刪除。我們新添加一列的值全爲空,然後刪除。
>>> df['sex'] = [np.nan,np.nan,np.nan]
>>> df
name toy born sex
0 Alfred NaN NaT NaN
1 Batman Batmobile 1940-04-25 NaN
2 Catwoman Bullwhip NaT NaN
>>> df.dropna(how='all',axis=1)
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
>>>
- 3. 如果想刪除指定列有空值的行,可以使用subset參數。這裏刪除的是name和born列的值爲空的行。
df.dropna(subset=['name', 'born'])
name toy born
1 Batman Batmobile 1940-04-25
- 4. 需要注意的是,上面的操作並沒有改變df,也就是說df裏面的空值並沒有刪除。
>>> df.dropna()
name toy born
1 Batman Batmobile 1940-04-25
>>> df
name toy born
0 Alfred NaN NaT
1 Batman Batmobile 1940-04-25
2 Catwoman Bullwhip NaT
>>>
需要將刪除空值的dataframe賦值給新的變量,或者將inplcace參數賦值爲true來改變原來的df(dataframe的許多函數裏都有這個參數)。
>>> df2 = df.dropna()
>>> df2
name toy born
1 Batman Batmobile 1940-04-25
>>>
>>> df.dropna(inplace=True)
>>> df
name toy born
1 Batman Batmobile 1940-04-25
>>>