聊聊python中令人迷惑的duplicated和drop_duplicates()用法
在算face_track_id map有感:
開始驗證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()是對整行進行查重,return 重復了的數(shù)據(jù),且只現(xiàn)實n-1條重復的數(shù)據(jù)(n是重復的次數(shù))frame[frame.duplicated() == True]
一開始還很疑惑,明明(1,b)只出現(xiàn)了1次,哪里duplicate了。其實,人家return的結果是去掉已經(jīng)出現(xiàn)過一次的行數(shù)據(jù)了。所以看起來有點confuse,感覺(1,b)并沒有重復,但其實人家的函數(shù)很簡潔呢,返回了重復值而且不冗余。

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

補充:python的pandas重復值處理(duplicated()和drop_duplicates())
一、生成重復記錄數(shù)據(jù)import numpy as npimport pandas as pd #生成重復數(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
輸出:

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

#刪除重復值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)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關文章:

網(wǎng)公網(wǎng)安備