<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>

          8個Python數(shù)據(jù)清洗代碼,拿來即用

          共 5568字,需瀏覽 12分鐘

           ·

          2021-06-03 13:13


          作者:Admond Lee

          編譯:機器之心(almosthuman2014)

          原文:

          https://towardsdatascience.com/the-simple-yet-practical-data-cleaning-codes-ad27c4ce0a38


          大家好,歡迎來到 Crossin的編程教室 !


          不管你承不承認,數(shù)據(jù)清洗著實不是一件簡單的任務(wù),大多數(shù)情況下這項工作是十分耗時而乏味的,但它又是十分重要的。


          如果你經(jīng)歷過數(shù)據(jù)清洗的過程,你就會明白我的意思。而這正是撰寫這篇文章的目的——讓讀者更輕松地進行數(shù)據(jù)清洗工作。


          事實上,我在不久前意識到,在進行數(shù)據(jù)清洗時,有一些數(shù)據(jù)具有相似的模式。也正是從那時起,我開始整理并編譯了一些數(shù)據(jù)清洗代碼(見下文),我認為這些代碼也適用于其它的常見場景。


          由于這些常見的場景涉及到不同類型的數(shù)據(jù)集,因此本文更加側(cè)重于展示和解釋這些代碼可以用于完成哪些工作,以便讀者更加方便地使用它們。


          我的數(shù)據(jù)清洗小工具箱


          在下面的代碼片段中,數(shù)據(jù)清洗代碼被封裝在了一些函數(shù)中,代碼的目的十分直觀。你可以直接使用這些代碼,無需將它們嵌入到需要進行少量參數(shù)修改的函數(shù)中。


          1. 刪除多列數(shù)據(jù)


          def drop_multiple_col(col_names_list, df): 
              '''
              AIM    -> Drop multiple columns based on their column names 

              INPUT  -> List of column names, df

              OUTPUT -> updated df with dropped columns 
              ------
              '''

              df.drop(col_names_list, axis=1, inplace=True)
              return df


          有時,并不是所有列的數(shù)據(jù)都對我們的數(shù)據(jù)分析工作有用。因此,「df.drop」可以方便地刪掉你選定的列。



          2. 轉(zhuǎn)換 Dtypes


          def change_dtypes(col_int, col_float, df): 
              '''
              AIM    -> Changing dtypes to save memory

              INPUT  -> List of column names (int, float), df

              OUTPUT -> updated df with smaller memory  
              ------
              '''

              df[col_int] = df[col_int].astype('int32')
              df[col_float] = df[col_float].astype('float32')


          當(dāng)我們面對更大的數(shù)據(jù)集時,我們需要對「dtypes」進行轉(zhuǎn)換,從而節(jié)省內(nèi)存。如果你有興趣學(xué)習(xí)如何使用「Pandas」來處理大數(shù)據(jù),我強烈推薦你閱讀「Why and How to Use Pandas with Large Data」這篇文章(https://towardsdatascience.com/why-and-how-to-use-pandas-with-large-data-9594dda2ea4c)。


          3. 將分類變量轉(zhuǎn)換為數(shù)值變量


          def convert_cat2num(df):
              # Convert categorical variable to numerical variable
              num_encode = {'col_1' : {'YES':1'NO':0},
                            'col_2'  : {'WON':1'LOSE':0'DRAW':0}}  
              df.replace(num_encode, inplace=True)  


          有一些機器學(xué)習(xí)模型要求變量是以數(shù)值形式存在的。這時,我們就需要將分類變量轉(zhuǎn)換成數(shù)值變量然后再將它們作為模型的輸入。對于數(shù)據(jù)可視化任務(wù)來說,我建議大家保留分類變量,從而讓可視化結(jié)果有更明確的解釋,便于理解。


          4. 檢查缺失的數(shù)據(jù)


          def check_missing_data(df):
              # check for any missing data in the df (display in descending order)
              return df.isnull().sum().sort_values(ascending=False)


          如果你想要檢查每一列中有多少缺失的數(shù)據(jù),這可能是最快的方法。這種方法可以讓你更清楚地知道哪些列有更多的缺失數(shù)據(jù),幫助你決定接下來在數(shù)據(jù)清洗和數(shù)據(jù)分析工作中應(yīng)該采取怎樣的行動。


          5. 刪除列中的字符串


          def remove_col_str(df):
              # remove a portion of string in a dataframe column - col_1
              df['col_1'].replace('\n''', regex=True, inplace=True)

              # remove all the characters after &# (including &#) for column - col_1
              df['col_1'].replace(' &#.*''', regex=True, inplace=True)


          有時你可能會看到一行新的字符,或在字符串列中看到一些奇怪的符號。你可以很容易地使用 df['col_1'].replace 來處理該問題,其中「col_1」是數(shù)據(jù)幀 df 中的一列。



          6. 刪除列中的空格


          def remove_col_white_space(df):
              # remove white space at the beginning of string 
              df[col] = df[col].str.lstrip()


          當(dāng)數(shù)據(jù)十分混亂時,很多意想不到的情況都會發(fā)生。在字符串的開頭有一些空格是很常見的。因此,當(dāng)你想要刪除列中字符串開頭的空格時,這種方法很實用。


          7. 將兩列字符串?dāng)?shù)據(jù)(在一定條件下)拼接起來


          def concat_col_str_condition(df):
              # concat 2 columns with strings if the last 3 letters of the first column are 'pil'
              mask = df['col_1'].str.endswith('pil', na=False)
              col_new = df[mask]['col_1'] + df[mask]['col_2']
              col_new.replace('pil'' ', regex=True, inplace=True)  # replace the 'pil' with emtpy space


          當(dāng)你希望在一定條件下將兩列字符串?dāng)?shù)據(jù)組合在一起時,這種方法很有用。例如,你希望當(dāng)?shù)谝涣幸阅承┨囟ǖ淖帜附Y(jié)尾時,將第一列和第二列數(shù)據(jù)拼接在一起。根據(jù)你的需要,還可以在拼接工作完成后將結(jié)尾的字母刪除掉。


          8. 轉(zhuǎn)換時間戳(從字符串類型轉(zhuǎn)換為日期「DateTime」格式)


          def convert_str_datetime(df): 
              '''
              AIM    -> Convert datetime(String) to datetime(format we want)

              INPUT  -> df

              OUTPUT -> updated df with new datetime format 
              ------
              '''

              df.insert(loc=2, column='timestamp', value=pd.to_datetime(df.transdate, format='%Y-%m-%d %H:%M:%S.%f'))


          在處理時間序列數(shù)據(jù)時,你可能會遇到字符串格式的時間戳列。這意味著我們可能不得不將字符串格式的數(shù)據(jù)轉(zhuǎn)換為根據(jù)我們的需求指定的日期「datetime」格式,以便使用這些數(shù)據(jù)進行有意義的分析和展示。


          以上便是清洗數(shù)據(jù)的一些簡單卻實用的代碼,在你進行數(shù)據(jù)分析項目時一定派上用場。


          如果文章對你有幫助,歡迎轉(zhuǎn)發(fā)/點贊/收藏~



          _往期文章推薦_

          清洗數(shù)據(jù),我習(xí)慣用這7步




          如需了解付費精品課程教學(xué)答疑服務(wù)
          請在Crossin的編程教室內(nèi)回復(fù): 666

          瀏覽 78
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

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

          手機掃一掃分享

          分享
          舉報
          <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>
                  青娱乐人操 | 色天堂免费下载 | 少妇无套内谢久久 | 国产无码自拍视频 | 黄色视频a|