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

版权声明:博客版权所有,转载注明出处。 https://blog.csdn.net/qq_33083551/article/details/86593019

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

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

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

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】 各种比赛的攻略文档。

猜你喜欢

转载自blog.csdn.net/qq_33083551/article/details/86593019
今日推荐