看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
本内容来自:https://gairuo.com
重复值在数据清洗中经常要删除,本文介绍Pandas如何识别重复值以及如何删除重复值。
重复值的识别
df.duplicated(subset=None, keep='first')可以返回表示重复行的布尔系列,可以指定列。keep参数确定要标记的重复项(如果有),选项有:
first:将除第一次出现的重复值标记为True,默认。
last:将除最后一次出现的重复值标记为True。
False:将所有重复值标记为True。
来实际操作一下:
df = pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
'rating': [4, 4, 3.5, 15, 5]
})
df
'''
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
'''
默认情况下,对于每组重复的值,第一次出现都设置为False,所有其他值设置为True。
df.duplicated()
'''
0 False
1 True
2 False
3 False
4 False
dtype: bool
'''
通过使用“ last”,将每组重复值的最后一次出现设置为False,将所有其他重复值设置为True。
df.duplicated(keep='last')
'''
0 True
1 False
2 False
3 False
4 False
dtype: bool
'''
通过将keep设置为False,所有重复项都为True。
df.duplicated(keep=False)
'''
0 True
1 True
2 False
3 False
4 False
dtype: bool
'''
要在特定列上查找重复项,请使用子集。
df.duplicated(subset=['brand'])
'''
0 False
1 True
2 False
3 True
4 True
dtype: bool
'''
删除重复值
删除重复值的语法为:
df.drop_duplicates(subset=None,
keep='first',
inplace=False,
ignore_index=False)
subset指定的标签或标签序列可选,仅删除某些列重复项,默认情况为使用所有列,其他有:
keep:确定要保留的重复项(如果有)
first : 保留第一次出现的重复项,默认
last : 保留最后一次出现的重复项。
False : 删除所有重复项
inplac:False,是将副本放置在适当位置还是返回副本
ignore_inde:如果为True, 则重新分配自然索引(0, 1, …, n - 1)
操作一下:
df = pd.DataFrame({
'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
'rating': [4, 4, 3.5, 15, 5]
})
df
'''
brand style rating
0 Yum Yum cup 4.0
1 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
'''
默认情况下,它将基于所有列删除重复的行。
df.drop_duplicates()
'''
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
3 Indomie pack 15.0
4 Indomie pack 5.0
'''
要删除特定列上的重复项,请使用子集。
df.drop_duplicates(subset=['brand'])
'''
brand style rating
0 Yum Yum cup 4.0
2 Indomie cup 3.5
'''
要删除重复项并保留最后一次出现,请使用keep。
df.drop_duplicates(subset=['brand', 'style'], keep='last')
'''
brand style rating
1 Yum Yum cup 4.0
2 Indomie cup 3.5
4 Indomie pack 5.0
'''
相关内容
pandas 标记重复订单中的首次与后续记录
2025-12-06 12:26:43
pandas习题 174:找出并删除重复订单
2025-08-31 13:12:05
pandas 比较两个 DataFrame 的差异
2023-11-28 22:31:54
pandas 根据值在其他列中出现的次数指定列值
2023-08-29 09:25:22
pandas 将时间区间展开为年月两列
2023-02-25 08:47:53
pandas 删除列名重复的列
2022-09-18 07:25:12
pandas 使用 groupby 后删除组内的重复数据
2020-12-30 21:50:58
< 缺失值 NA 标量
pandas 教程
pandas 的聚合分组 >
更新时间:2024-08-09 08:39:43
标签:pandas
重复值