机器学习-数据整理or数据清洗

本文深入探讨了数据清洗的重要性和常见步骤,包括使用Pandas进行数据加载、基本信息查看、数据可视化、数据类型转换、缺失值处理、字符串清理及时间戳转换等关键操作。通过具体实例,如房价数据的分析,展示了如何有效清洗和预处理数据,为机器学习模型训练做好准备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

尝试了几次比赛后,感觉到所有的源数据,都是不规则,多样,杂乱的。符合客观实际情况。

在这种情况下,我们往往需要对数据进行清洗。

甚至已经成为了一种套路,不管三七二十一,先查看数据源特点,整理数据,总是没错的。

1:引入pandas包

import pandas as pd

train_data = pd.read_csv(r'./source data/train.csv')

2:最简单的,直接看数据信息。用info。

print(all_data.info()) 

3:导入画图,直接形象的对比和看。

import matplotlib.pyplot as plt
import seaborn as sns

例子:

#研究分析房价数据分布
print(train_data['SalePrice'].describe())
sns.set_style("whitegrid")
sns.distplot(train_data['SalePrice'])


#居住面积和房价
fig, ax =plt.subplots()
ax.scatter( x  = train_data['GrLivArea'], y = train_data['SalePrice'])
plt.ylabel('SalePrice')
plt.xlabel('GrLivArea')
plt.show()

4:常用的功能

4.1 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

清除某一列。

4.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')

4.3 标签转换(可以考虑one-hot编码)

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.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)

4.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)

尤其是CSV和其他格式互转。多一个逗号,多一个空格,多一个'\n’之类的。

4.6 删除空格

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

4.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

比如:当第一列以某些特定的字母结尾时,将第一列和第二列数据拼接在一起。

4.8 时间戳转换。(string ---->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'))

 

未完待续

欢迎关注,有什么问题,大家共同讨论,:

参考文献

【1】 https://towardsdatascience.com/the-simple-yet-practical-data-cleaning-codes-ad27c4ce0a38

【2】 各种比赛的攻略文档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值