聊聊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)
# 說明duplicated()是對整行進(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)過一次的行數(shù)據(jù)了。所以看起來有點(diǎn)confuse,感覺(1,b)并沒有重復(fù),但其實(shí)人家的函數(shù)很簡潔呢,返回了重復(fù)值而且不冗余。
# 說明drop_duplicates()函數(shù)是將所有重復(fù)的數(shù)據(jù)都去掉了,且默認(rèn)保留重復(fù)數(shù)據(jù)的第一條。# 比如(2,d)出現(xiàn)了3次,在duplicated()中顯示了2次,在drop_dupicates()后保留了一個frame.drop_duplicates().shape$ (4,2)
# 留下了完全唯一的數(shù)據(jù)行frame.drop_duplicates()
補(bǔ)充:python的pandas重復(fù)值處理(duplicated()和drop_duplicates())
一、生成重復(fù)記錄數(shù)據(jù)import numpy as npimport 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ù)數(shù)據(jù)isDplicated=df.duplicated() #判斷重復(fù)數(shù)據(jù)記錄isDplicated
輸出:
#刪除重復(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_df1new_df2new_df3new_df4
輸出:
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JS中map和parseInt的用法詳解2. 爬取今日頭條Ajax請求3. ASP.NET Core按用戶等級授權(quán)的方法4. HTML DOM setInterval和clearInterval方法案例詳解5. 詳解JSP 內(nèi)置對象request常見用法6. JavaScrip簡單數(shù)據(jù)類型隱式轉(zhuǎn)換的實(shí)現(xiàn)7. ASP常用日期格式化函數(shù) FormatDate()8. webpack高級配置與優(yōu)化詳解9. HTML <!DOCTYPE> 標(biāo)簽10. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享
