通常在進行數據分析之前,有一步非常重要的工作要做,就是數據清理,從而保證數據的質量,這也直接關係到數據最終分析和預測結果的準確性。
數據清洗不是一件簡單的任務,大多數情況下這項工作是十分耗時而乏味的,但它又是十分重要的。
如果你經歷過數據清洗的過程,你就會明白我的意思。
在進行數據清洗時,有一些數據具有相似的模式。也正是從那時起,開始整理並編譯了一些數據清洗代碼,我認為這些代碼也適用於其它的常見場景。
由於這些常見的場景涉及到不同類型的數據集,因此本文更加側重於展示和解釋這些代碼可以用於完成哪些工作。
刪除多列數據
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
轉換 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')
將分類變量轉換為數值變量
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)
如果你想要檢查每一列中有多少缺失的數據,這可能是最快的方法。這種方法可以讓你更清楚地知道哪些列有更多的缺失數據,幫助你決定接下來在數據清洗和數據分析工作中應該採取怎樣的行動。
刪除列中的字符串
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」是數據幀 df 中的一列。
刪除列中的空格
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', ' ', regex=True, inplace=True) # replace the 'pil' with emtpy space
當你希望在一定條件下將兩列字符串數據組合在一起時,這種方法很有用。例如,你希望當第一列以某些特定的字母結尾時,將第一列和第二列數據拼接在一起。根據你的需要,還可以在拼接工作完成後將結尾的字母刪除掉。
轉換時間戳(從字符串類型轉換為日期「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'))
在處理時間序列數據時,你可能會遇到字符串格式的時間戳列。這意味著我們可能不得不將字符串格式的數據轉換為根據我們的需求指定的日期「datetime」格式,以便使用這些數據進行有意義的分析和展示。
文章轉自機器學習研究會訂閱號
閱讀更多 AI技術聯盟 的文章