Pandas重复记录处理

2019-08-14  本文已影响0人  neumeng

Pandas重复记录处理

1 概述

Pandas提供了duplicatedIndex.duplicateddrop_duplicates函数来标记及删除重复记录。

duplicated函数用于标记Series中的值、DataFrame中的记录行是否是重复,重复为True,不重复为False

函数定义:

其中参数解释如下:

2 标记DataFrame重复例子

# 引入numpy和pandas
import numpy as np
import pandas as pd
df = pd.DataFrame({'col1': ['one', 'one', 'two', 'two', 'two', 'three', 'four'], 'col2': [1, 2, 1, 2, 1, 1, 1],
   'col3':['AA','BB','CC','DD','EE','FF','GG']},index=['a', 'a', 'b', 'c', 'b', 'a','c'])
df
(index) col1 col2 col3
a one 1 AA
a one 2 BB
b two 1 CC
c two 2 DD
b two 1 EE
a three 1 FF
c four 1 GG

2.1 根据列名标记

#keep='first'
df.duplicated()#默认所有列,无重复记录
a    False
a    False
b    False
c    False
b    False
a    False
c    False
dtype: bool
#keep='first'
df.duplicated('col1')#第二、四、五行被标记为重复
a    False
a     True
b    False
c     True
b     True
a    False
c    False
dtype: bool
#keep='first'
df.duplicated(['col1','col2'])#第五行被标记为重复
a    False
a    False
b    False
c    False
b     True
a    False
c    False
dtype: bool
#keep='last'
df.duplicated('col1','last')#第一、三、四行被标记重复
a     True
a    False
b     True
c     True
b    False
a    False
c    False
dtype: bool
df.duplicated(['col1','col2'],keep='last')#第三行被标记为重复
a    False
a    False
b     True
c    False
b    False
a    False
c    False
dtype: bool
#keep=False
df.duplicated('col1',False)
a     True
a     True
b     True
c     True
b     True
a    False
c    False
dtype: bool
#keep=False
df.duplicated(['col1','col2'],keep=False)
a    False
a    False
b     True
c    False
b     True
a    False
c    False
dtype: bool
type(df.duplicated(['col1','col2'],keep=False))
pandas.core.series.Series

2.2 根据索引标记

df.index.duplicated()#默认keep='first',第二、五、七行被标记为重复
array([False,  True, False, False,  True,  True,  True])
df.index.duplicated(keep='last')#第一、二、三、四被标记为重复
array([ True,  True,  True,  True, False, False, False])
df[df.index.duplicated()]#获取重复记录行
(index) col1 col2 col3
a one 2 BB
b two 1 EE
a three 1 FF
c four 1 GG
df[~df.index.duplicated('last')]#获取不重复记录行
(index) col1 col2 col3
b two 1 EE
a three 1 FF
c four 1 GG

3 标记Series重复例子

s = pd.Series(['one', 'one', 'two', 'two', 'two', 'three', 'four'] ,index= ['a', 'a', 'b', 'c', 'b', 'a','c'],name='sname')
s
a      one
a      one
b      two
c      two
b      two
a    three
c     four
Name: sname, dtype: object
s.duplicated()
a    False
a     True
b    False
c     True
b     True
a    False
c    False
Name: sname, dtype: bool
s.duplicated('last')
a     True
a    False
b     True
c     True
b    False
a    False
c    False
Name: sname, dtype: bool
s.duplicated(False)
a     True
a     True
b     True
c     True
b     True
a    False
c    False
Name: sname, dtype: bool
s.index.duplicated()
array([False,  True, False, False,  True,  True,  True])
s.index.duplicated('last')
array([ True,  True,  True,  True, False, False, False])
s.index.duplicated(False)
array([ True,  True,  True,  True,  True,  True,  True])

上一篇下一篇

猜你喜欢

热点阅读