一.前言
最近剛好在練手一個(gè)數(shù)據(jù)挖掘的項(xiàng)目,眾所周知,數(shù)據(jù)挖掘中比較重要的一步為數(shù)據(jù)清洗,而對(duì)重復(fù)數(shù)據(jù)的處理也是數(shù)據(jù)清洗中經(jīng)常碰到的一項(xiàng)。本文將僅介紹如何利用Pandas來清除重復(fù)數(shù)據(jù)(主要指重復(fù)行),話不多說請(qǐng)看下文。
二.具體介紹
2.1. 導(dǎo)入Pandas庫(kù)
pandas是python的核心數(shù)據(jù)分析庫(kù),你可以把它理解為python版的excel,倘若你還沒有安裝相應(yīng)的庫(kù),請(qǐng)查詢相關(guān)教程進(jìn)行安裝,導(dǎo)入pandas的代碼為:
import pandas as pd
2.2. DataFrame.duplicated和DataFrame.drop_duplicates
2.2.1. duplicated函數(shù)
duplicated函數(shù)的功能為:Return boolean Series denoting duplicate rows,即返回一個(gè)標(biāo)識(shí)重復(fù)行的布爾類型的數(shù)組(Series),其中重復(fù)行將標(biāo)識(shí)為true,而非重復(fù)行將標(biāo)識(shí)為false。
要介紹該函數(shù)的功能,首先我隨意創(chuàng)建一個(gè)DataFrame對(duì)象,該對(duì)象的數(shù)據(jù)如下:
對(duì)應(yīng)的創(chuàng)建代碼為
import pandas as pd#利用字典創(chuàng)建DataFrame對(duì)象animal={'class':['mammal','reptile','bird','mammal','bird','bird','reptile','mammal'], 'name':['humans','lizard','dove','monkey','dove','dove','snake','monkey'], 'max_speed':[42.5,56,130,79.6,130,130,66.6,79.6]}df = pd.DataFrame(animal)
應(yīng)用duplicated函數(shù)便可以得到對(duì)應(yīng)的bool數(shù)組,對(duì)應(yīng)的代碼行為
print(df.duplicated())'''對(duì)應(yīng)的運(yùn)行結(jié)果為 0 False 1 False 2 False 3 False 4 True 5 True 6 False 7 True dtype: bool'''
當(dāng)然,在應(yīng)用該函數(shù)時(shí),我們可以為其指定參數(shù),其原型為DataFrame.duplicated(self,subset,keep),其中:
subset參數(shù)用來指定用來識(shí)別重復(fù)的列標(biāo)簽/列標(biāo)簽序列,當(dāng)未指定時(shí)默認(rèn)比較整行的所有列來判別是否重復(fù);
keep參數(shù)用來指定如何標(biāo)記重復(fù)行,它的值有三個(gè):first,last,False。當(dāng)選擇first時(shí),重復(fù)行中除了第一次出現(xiàn)的全部標(biāo)記為True;當(dāng)選擇last時(shí),重復(fù)行中除最后一次出現(xiàn)的全部標(biāo)記為True;當(dāng)選擇False時(shí),所有重復(fù)行都將標(biāo)記為True。
上述參數(shù)的代碼示例為
#指定subset為classprint(df.duplicated('class'))'''對(duì)應(yīng)的運(yùn)行結(jié)果 0 False 1 False 2 False 3 True 4 True 5 True 6 True 7 True dtype: bool'''#指定subset為class,nameprint(df.duplicated(['class','name']))'''對(duì)應(yīng)的運(yùn)行結(jié)果 0 False 1 False 2 False 3 False 4 True 5 True 6 False 7 True dtype: bool'''#指定keep為lastprint(df.duplicated(subset=['class','name'],keep='last'))'''對(duì)應(yīng)的運(yùn)行結(jié)果 0 False 1 False 2 True 3 True 4 True 5 False 6 False 7 False dtype: bool'''
新聞熱點(diǎn)
疑難解答
圖片精選