數(shù)據(jù)清洗指南完整分享
? 01-啟動(dòng)階段
import?os
import?pandas?as?pd
import?numpy?as?np
#?顯示當(dāng)前工作路徑
os.getcwd()
#?羅列當(dāng)前路徑下的所有文件
os.listdir()
#?改變工作目錄
os.chdir("/PATH/TO/SAMSHARE")
#?初始化基礎(chǔ)目錄
data_path?=?'./02_data/'
save_path?=?'./03_model/'
output_path?=?'./04_output/'
02-導(dǎo)入數(shù)據(jù)
#?讀取CSV文件
data?=?pd.read_csv(data_path+'data.csv’,?encoding='utf8')?#有時(shí)候用gbk
#?讀取TXT文件
data?=?pd.read_csv(data_path+'data.txt’,?seq='\t',?encoding='utf8')?#有時(shí)候用gbk
#?讀取excel文件
data?=?pd.read_excel(data_path+'data.xlsx')
03-數(shù)據(jù)結(jié)構(gòu)初探
#?查看DataFrame每個(gè)字段的空值情況,數(shù)據(jù)類(lèi)型
df.info()
#?查看DataFrame的形狀
df.shape
#?查看DataFrame的列名
df.columns
#?查看字段的枚舉值數(shù)量
df["type"].nunique()
#?查看字段的枚舉值
df["type"].unique()
#?查看字段的枚舉值統(tǒng)計(jì)
df["species"].value_counts()
04-數(shù)據(jù)空值處理
#?查看空值占比
df.isnull().sum()*100/len(df)
##?丟棄與空值相關(guān)的數(shù)據(jù)?##
#######################
#?刪除所有包含空值的行
df.dropna()
#?刪除所有包含空值的列
df.dropna(axis=1)
#?刪除全部為空值的列
df.dropna(axis=1,?how='all')
##?特殊值替代空值?##
##################
#?空值全部填充為0
df.fillna(0)
#?修改指定位置的值
df.at[1,?"sepal_length"]=?9999
#?用字符串替代空值
df.fillna("data?missing")
#?用均值填充
df.fillna(df.mean())
#?用指定列的均值來(lái)填充指定列
df["sepal_length"].fillna(df["sepal_length"].mean())
05-基礎(chǔ)列操作
#?通過(guò)列名選擇指定“單列”
df["sepal_length"]
#?通過(guò)列名選擇指定“多列”
df[["sepal_length",?"sepal_width",?"petal_length",?"spp"]]
#?通過(guò)數(shù)字選擇指定列(需要連續(xù))
df.iloc[:,?2:4]
#?通過(guò)數(shù)字選擇指定列(不需要連續(xù))
df.iloc[:,?[1,3,4]]
#?丟棄某列
df.drop("sepal_length",?axis=1)
#?添加新列
df['new']?=?df["sepal_length"]*2
#?條件判斷生成新列
df['newcol']?=?["short"?if?i<3?else?"long"?for?i?in?df["sepal_width"]]?
#?枚舉值映射轉(zhuǎn)換
df.replace({"Species":{"setosa":1,?"versicolor":2,?"virginica":3}})
#?計(jì)算指定兩列的均值
df[["sepal_length",?"sepal_width"]].mean()
#?同時(shí)計(jì)算指定兩列的加總和均值
df[["sepal_length",?"sepal_width"]].agg([np.sum,?np.mean])
#?轉(zhuǎn)置DataFrame
df.T
#?把列名轉(zhuǎn)成List
df.columns.tolist()
#?排序
df.sort_values(by?=?"sepal_width",?ascending?=?True)
#?改列名
df.rename(columns={"old_name":?"new_name"})
06-基礎(chǔ)行操作
#?選取指定行的數(shù)據(jù)
df.iloc[3:10,]
#?通過(guò)索引選取指定行的數(shù)據(jù)
df.loc["index1",?"index2"]
#?檢索包含?"關(guān)鍵字"?的行
df[df["species"].isin(["setosa"])]
#?根據(jù)條件篩選行
df.query('sepal_length>=5')?#?方法1
df[df.sepal_length>=?5]?#?方法2
#?根據(jù)指定內(nèi)容篩選出符合要求的行
df[df["petal_length"].isin([0.2,?0.3])]
#?多條件篩選符合要求的行
df[(df.sepal_length>1)?&?(df.species=="setosa")?|?(df.sepal_width<3)]
#?丟棄某行
df.drop(df.index[1])?
07-分組操作
#?返回根據(jù)字段"species"分組的對(duì)象
df.groupby("species")
#?根據(jù)"species"分組,返回"sepal_length"的均值
df["sepal_length"].groupby(df["species"]).mean()
#?所有列根據(jù)字段"species"分組,?返回sum、mean和std的值?
df.groupby("species").agg([np.sum,?np.mean,?np.std])
08-關(guān)聯(lián)操作
##?merge?##
###########
data?=?pd.merge(df1,df2,on='key',how='left')?#?right?outer
##?concat?##
############
#?上下合并
data?=?pd.concat([df1,df2])
#?左右合并
data?=?pd.concat([df1,df2],axis=1)
##?join?##
##########
data?=?df1.join(df2,?how='left',?lsuffix='_1',?rsuffix='_2')評(píng)論
圖片
表情
