聊聊python中令人迷惑的duplicated和drop_duplicates()用法
在算face_track_id map有感:
開始驗(yàn)證
data={'state':[1,1,2,2,1,2,2,2],'pop':['a','b','c','d','b','c','d','d']}
frame=pd.DataFrame(data)
frame

frame.shape $ (8,2)
# 說(shuō)明duplicated()是對(duì)整行進(jìn)行查重,return 重復(fù)了的數(shù)據(jù),且只現(xiàn)實(shí)n-1條重復(fù)的數(shù)據(jù)(n是重復(fù)的次數(shù)) frame[frame.duplicated() == True]
一開始還很疑惑,明明(1,b)只出現(xiàn)了1次,哪里duplicate了。其實(shí),人家return的結(jié)果是去掉已經(jīng)出現(xiàn)過(guò)一次的行數(shù)據(jù)了。所以看起來(lái)有點(diǎn)confuse,感覺(1,b)并沒有重復(fù),但其實(shí)人家的函數(shù)很簡(jiǎn)潔呢,返回了重復(fù)值而且不冗余。

# 說(shuō)明drop_duplicates()函數(shù)是將所有重復(fù)的數(shù)據(jù)都去掉了,且默認(rèn)保留重復(fù)數(shù)據(jù)的第一條。 # 比如(2,d)出現(xiàn)了3次,在duplicated()中顯示了2次,在drop_dupicates()后保留了一個(gè) frame.drop_duplicates().shape $ (4,2)
# 留下了完全唯一的數(shù)據(jù)行 frame.drop_duplicates()

補(bǔ)充:python的pandas重復(fù)值處理(duplicated()和drop_duplicates())
一、生成重復(fù)記錄數(shù)據(jù)
import numpy as np import pandas as pd #生成重復(fù)數(shù)據(jù) df=pd.DataFrame(np.ones([5,2]),columns=['col1','col2']) df['col3']=['a','b','a','c','d'] df['col4']=[3,2,3,2,2] df=df.reindex(columns=['col3','col4','col1','col2']) #將新增的一列排在第一列 df
輸出:

二、判斷重復(fù)記錄(行)
#判斷重復(fù)數(shù)據(jù) isDplicated=df.duplicated()#判斷重復(fù)數(shù)據(jù)記錄 isDplicated
輸出:

三、刪除重復(fù)值
#刪除重復(fù)值 new_df1=df.drop_duplicates() #刪除數(shù)據(jù)記錄中所有列值相同的記錄 new_df2=df.drop_duplicates(['col3']) #刪除數(shù)據(jù)記錄中col3列值相同的記錄 new_df3=df.drop_duplicates(['col4']) #刪除數(shù)據(jù)記錄中col4列值相同的記錄 new_df4=df.drop_duplicates(['col3','col4']) #刪除數(shù)據(jù)記錄中(col3和col4)列值相同的記錄 new_df1 new_df2 new_df3 new_df4
輸出:


以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信