<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Pandas缺失值處理-判斷和刪除

          共 6024字,需瀏覽 13分鐘

           ·

          2021-08-25 13:10

          一、缺失值概述
          缺失數(shù)據(jù),在大部分數(shù)據(jù)分析中都很常見,Pandas在設計之時,就考慮了這種缺失值的情況并讓這種缺失數(shù)據(jù)處理任務變得輕松,構造了非常強大而又全面的缺失值處理方法,默認情況下,大部分的計算函數(shù)都會自動忽略數(shù)據(jù)集中的缺失值,在很多算法中,還是需要自行處理缺失值。
          缺失值處理流程無非4個方面:檢測、填充、刪除、替換
           
          官方文檔:https://pandas.pydata.org/pandas-docs/stable/reference/frame.html

          函數(shù)列表:
          DataFrame.backfill([axis, inplace, limit, …])
          for DataFrame.fillna() with method='bfill'.
          DataFrame.bfill([axis, inplace, limit, downcast])
          for DataFrame.fillna() with method='bfill'.
          DataFrame.dropna([axis, how, thresh, …])
          Remove missing values.
          DataFrame.ffill([axis, inplace, limit, downcast])
          for DataFrame.fillna() with method='ffill'.
          DataFrame.fillna([value, method, axis, …])
          Fill NA/NaN values using the specified method.
          DataFrame.interpolate([method, axis, limit, …])
          Please note that only method='linear' is supported for DataFrame/Series with a MultiIndex.
          DataFrame.isna()
          Detect missing values.
          DataFrame.isnull()
          Detect missing values.
          DataFrame.notna()
          Detect existing (non-missing) values.
          DataFrame.notnull()
          Detect existing (non-missing) values.
          DataFrame.pad([axis, inplace, limit, downcast])
          for DataFrame.fillna() with method='ffill'.
          DataFrame.replace([to_replace, value, …])
          Replace values given in to_replace with value.
          關于空值的處理,主要有是4個方法,判斷、填充、刪除、替換。
          缺失值檢測,isna或isnull,二者等價,用于判斷一個series或dataframe各元素值是否為空的bool結果。需注意對空值的界定:即None或numpy.nan才算空值,而空字符串、空列表等則不屬于空值;類似地,notna和notnull則用于判斷是否非空
          缺失值填充,fillna,按一定策略對空值進行填充,如常數(shù)填充、向前/向后填充等,也可通過inplace參數(shù)確定是否本地更改
          缺失值刪除,dropna,刪除存在空值的整行或整列,可通過axis設置,也包括inplace參數(shù)
          缺失值替換,replace,非常強大的功能,對series或dataframe中每個元素執(zhí)行按條件替換操作,還可開啟正則表達式功能。
           

          二、缺失值判斷

          Pandas提供了缺失值的檢測方法是 isna 和 isnull,該方法通過布爾值的形式反饋某個值是否為缺失值。這樣就可以便于觀測缺失值,以及后續(xù)進一步地通過編程的方法批量地處理缺失值。isnull還有一個鏡像方法notnull,以應對不同的編程場景。
           

          DataFrame.isna()

          df = pd.DataFrame({'age': [5, 6, np.NaN],                   'born': [pd.NaT, pd.Timestamp('1939-05-27'),                            pd.Timestamp('1940-04-25')],                   'name': ['Alfred', 'Batman', ''],                   'toy': [None'Batmobile''Joker']})df   age       born    name        toy0  5.0        NaT  Alfred       None1  6.0 1939-05-27  Batman  Batmobile2  NaN 1940-04-25              Jokerdf.isna()     age   born   name    toy0  False   True  False   True1  False  False  False  False2   True  False  False  Falseser = pd.Series([5, 6, np.NaN])ser.isna()0    False1    False2     True# 但對于DataFrame我們更關心到底每列有多少缺失值 統(tǒng)計缺失值的個數(shù)df.isna().sum()age     1born    1name    0toy     1

           

          DataFrame.isnull()

          與函數(shù)isna()兩者其實是一樣的,isnull就是一個別名而已
          df.isnull()     age   born   name    toy0  False   True  False   True1  False  False  False  False2   True  False  False  False#統(tǒng)計某一列的缺失值個數(shù)df['age'].isnull().sum()1
           

          DataFrame.notna()

          非空值得個數(shù)
          df.notna() age born name toy0 True False True False1 True True True True2 False True True True
           

          DataFrame.notnull()

          df.notnull() age born name toy0 True False True False1 True True True True2 False True True True
           
          可以通過info()函數(shù)也可以看到缺失值的信息
          df.info()<class 'pandas.core.frame.DataFrame'>RangeIndex: 3 entries, 0 to 2Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 age 2 non-null float64 1 born 2 non-null datetime64[ns] 2 name 3 non-null object 3 toy 2 non-null object dtypes: datetime64[ns](1), float64(1), object(2)memory usage: 224.0+ bytes
           
           

          三、缺失值刪除

          DataFrame.dropna

          函數(shù)作用:
          刪除含有空值的行或列
           
          函數(shù)用法:
          DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)

          具體參數(shù):
          axis:維度,axis=0表示index行,axis=1表示columns列,默認為0
          how:"all"表示這一行或列中的元素全部缺失(為nan)才刪除這一行或列,"any"表示這一行或列中只要有元素缺失,就刪除這一行或列
          thresh:axis中至少有thresh個非缺失值,否則刪除。
          subset:在某些列的子集中選擇出現(xiàn)了缺失值的列刪除,不在子集中的含有缺失值得列或行不會刪除(有axis決定是行還是列)
          inplace:刷選過缺失值得新數(shù)據(jù)是存為副本還是直接在原數(shù)據(jù)上進行修改。默認是False,即創(chuàng)建新的對象進行修改,原對象不變,和深復制和淺復制有些類似。

          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 born0 Alfred NaN NaT1 Batman Batmobile 1940-04-252 Catwoman Bullwhip NaT
          #刪除包含缺失值的行df.dropna() name toy born1 Batman Batmobile 1940-04-25#刪除包含缺失值的列,需要用到參數(shù)axis='columns'df.dropna(axis='columns') name0 Alfred1 Batman2 Catwoman
          df.dropna(how='all') name toy born0 Alfred NaN NaT1 Batman Batmobile 1940-04-252 Catwoman Bullwhip NaT
          df.dropna(thresh=2) name toy born1 Batman Batmobile 1940-04-252 Catwoman Bullwhip NaT
          df.dropna(subset=['name', 'born']) name toy born1 Batman Batmobile 1940-04-25
          df.dropna(inplace=True)df name toy born1  Batman  Batmobile 1940-04-25
          ···  END  ···
          推薦閱讀:
          Pandas中的寶藏函數(shù)-map
          Pandas中的寶藏函數(shù)-apply
          Pandas中的寶藏函數(shù)-applymap
          一文搞懂Pandas數(shù)據(jù)排序
          一網(wǎng)打盡Pandas中的各種索引 iloc,loc,ix,iat,at,直接索引
          Pandas數(shù)據(jù)可視化原來也這么厲害
          Pandas向量化字符串操作
          一、Number(數(shù)字)
          全面掌握Python基礎,這一篇就夠了,建議收藏
          Python基礎之數(shù)字(Number)超級詳解
          Python隨機模塊22個函數(shù)詳解
          Python數(shù)學math模塊55個函數(shù)詳解
          二、String(字符串)
          Python字符串的45個方法詳解
          Pandas向量化字符串操作
          三、List(列表)
          超級詳解系列-Python列表全面解析
          Python輕量級循環(huán)-列表推導式
          四、Tuple(元組)
          Python的元組,沒想象的那么簡單
          五、Set(集合)
          全面理解Python集合,17個方法全解,看完就夠了
          六、Dictionary(字典)
          Python字典詳解-超級完整版
          七、內置函數(shù)
          Python初學者必須吃透這69個內置函數(shù)!
          八、正則模塊
          Python正則表達式入門到入魔
          筆記 | 史上最全的正則表達式
          八、系統(tǒng)操作
          Python之shutil模塊11個常用函數(shù)詳解
          Python之OS模塊39個常用函數(shù)詳解
          九、進階模塊
          【萬字長文詳解】Python庫collections,讓你擊敗99%的Pythoner
          高手如何在Python中使用collections模塊
          掃描關注本號↓
          瀏覽 76
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  一本色道久久综合熟妇人妻 | 人人射视频 | 青青草在线观看免费视频 | 国产avwww| 亚洲无码精品在线观看 |