Pandas:여러 열이 같은지 확인하는 방법
다음 방법을 사용하여 팬더에서 여러 열이 동일한지 확인할 수 있습니다.
방법 1: 모든 열이 동일한지 확인
df[' matching '] = df. eq (df. iloc [:, 0], axis= 0 ). all (1)
방법 2: 특정 열이 동일한지 확인
df[' matching '] = df. apply ( lambda x: x.col1 == x.col3 == x.col4 , axis= 1 )
다음 예에서는 다음 pandas DataFrame에서 실제로 각 메서드를 사용하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' A ': [4, 0, 3, 3, 6, 8, 7], ' B ': [4, 2, 3, 5, 6, 4, 7], ' C ': [4, 0, 3, 3, 5, 10, 7], ' D ': [4, 0, 3, 3, 3, 8, 7]}) #view DataFrame print (df) ABCD 0 4 4 4 4 1 0 2 0 0 2 3 3 3 3 3 3 5 3 3 4 6 6 5 3 5 8 4 10 8 6 7 7 7 7
예시 1: 모든 열이 동일한지 확인
다음 구문을 사용하여 DataFrame의 각 열 값이 각 행에 대해 동일한지 확인할 수 있습니다.
#create new column that checks if all columns match in each row df[' matching '] = df. eq (df. iloc [:, 0], axis= 0 ). all (1) #view updated DataFrame print (df) ABCD matching 0 4 4 4 4 True 1 0 2 0 0 False 2 3 3 3 3 True 3 3 5 3 3 False 4 6 6 5 3 False 5 8 4 10 8 False 6 7 7 7 7 True
각 열의 값이 같으면 해당 열은 True 를 반환합니다.
그렇지 않으면 False 를 반환합니다.
참고로 다음과 같이 astype(int)를 사용하여 True 와 False 값을 1 과 0 으로 변환할 수 있습니다.
#create new column that checks if all columns match in each row df[' matching '] = df. eq (df. iloc [:, 0], axis= 0 ). all (1). astype (int) #view updated DataFrame print (df) ABCD matching 0 4 4 4 4 1 1 0 2 0 0 0 2 3 3 3 3 1 3 3 5 3 3 0 4 6 6 5 3 0 5 8 4 10 8 0 6 7 7 7 7 1
예시 2: 특정 열이 동일한지 확인
다음 구문을 사용하여 DataFrame의 A, C, D 열 값이 각 행에서 동일한지 확인할 수 있습니다.
#create new column that checks if values in columns A, C, and D are equal df[' matching '] = df. apply ( lambda x: x. A == x. C == x. D , axis= 1 ) #view updated DataFrame print (df) ABCD matching 0 4 4 4 4 True 1 0 2 0 0 True 2 3 3 3 3 True 3 3 5 3 3 True 4 6 6 5 3 False 5 8 4 10 8 False 6 7 7 7 7 True
A, C, D 열의 값이 동일하면 해당 열은 True 를 반환합니다.
그렇지 않으면 False 를 반환합니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas에서 열 이름을 바꾸는 방법
Pandas DataFrame에 열을 추가하는 방법
Pandas DataFrame에서 열 순서를 변경하는 방법