8 个机器学习资料清洗 Python 程式码 简洁实用

编译整理 | 乾明
出品 | 量子位(QbitAI)
最近,大资料工程师Kin Lim Lee在Medium上发表了一篇文章,介绍了8个用于资料清洗的Python程式码。
资料清洗,是进行资料分析和使用资料训练模型的必经之路,也是最耗费资料科学家/程序员精力的地方。
这些用于资料清洗的程式码有两个优点:一是由函式编写而成,不用改引数就可以直接使用。二是非常简单,加上注释最长的也不过11行。
在介绍每一段程式码时,Lee都给出了用途,也在程式码中也给出注释。
大家可以把这篇文章收藏起来,当做工具箱使用。
这些资料清洗程式码,一共涵盖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(‘\n‘, ‘‘, regex=True, inplace=True)
# remove all the characters after (including ) for column - col_1
df[‘col_1‘].replace(‘ .*‘, ‘‘, regex=True, 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‘, ‘ ‘, regex=True, 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 %H:%M:%S.%f‘))
原文传送门:
原文 pdf 档案下载:
连结:
提取码:9zmw
-END-

600分钟超长视讯讲解!本书案例具有实用性,例如校园网搜索引擎、小小翻译器、抓取百度图片这些爬虫案例略加修改可以应用到实际专案中;还有通过微信通讯协议开发微信机器人、机器学习的文字分类、基于卷积神经网络的手写体识别等案例;另外是一些大家耳熟能详的游戏案例,例如连连看、推箱子、中国象棋、网络五子棋、两人麻将、人物拼图和飞机大战等游戏。
扫描,京东优惠购书中...
凡是在京东购买使用者,将订单和评价截图发到邮箱[email protected]
将获得额外Python大礼包(如下图样例)

扫码,免费送书