本文介紹了df.unique() 基于列的整個 DataFrame的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個 DataFrame df
填充有重復 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
...
當我使用時:
uniqueId = df["Id"].unique()
我得到一個唯一 ID 列表.
I get a list of unique IDs.
但是,我怎樣才能在整個 DataFrame 上應用此過濾,以便它保留結構但刪除重復項(基于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
參數 subset
指定測試重復的位置:
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
這篇關于df.unique() 基于列的整個 DataFrame的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!