[Python] Pandas: 7. 중복값 처리(drop_duplicates(), duplicated())

Jae Gyeong Lee·2024년 5월 2일
import pandas as pd

data_list = [['A', 'Math', '2002'],
             ['A', 'psychology', '2001'],
             ['B', 'Computer', '1999'],
             ['H', 'Computer', '1996'],
             ['C', 'Communication', '1995'],
             ['C', 'Communication', '1997'],
             ['D', 'Language', '2000'],
             ['D', 'Language', '2000'],
             ['E', 'psychology', '2001']]
             
df = pd.DataFrame(data_list, columns = ['Name', 'Major', 'Born'])

df
>>>
	Name	Major	Born
0	A	Math	2002
1	A	psychology	2001
2	B	Computer	1999
3	H	Computer	1996
4	C	Communication	1995
5	C	Communication	1997
6	D	Language	2000
7	D	Language	2000
8	E	psychology	2001

1. 중복값 확인

DataFrame.duplicated(subset=None, keep='first')
 - subset: 중복값을 확인할 column 설정
 - keep: 중복값이 있을 때, True로 반환할 값의 위치 설정

DataFrame.duplicated()

1.1) row에 있는 모든 값이 같은 경우만 True 반환

df.duplicated()
>>>
0    False
1    False
2    False
3    False
4    False
5    False
6    False
7     True
8    False
dtype: bool

1.2) 특정 column 내 값(1개)만 중복되어도, '중복'으로 볼 경우

# 'Name' column 내 중복된 값이 있는 경우 True 반환
df.duplicated(['Name']) 
>>>
0    False
1     True
2    False
3    False
4    False
5     True
6    False
7     True
8    False
dtype: bool

1.3) 특정 column 내 값(2개)만 중복되어도, '중복'으로 볼 경우

# 'Name' column 과 'Major' column 모두 중복된 값이 있는 경우 True 반환
df.duplicated(['Name', 'Major'])
>>>
0    False
1    False
2    False
3    False
4    False
5     True
6    False
7     True
8    False
dtype: bool

2. 중복값 삭제

DataFrame.drop_duplicates(subset=None, *, keep='first', inplace=False, ignore_index=False)

 - subset: 중복값을 확인할 column 설정
 - keep: 중복값이 있을 때, 삭제할 값의 위치 설정

DataFrame.drop_duplicates()

2.1) row에 있는 모든 값이 같은 경우 삭제

df.drop_duplicates()
>>>
	Name	Major	Born
0	A	Math	2002
1	A	psychology	2001
2	B	Computer	1999
3	H	Computer	1996
4	C	Communication	1995
5	C	Communication	1997
6	D	Language	2000
8	E	psychology	2001

2.2) 특정 column 내 값(1개)이 중복되면 삭제

# 'Name' column 내 중복된 값이 있는 경우 삭제
df.drop_duplicates(['Name'])
>>>
	Name	Major	Born
0	A	Math	2002
2	B	Computer	1999
3	H	Computer	1996
4	C	Communication	1995
6	D	Language	2000
8	E	psychology	2001

2.3) 특정 column 내 값(2개)이 중복되면 삭제

# 'Name' column 과 'Major' column 모두 중복된 값이 있는 경우 삭제
df.drop_duplicates(['Name', 'Major'])
>>>
	Name	Major	Born
0	A	Math	2002
1	A	psychology	2001
2	B	Computer	1999
3	H	Computer	1996
4	C	Communication	1995
6	D	Language	2000
8	E	psychology	2001

2.4) 삭제할 값의 위치 설정: keep 옵션 사용

  • default: first
#앞에 있는 값을 살리고자 할 시, keep = 'first'
df.drop_duplicates(['Name'], keep = 'first')
#뒤에 있는 값을 살리고자 할 시, keep = 'last'
df.drop_duplicates(['Name'], keep = 'last')

참고)

profile
안녕하세요 반갑습니다. 공부한 내용들을 기록하고 있습니다.

0개의 댓글