Python 八个数据清洗实例代码详解

Miles
Miles
发布时间:2026-10-16 | 4人浏览过
原创

本文整理了八个Python数据清洗的常见场景及对应代码,涵盖删除多列、转换数据类型、分类变量数值化、检查缺失值、处理字符串异常及空格、条件拼接字符串以及时间戳转换。通过封装函数,帮助开发者高效完成数据预处理工作,提升数据分析效率。

经历过数据清洗工作的人深知其繁琐与重要。撰写本文旨在帮助读者更轻松地应对这一环节。

近期,我注意到许多数据清洗任务中存在相似的模式。基于此,我整理并编译了一系列适用于常见场景的数据清洗代码片段。

鉴于这些场景涉及不同类型的数据集,本文重点展示并解释这些代码的具体用途,以便读者能更便捷地将其应用于实际工作中。

数据清洗小工具箱

以下代码片段将数据清洗逻辑封装为独立函数,目的直观明确。你可以直接调用这些函数,无需将其嵌入复杂的参数修改流程中。

1. 删除多列数据


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

并非所有列都对数据分析有价值。使用「df.drop」可以方便地移除选定的列。

2. 转换 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')

处理大规模数据集时,转换「dtypes」有助于节省内存。若对使用「Pandas」处理大数据感兴趣,推荐阅读「Why and How to Use Pandas with Large Data」一文(https://towardsdatascience.com/why-and-how-to-use-pandas-with-large-data-9594dda2ea4c)。

3. 将分类变量转换为数值变量


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)  

部分机器学习模型要求输入为数值型变量,因此需将分类变量转换为数值。对于数据可视化任务,建议保留分类变量,以便获得更明确且易于理解的可视化结果。

4. 检查缺失的数据


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)

这是快速统计每列缺失数据数量的有效方法。它能清晰展示哪些列缺失数据较多,从而辅助你决定后续数据清洗和分析的策略。

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」代表数据帧 df 中的特定列。

6. 删除列中的空格


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

数据混乱时易出现意外情况,如字符串开头包含空格。使用该方法可有效删除列中字符串开头的空格。

7. 将两列字符串数据(在一定条件下)拼接起来


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

当需要在特定条件下将两列字符串数据组合时,此方法十分实用。例如,若第一列以特定字母结尾,可将第一列与第二列数据拼接。根据需求,还可选择拼接后删除结尾的特定字母。

8. 转换时间戳(从字符串类型转换为日期「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」格式,以便进行有意义的分析和展示。

至此,关于Python八个数据清洗实例代码的详解介绍完毕。如需了解更多Python数据清洗内容,欢迎搜索本站往期文章或继续阅读后续相关教程,感谢大家的支持!

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表