pandas.DataFrame.duplicated—返回表示重复行的布尔集合

发布时间 2023-06-08 22:08:16作者: yayagogogo

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.duplicated.html

语法格式

DataFrame.duplicated(subset=Nonekeep='first')

参数解释:

  • suset: 指定某些列来标识重复项,默认情况下使用所有列;
  • keep: 确定标记哪些重复值。接受‘first’, ‘last’, False"first"表示将重复值第一次出现以外的其他情况标记为True"last"表示将重复值最后一次出现以外的其他情况标记为TrueFalse表示将所有的重复均标记为True。默认为"first"

返回由每个重复行的布尔series。

代码示例

import pandas as pd

d1 = [[3,"negative",2],[4,"negative",6],[11,"positive",0],[12,"positive",2],[4,"negative",6],[3,"negative",6]]
df1 = pd.DataFrame(d1, columns=["ID","result","value"])
print(df1)

#  ID    result  value
# 0   3  negative      2
# 1   4  negative      6
# 2  11  positive      0
# 3  12  positive      2
# 4   4  negative      6
# 5   3  negative      6

df1.duplicated() #默认根据所有列将重复值第一次出现以外的其他情况标记为True
# 0    False
# 1    False
# 2    False
# 3    False
# 4     True
# 5    False
# dtype: bool

df1.duplicated(subset="ID",keep=False) #根据ID列将所有的重复均标记为True
# 0     True
# 1     True
# 2    False
# 3    False
# 4     True
# 5     True
# dtype: bool

df1.duplicated(keep="last") #将重复值最后一次出现以外的其他情况标记为True
# 0    False
# 1     True
# 2    False
# 3    False
# 4    False
# 5    False
# dtype: bool