新知榜官方账号
2023-09-18 19:40:33
通常在进行数据分析之前,有一步非常重要的工作要做,就是数据清理,从而保证数据的质量,这也直接关系到数据最终分析和预测结果的准确性。数据清洗不是一件简单的任务,大多数情况下这项工作是十分耗时而乏味的,但它又是十分重要的。如果你经历过数据清洗的过程,你就会明白我的意思。在进行数据清洗时,有一些数据具有相似的模式。也正是从那时起,开始整理并编译了一些数据清洗代码,我认为这些代码也适用于其它的常见场景。由于这些常见的场景涉及到不同类型的数据集,因此本文更加侧重于展示和解释这些代码可以用于完成哪些工作。
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)
这种方法可以检查数据集中是否有缺失的数据。
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 whitespace 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)
这种方法可以将数据集中满足一定条件的两列字符串数据拼接在一起。
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」格式。
以上是数据清洗中常用的技巧和代码,希望对您有所帮助。
相关工具
相关文章
推荐
亲测真香!这6个AI工具让工作效率翻倍,同事追着问链接
2025-06-17 16:21
FLUX.1 Kontext 一出,AI生图领域 “地震” 了!
2025-06-06 15:38
用Deepseek写AI绘图提示词,像呼吸一样简单!
2025-02-19 16:12
你以为AI绘画是黑科技?其实早成了“路边摊生意”!
2025-02-19 10:15
Flux爆火,全网最全面最详细的Flux使用教程!
2025-02-18 14:19
用AI如何创作音乐,实战教学来啦!
2025-02-17 17:23
MidJourney让你秒变绘画大神,从零开始画哪吒!
2025-02-17 14:56
AI应用新境界:让人工智能成为你的得力助手
2025-02-14 15:45
AI短片革命:当创作遇上智能,人人都能成为导演
2025-02-14 14:53
AI狂潮下的人类职场:是失业危机还是进化契机?
2025-02-13 16:53