8 段用于数据清洗 Python 代码

2019 年 10 月 29 日 数据库开发

(给数据分析与开发加星标,提升数据技能

原作 Kin Lim Lee
乾明 编译整理
量子位 出品 | 公众号 QbitAI
最近,大数据工程师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(  &#.* , , 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 )) 
最后,附上原文传送门~
https://towardsdatascience.com/the-simple-yet-practical-data-cleaning-codes-ad27c4ce0a38


看完本文有收获?请转发分享给更多人

关注「数据分析与开发」加星标,提升数据技能

好文章,我在看❤️

登录查看更多
1

相关内容

分类变量(categorical variable)是说明事物类别的一个名称,其取值是分类数据。如“性别”就是一个分类变量,其变量值为“男”或“女”;“行业”也是一个分类变量,其变量值可以为“零售业”、“旅游业”、“汽车制造 业”等。
【实用书】学习用Python编写代码进行数据分析,103页pdf
专知会员服务
190+阅读 · 2020年6月29日
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
【干货书】用于概率、统计和机器学习的Python,288页pdf
专知会员服务
281+阅读 · 2020年6月3日
Python地理数据处理,362页pdf,Geoprocessing with Python
专知会员服务
110+阅读 · 2020年5月24日
干净的数据:数据清洗入门与实践,204页pdf
专知会员服务
160+阅读 · 2020年5月14日
算法与数据结构Python,369页pdf
专知会员服务
160+阅读 · 2020年3月4日
吐血整理!140种Python标准库、第三方库和外部工具都有了
炼数成金订阅号
14+阅读 · 2019年7月30日
一文看懂怎么用 Python 做数据分析
大数据技术
23+阅读 · 2019年5月5日
Python中机器学习的特征选择工具
云栖社区
8+阅读 · 2018年7月16日
实战 | 用Python做图像处理(三)
七月在线实验室
15+阅读 · 2018年5月29日
快乐的迁移到 Python3
Python程序员
5+阅读 · 2018年3月25日
教你用Python来玩跳一跳
七月在线实验室
6+阅读 · 2018年1月2日
python pandas 数据处理
Python技术博文
3+阅读 · 2017年8月30日
Meta-Learning to Cluster
Arxiv
17+阅读 · 2019年10月30日
A Survey on Deep Transfer Learning
Arxiv
11+阅读 · 2018年8月6日
Feature Selection Library (MATLAB Toolbox)
Arxiv
7+阅读 · 2018年8月6日
Arxiv
5+阅读 · 2018年3月28日
VIP会员
相关VIP内容
【实用书】学习用Python编写代码进行数据分析,103页pdf
专知会员服务
190+阅读 · 2020年6月29日
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
【干货书】用于概率、统计和机器学习的Python,288页pdf
专知会员服务
281+阅读 · 2020年6月3日
Python地理数据处理,362页pdf,Geoprocessing with Python
专知会员服务
110+阅读 · 2020年5月24日
干净的数据:数据清洗入门与实践,204页pdf
专知会员服务
160+阅读 · 2020年5月14日
算法与数据结构Python,369页pdf
专知会员服务
160+阅读 · 2020年3月4日
相关资讯
吐血整理!140种Python标准库、第三方库和外部工具都有了
炼数成金订阅号
14+阅读 · 2019年7月30日
一文看懂怎么用 Python 做数据分析
大数据技术
23+阅读 · 2019年5月5日
Python中机器学习的特征选择工具
云栖社区
8+阅读 · 2018年7月16日
实战 | 用Python做图像处理(三)
七月在线实验室
15+阅读 · 2018年5月29日
快乐的迁移到 Python3
Python程序员
5+阅读 · 2018年3月25日
教你用Python来玩跳一跳
七月在线实验室
6+阅读 · 2018年1月2日
python pandas 数据处理
Python技术博文
3+阅读 · 2017年8月30日
Top
微信扫码咨询专知VIP会员