pandas
重复值
看过来
《pandas 教程》 持续更新中,可作为 pandas 入门进阶课程、pandas 中文手册、用法大全,配有案例讲解和速查手册。提供建议、纠错、催更等加作者微信: gairuo123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。查看更新日志。作者开办 Python 数据分析培训,详情 Python 数据分析培训。
![]() |
本教程作者所著新书《Python之光:Python编程入门与实战》(ISBN:9787111729891)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
![]() |
本教程作者所著新书《深入浅出Pandas:利用Python进行数据处理与分析》(ISBN:9787111685456)已由机械工业出版社出版上市,各大电商平台有售,欢迎:查看详情并关注购买。 |
重复值在数据清洗中经常要删除,本文介绍Pandas如何识别重复值以及如何删除重复值。
df.duplicated(subset=None, keep='first')
可以返回表示重复行的布尔系列,可以指定列。keep参数确定要标记的重复项(如果有),选项有:
来实际操作一下:
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指定的标签或标签序列可选,仅删除某些列重复项,默认情况为使用所有列,其他有:
操作一下:
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
'''