Python?Pandas中缺失值NaN的判斷,刪除及替換
前言
當(dāng)使用pandas讀取csv文件時,如果元素為空,則將其視為缺失值NaN(Not a Number, 非數(shù)字)。
使用dropna()方法刪除缺失值,使用fillna()方法用其他值替換(填充)缺失值。
如果要提取包含缺失值的行或列,使用isnull()方法確定元素是否缺失。
1. 檢查缺失值NaN
例如,讀取并使用包含帶read_csv的空格的csv文件。
import pandas as pd import numpy as np import math df = pd.read_csv('./data/05/sample_pandas_normal_nan.csv') print(df) # name age state point other # 0 Alice 24.0 NY NaN NaN # 1 NaN NaN NaN NaN NaN # 2 Charlie NaN CA NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen NaN CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
使用pandas.isnull() 檢查所有缺失的值:
print(df.isnull()) # 或者 print(pd.isnull(df)) # name age state point other # 0 False False False True True # 1 True True True True True # 2 False True False True True # 3 False False False False True # 4 False True False False True # 5 False False True True True
檢查 ‘name’ 列缺失的值:
print(df['name'].isnull()) # 0 False # 1 True # 2 False # 3 False # 4 False # 5 False Name: name, dtype: bool
也可以使用numpy.isnan() 和math.isnan() (但是需要分別導(dǎo)入NumPy和math):
print(pd.isnull(df.at[0, 'point'])) print(np.isnan(df.at[0, 'point'])) print(math.isnan(df.at[0, 'point'])) # True # True # True
2. Pandas中NaN的類型
在Pandas中,將None,np.nan,math.nan和pd.np.nan視為缺失值NaN
s_nan = pd.Series([None, np.nan, math.nan, pd.np.nan]) print(s_nan) # 0 NaN # 1 NaN # 2 NaN # 3 NaN # dtype: float64 print(s_nan[0]) print(type(s_nan[0])) # nan # <class 'numpy.float64'> print(s_nan.isnull()) # 0 True # 1 True # 2 True # 3 True # dtype: bool
3. NaN的刪除 dropna()
使用dropna()方法刪除缺失值。
默認(rèn)情況下,將返回新對象,并且不會更改原始對象,但是參數(shù)inplace = True會更改原始對象本身。
print(df) # name age state point other # 0 Alice 24.0 NY NaN NaN # 1 NaN NaN NaN NaN NaN # 2 Charlie NaN CA NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen NaN CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
3.1 刪除所有值均缺失的行/列
如果指定了參數(shù)how =‘all’,則將刪除所有缺少值的行。
print(df.dropna(how='all')) # name age state point other # 0 Alice 24.0 NY NaN NaN # 2 Charlie NaN CA NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen NaN CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
如果設(shè)置axis = 1,則將刪除所有缺少值的列。
print(df.dropna(how='all', axis=1)) # name age state point # 0 Alice 24.0 NY NaN # 1 NaN NaN NaN NaN # 2 Charlie NaN CA NaN # 3 Dave 68.0 TX 70.0 # 4 Ellen NaN CA 88.0 # 5 Frank 30.0 NaN NaN
刪除所有缺少值的行和列的數(shù)據(jù):
df2 = df.dropna(how='all').dropna(how='all', axis=1) print(df2) # name age state point # 0 Alice 24.0 NY NaN # 2 Charlie NaN CA NaN # 3 Dave 68.0 TX 70.0 # 4 Ellen NaN CA 88.0 # 5 Frank 30.0 NaN NaN
3.2 刪除至少包含一個缺失值的行/列
基于上面刪除所有缺少值的行和列的數(shù)據(jù)df2 :
print(df2) # name age state point # 0 Alice 24.0 NY NaN # 2 Charlie NaN CA NaN # 3 Dave 68.0 TX 70.0 # 4 Ellen NaN CA 88.0 # 5 Frank 30.0 NaN NaN
如果指定了參數(shù)how =‘any’,則將刪除至少包含一個缺失值的行。默認(rèn)值為how =‘any’。
print(df2.dropna(how='any')) # name age state point # 3 Dave 68.0 TX 70.0 print(df2.dropna()) # name age state point # 3 Dave 68.0 TX 70.0
如果設(shè)置axis = 1,則將刪除包含至少一個缺失值的列將被刪除。
print(df2.dropna(how='any', axis=1)) # name # 0 Alice # 2 Charlie # 3 Dave # 4 Ellen # 5 Frank
3.3 根據(jù)不缺少值的元素數(shù)量刪除行/列
通過在參數(shù)thresh中指定數(shù)字,可以根據(jù)不缺少值的元素數(shù)量刪除行和列。
例如,如果thresh = 3,則保留包含三個或更多個不丟失值的元素的行,并刪除其他行(包含兩個或更多個不丟失值的元素的行)。
print(df.dropna(thresh=3)) # name age state point other # 0 Alice 24.0 NY NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen NaN CA 88.0 NaN
如果axis= 1,則應(yīng)用于列。
print(df.dropna(thresh=3, axis=1)) # name age state # 0 Alice 24.0 NY # 1 NaN NaN NaN # 2 Charlie NaN CA # 3 Dave 68.0 TX # 4 Ellen NaN CA # 5 Frank 30.0 NaN
3.4 刪除特定行/列中缺少值的列/行
如果要基于特定的行/列刪除,請?jiān)诹斜淼膮?shù)子集中指定要定位的行/列標(biāo)簽。由于它必須是列表,因此請至少指定一個目標(biāo),例如subset = [‘name’]。 默認(rèn)情況下,子集指定的列中缺少值的行將被刪除。
print(df.dropna(subset=['age'])) # name age state point other # 0 Alice 24.0 NY NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 5 Frank 30.0 NaN NaN NaN
如果指定了多列,則默認(rèn)為刪除所有缺少指定值的行。
print(df.dropna(subset=['age', 'state'])) # name age state point other # 0 Alice 24.0 NY NaN NaN # 3 Dave 68.0 TX 70.0 NaN
如果參數(shù)how =‘all’,則僅刪除所有指定列均缺少值的行。
print(df.dropna(subset=['age', 'state'], how='all')) # name age state point other # 0 Alice 24.0 NY NaN NaN # 2 Charlie NaN CA NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen NaN CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
4. 缺失值NaN的替換(填充) fillna()
可以使用fillna()方法將缺失值替換為任意值。
默認(rèn)情況下,將返回新對象,并且不會更改原始對象,但是參數(shù)inplace = True會更改原始對象本身。
print(df) # name age state point other # 0 Alice 24.0 NY NaN NaN # 1 NaN NaN NaN NaN NaN # 2 Charlie NaN CA NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen NaN CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
4.1 用通用值統(tǒng)一替換
如果指定要用參數(shù)替換的值,則所有缺少的值NaN都將替換為該值。
print(df.fillna(0)) # name age state point other # 0 Alice 24.0 NY 0.0 0.0 # 1 0 0.0 0 0.0 0.0 # 2 Charlie 0.0 CA 0.0 0.0 # 3 Dave 68.0 TX 70.0 0.0 # 4 Ellen 0.0 CA 88.0 0.0 # 5 Frank 30.0 0 0.0 0.0
4.2 為每列替換不同的值
將字典指定為參數(shù)時,每列將替換一個不同的值。字典鍵是列標(biāo)簽(列名),而值是要替換的值。未指定的列仍缺少值NaN。
print(df.fillna({'name': 'XXX', 'age': 20, 'point': 0})) # name age state point other # 0 Alice 24.0 NY 0.0 NaN # 1 XXX 20.0 NaN 0.0 NaN # 2 Charlie 20.0 CA 0.0 NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen 20.0 CA 88.0 NaN # 5 Frank 30.0 NaN 0.0 NaN
不僅可以指定字典,還可以指定pandas.Series。具有與pandas.Series中的標(biāo)簽匹配的列標(biāo)簽(列名)的列中缺少的值將替換為pandas.Series值。與pandas.Series標(biāo)簽不對應(yīng)的列仍然缺少值。
s_for_fill = pd.Series(['ZZZ', 100], index=['name', 'age']) print(s_for_fill) # name ZZZ # age 100 # dtype: object print(df.fillna(s_for_fill)) # name age state point other # 0 Alice 24.0 NY NaN NaN # 1 ZZZ 100.0 NaN NaN NaN # 2 Charlie 100.0 CA NaN NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen 100.0 CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
4.3 用每列的平均值,中位數(shù),眾數(shù)等替換
可以使用mean()方法計算每列的平均值。結(jié)果是pandas.Series。缺失值將被排除并計算。
print(df.mean()) # age 40.666667 # point 79.000000 # other NaN # dtype: float64
如果將此pandas.Series指定為fillna()的參數(shù),則如上所述,將相應(yīng)列中的缺失值替換為平均值。
print(df.fillna(df.mean())) # name age state point other # 0 Alice 24.000000 NY 79.0 NaN # 1 NaN 40.666667 NaN 79.0 NaN # 2 Charlie 40.666667 CA 79.0 NaN # 3 Dave 68.000000 TX 70.0 NaN # 4 Ellen 40.666667 CA 88.0 NaN # 5 Frank 30.000000 NaN 79.0 NaN
同樣,如果要替換中位數(shù),請使用中位數(shù)()方法。在偶數(shù)的情況下,兩個中心值的平均值是中值。
print(df.fillna(df.median())) # name age state point other # 0 Alice 24.0 NY 79.0 NaN # 1 NaN 30.0 NaN 79.0 NaN # 2 Charlie 30.0 CA 79.0 NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen 30.0 CA 88.0 NaN # 5 Frank 30.0 NaN 79.0 NaN
4.4 替換為上一個或下一個值
通過使用method參數(shù),可以替換之前和之后的值,而不是指定的值。 如果method =‘ffill’,它將被以前的值替換;如果method =‘bfill’,將被后面的值替換。對于時間序列數(shù)據(jù)很有用。
print(df.fillna(method='ffill')) # ? ? ? name ? age state ?point ?other # 0 ? ?Alice ?24.0 ? ?NY ? ?NaN ? ?NaN # 1 ? ?Alice ?24.0 ? ?NY ? ?NaN ? ?NaN # 2 ?Charlie ?24.0 ? ?CA ? ?NaN ? ?NaN # 3 ? ? Dave ?68.0 ? ?TX ? 70.0 ? ?NaN # 4 ? ?Ellen ?68.0 ? ?CA ? 88.0 ? ?NaN # 5 ? ?Frank ?30.0 ? ?CA ? 88.0 ? ?NaN print(df.fillna(method='bfill')) # ? ? ? name ? age state ?point ?other # 0 ? ?Alice ?24.0 ? ?NY ? 70.0 ? ?NaN # 1 ?Charlie ?68.0 ? ?CA ? 70.0 ? ?NaN # 2 ?Charlie ?68.0 ? ?CA ? 70.0 ? ?NaN # 3 ? ? Dave ?68.0 ? ?TX ? 70.0 ? ?NaN # 4 ? ?Ellen ?30.0 ? ?CA ? 88.0 ? ?NaN # 5 ? ?Frank ?30.0 ? NaN ? ?NaN ? ?NaN
使用參數(shù)limit,可以指定連續(xù)替換的最大數(shù)量。
print(df.fillna(method='bfill', limit=1)) # name age state point other # 0 Alice 24.0 NY NaN NaN # 1 Charlie NaN CA NaN NaN # 2 Charlie 68.0 CA 70.0 NaN # 3 Dave 68.0 TX 70.0 NaN # 4 Ellen 30.0 CA 88.0 NaN # 5 Frank 30.0 NaN NaN NaN
參考博客:
Pandas刪除,替換并提取其中的缺失值NaN(dropna,fillna,isnull): http://www.dbjr.com.cn/article/233846.htm
總結(jié)
到此這篇關(guān)于Python Pandas中缺失值NaN的判斷,刪除及替換的文章就介紹到這了,更多相關(guān)Pandas缺失值NaN判斷刪除及替換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python缺失值填充方法示例代碼
- Python數(shù)據(jù)預(yù)處理時缺失值的不同處理方式總結(jié)
- Python?數(shù)據(jù)清洗刪除缺失值替換缺失值詳情
- python?sklearn與pandas實(shí)現(xiàn)缺失值數(shù)據(jù)預(yù)處理流程詳解
- Python處理缺失值的8種不同方法實(shí)例
- Python缺失值處理方法
- Python3?DataFrame缺失值的處理方法
- python如何去除異常值和缺失值的插值
- Python數(shù)據(jù)分析之缺失值檢測與處理詳解
- Python數(shù)據(jù)分析的八種處理缺失值方法詳解
- python缺失值的解決方法總結(jié)
- Python中查找缺失值的三種方法
相關(guān)文章
TensorFlow實(shí)現(xiàn)從txt文件讀取數(shù)據(jù)
今天小編就為大家分享一篇TensorFlow實(shí)現(xiàn)從txt文件讀取數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02python中的多線程鎖lock=threading.Lock()使用方式
這篇文章主要介紹了python中的多線程鎖lock=threading.Lock()使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06Python實(shí)現(xiàn)模擬分割大文件及多線程處理的方法
這篇文章主要介紹了Python實(shí)現(xiàn)模擬分割大文件及多線程處理的方法,涉及Python文件讀取、分割及多線程相關(guān)操作技巧,需要的朋友可以參考下2017-10-10python實(shí)現(xiàn)簡單學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python簡單的學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-04-04python?中的?BeautifulSoup?網(wǎng)頁使用方法解析
這篇文章主要介紹了python?中的?BeautifulSoup?網(wǎng)頁使用方法解析,文章基于python的相關(guān)資料展開詳細(xì)內(nèi)容介紹,具有一定的參考價值需要的小伙伴可以參考一下2022-04-04python實(shí)現(xiàn)騰訊滑塊驗(yàn)證碼識別
這篇文章主要介紹了python如何實(shí)現(xiàn)騰訊滑塊驗(yàn)證碼識別,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04深入討論P(yáng)ython函數(shù)的參數(shù)的默認(rèn)值所引發(fā)的問題的原因
這篇文章主要介紹了深入討論P(yáng)ython函數(shù)的參數(shù)的默認(rèn)值所引發(fā)的問題的原因,利用了Python解釋器在內(nèi)存地址分配中的過程解釋了參數(shù)默認(rèn)值帶來陷阱的原因,需要的朋友可以參考下2015-03-03