本文介紹了df.unique() 基于列的整個 DataFrame的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我有一個 DataFrame df
填充有重復(fù) Id 的行和列:
I have a DataFrame df
filled with rows and columns where there are duplicate Id's:
Index Id Type
0 a1 A
1 a2 A
2 b1 B
3 b3 B
4 a1 A
...
當(dāng)我使用時:
uniqueId = df["Id"].unique()
我得到一個唯一 ID 列表.
I get a list of unique IDs.
但是,我怎樣才能在整個 DataFrame 上應(yīng)用此過濾,以便它保留結(jié)構(gòu)但刪除重復(fù)項(基于Id")?
How can I however apply this filtering on the whole DataFrame such that it keeps the structure but that the duplicates (based on "Id") are removed?
推薦答案
看來你需要DataFrame.drop_duplicates
參數(shù) subset
指定測試重復(fù)的位置:
It seems you need DataFrame.drop_duplicates
with parameter subset
which specify where are test duplicates:
#keep first duplicate value
df = df.drop_duplicates(subset=['Id'])
print (df)
Id Type
Index
0 a1 A
1 a2 A
2 b1 B
3 b3 B
<小時>
#keep last duplicate value
df = df.drop_duplicates(subset=['Id'], keep='last')
print (df)
Id Type
Index
1 a2 A
2 b1 B
3 b3 B
4 a1 A
<小時>
#remove all duplicate values
df = df.drop_duplicates(subset=['Id'], keep=False)
print (df)
Id Type
Index
1 a2 A
2 b1 B
3 b3 B
這篇關(guān)于df.unique() 基于列的整個 DataFrame的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!