1. 程式人生 > 程式設計 >8段用於資料清洗Python程式碼(小結)

8段用於資料清洗Python程式碼(小結)

最近,大資料工程師Kin Lim Lee在Medium上發表了一篇文章,介紹了8個用於資料清洗的Python程式碼。

資料清洗,是進行資料分析和使用資料訓練模型的必經之路,也是最耗費資料科學家/程式設計師精力的地方。

這些用於資料清洗的程式碼有兩個優點:一是由函式編寫而成,不用改引數就可以直接使用。二是非常簡單,加上註釋最長的也不過11行。在介紹每一段程式碼時,Lee都給出了用途,也在程式碼中也給出註釋。大家可以把這篇文章收藏起來,當做工具箱使用。

涵蓋8大場景的資料清洗程式碼

這些資料清洗程式碼,一共涵蓋8個場景,分別是:

刪除多列、更改資料型別、將分類變數轉換為數字變數、檢查缺失資料、刪除列中的字串、刪除列中的空格、用字串連線兩列(帶條件)、轉換時間戳(從字串到日期時間格式)

刪除多列

在進行資料分析時,並非所有的列都有用,用df.drop可以方便地刪除你指定的列。

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

轉換資料型別

當資料集變大時,需要轉換資料型別來節省記憶體。

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 )

將分類變數轉換為數值變數

一些機器學習模型要求變數採用數值格式。這需要先將分類變數轉換為數值變數。同時,你也可以保留分類變數,以便進行資料視覺化。

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) 

檢查缺失資料

如果你要檢查每列缺失資料的數量,使用下列程式碼是最快的方法。可以讓你更好地瞭解哪些列缺失的資料更多,從而確定怎麼進行下一步的資料清洗和分析操作。

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)

刪除列中的字串

有時候,會有新的字元或者其他奇怪的符號出現在字串列中,這可以使用df[‘col_1'].replace很簡單地把它們處理掉。

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

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

刪除列中的空格

資料混亂的時候,什麼情況都有可能發生。字串開頭經常會有一些空格。在刪除列中字串開頭的空格時,下面的程式碼非常有用。

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

用字串連線兩列(帶條件)

當你想要有條件地用字串將兩列連線在一起時,這段程式碼很有幫助。比如,你可以在第一列結尾處設定某些字母,然後用它們與第二列連線在一起。根據需要,結尾處的字母也可以在連線完成後刪除。

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,inplace=True) # replace the pil with emtpy space

轉換時間戳(從字串到日期時間格式)

在處理時間序列資料時,我們很可能會遇到字串格式的時間戳列。這意味著要將字串格式轉換為日期時間格式(或者其他根據我們的需求指定的格式) ,以便對資料進行有意義的分析。

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。