我需要使用 Pandas 检查数据帧的一列中是否有重复值,如果有重复值,则删除整行。 我只需要检查第一列。
示例:
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]:
答案 0 :(得分:0)
通过重复的掩码选择并否定它
df = df[~df["object"].duplicated()]
哪个给了
object type
0 apple fruit
1 ball toy
2 banana fruit
3 xbox videogame
答案 1 :(得分:0)
使用drop_duplicates方法
d = pd.DataFrame(
{'object': ['apple', 'ball', 'banana', 'xbox', 'banana', 'apple'],
'type': ['fruit', 'toy', 'fruit', 'videogame', 'fruit', 'fruit']}
)
d.drop_duplicates()
有几个关键字参数。这可能会派上用场(例如 inplace=True
,如果您希望更新数据框 d
)
答案 2 :(得分:0)
您可以使用带有参数subset='object'
的{{3}}来选择要检查的列,如下所示:
df_out = df.drop_duplicates(subset='object')
结果:
print(df_out)
object type
0 apple fruit
1 ball toy
2 banana fruit
3 xbox videogame