[英]How to delete duplicates, but keep the first instance and a blank cell for the duplicates in Pandas?
[英]How to delete duplicates pandas
我需要使用 Pandas 檢查 dataframe 的一列中是否有一些重復值,如果有任何重復,請刪除整行。 我只需要檢查第一列。
例子:
object type
apple fruit
ball toy
banana fruit
xbox videogame
banana fruit
apple fruit
我需要的是:
object type
apple fruit
ball toy
banana fruit
xbox videogame
我可以使用以下代碼刪除“對象”重復項,但我無法刪除包含重復項的整行,因為不會刪除第二列。
df = pd.read_csv(directory, header=None,)
objects= df[0]
for object in df[0]:
Select 通過重復的掩碼和否定它
df = df[~df["object"].duplicated()]
這使
object type
0 apple fruit
1 ball toy
2 banana fruit
3 xbox videogame
使用drop_duplicates方法
d = pd.DataFrame(
{'object': ['apple', 'ball', 'banana', 'xbox', 'banana', 'apple'],
'type': ['fruit', 'toy', 'fruit', 'videogame', 'fruit', 'fruit']}
)
d.drop_duplicates()
有幾個關鍵字參數。 這可能會派上用場(比如 inplace inplace=True
如果你想更新你的 dataframe d
)
您可以使用帶有參數subset='object'
.drop_duplicates()
到select要檢查的列,如下:
df_out = df.drop_duplicates(subset='object')
結果:
print(df_out)
object type
0 apple fruit
1 ball toy
2 banana fruit
3 xbox videogame
刪除重復項后獲取長度
df = len(df)-len(df.drop_duplicates())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.