数据分析-简单实用的数据清洗代码整合

在这里插入图片描述

数据清洗代码整合

1 删除多列数据

有时,并不是所有列都对我们的分析有用。因此,df.drop函数是一个得心应手的工具去移除指定的列。

def drop_multiple_col(col_names_list,df):
    df.drop(col_names_list,axis=1,inplace=True)
    return df

2 改变数据类型

当一个数据集变大时,我们需要改变dtypes保存。

def change_dtypes(col_int,col_float,df):
    df[col_int] = df[col_int].astype("int32")
    df[col_float] = df[col_float].astype("float32")

3 类变量转换为数值变量

def convert_cat2num(df):
    num_encode = {"col_1":{"YES":1,"NO":0},"col_2":{"WON":1,"LOSE":0,"DRAW":0}}
    df.replace(num_code,inplace=True)

4 检查丢失数据

检查每列中丢失数据的数量,可以理解哪些列有多少丢失数据。

def check_missing_data(df):
    return df.isnull().sum().sort_values(ascending=False)

5 移除列中特殊字符串

def remove_col_str(df):
    # remove a portion of string in a datafram 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)

6 移除列中空格

def remove_col_white_space(df):
    ddf[col] = df[col].str.lstrip()

7 合并列

def concat_col_str_condition(df):
    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)#place the 'pil' with empty space

8 转换时间戳(string到datetime)

def convert_str_datetime(df):
    df.insert(loc=2,column='timestamp',value=pd.to_datetime(df.transdate, format='%Y-%m-%d %H:%M:%S.%f'))
发布了478 篇原创文章 · 获赞 417 · 访问量 32万+

猜你喜欢

转载自blog.csdn.net/Mind_programmonkey/article/details/99619824
今日推荐