是否有一种方法可以检查数据框列中是否有重复的值而不删除行?我有一个将删除重复行的函数,但是,仅当特定列中确实存在重复项时,我才希望它运行。
当前,我将列中的唯一值的数量与行的数量进行比较:如果唯一值的数量少于行,那么重复的代码就会运行。
if len(df['Student'].unique()) < len(df.index):
# Code to remove duplicates based on Date column runs
是否有使用熊猫来检查特定列中是否存在重复值的更简单或更有效的方法?
我正在使用的一些示例数据(仅显示两列)。如果发现重复,则另一个函数标识要保留的行(日期最早的行):
Student Date
0 Joe December 2017
1 James January 2018
2 Bob April 2018
3 Joe December 2017
4 Jack February 2018
5 Jack March 2018
一列中是否有重复值,True / False]
╔═════════╦═══════════════╗
║ Student ║ Date ║
╠═════════╬═══════════════╣
║ Joe ║ December 2017 ║
╠═════════╬═══════════════╣
║ Bob ║ April 2018 ║
╠═════════╬═══════════════╣
║ Joe ║ December 2018 ║
╚═════════╩═══════════════╝
假设上面的数据帧(df),我们可以快速检查是否在Student
列中通过以下方式重复:
boolean = any(df['Student'].duplicated()) # True
以上我们使用的是Pandas系列方法之一。熊猫DataFrame有几个有用的methods,其中两个是:
这些方法可以整体应用于DataFrame,而不仅限于上面的Serie(列)。等效为:
boolean = any(df.duplicated(subset=['Student'])) # True
# We were expecting True, as Joe can be seen twice.
但是,如果我们对整个框架感兴趣,我们可以继续做:
boolean = any(df.duplicated()) # False
boolean = any(df.duplicated(subset=['Student','Date'])) # False
# We were expecting False here - no duplicates row-wise
# ie. Joe Dec 2017, Joe Dec 2018
还有最后一个有用的提示。通过使用keep
参数,我们通常可以跳过几行直接访问所需的内容:
保持:{'first','last',False},默认为'first'
import pandas as pd
import io
data = '''\
Student,Date
Joe,December 2017
Bob,April 2018
Joe,December 2018'''
df = pd.read_csv(io.StringIO(data), sep=',')
# Approach 1: Simple True/False
boolean = any(df.duplicated(subset=['Student']))
print(boolean, end='\n\n') # True
# Approach 2: First store boolean array, check then remove
duplicate_in_student = df.duplicated(subset=['Student'])
if any(duplicate_in_student):
print(df.loc[~duplicate_in_student], end='\n\n')
# Approach 3: Use drop_duplicates method
df.drop_duplicates(subset=['Student'], inplace=True)
print(df)
返回
True
Student Date
0 Joe December 2017
1 Bob April 2018
Student Date
0 Joe December 2017
1 Bob April 2018
除了DataFrame.duplicated
和DataFrame.duplicated
,熊猫还具有Series.duplicated
和Series.duplicated
。
DataFrame.any
检查重复项:
DataFrame.any
对于Python≥3.8,如果需要访问重复的行,请考虑使用Series.any
以避免重新计算重复的行:
Series.any