Python/NumPy | Pandas

[Pandas] compare - DataFrame 비교

비번변경 2024. 2. 14. 18:04

개요

2024.02.09 - [Pandas] DataFrame 비교 - equals에 이어서 DataFrame을 비교할 수 있는 방법 중 하나인 compare에 대해 정리한다.

 

 

DataFrame.compare

DataFrame.compare 함수는 데이터프레임 간 일치 여부를 반환하는 equals와 달리 데이터프레임 간 차이점을 반환한다.

DataFrame.compare(other, align_axis=1, 
                  keep_shape=False, keep_equal=False, 
                  result_names=('self', 'other'))

- other : 비교할 데이터프레임

- align_axis: 비교 결과 정렬 축

- keep_shape : True이면 같은 값을 가진 셀도 포함하여 출력한다.

- keep_equal : True이면 같은 값을 가진 셀의 값도 출력한다. False이면 NaN으로 표기한다.

- result_names : 비교한 데이터프레임의 이름. 원본은 self, 비교할 데이터프레임은 other이다.

 

비교하는 두 데이터프레임의 컬럼 개수와 컬럼 순서, 그리고 행의 수가 동일해야 한다.

 

 

테스트

1. 같은 데이터로 생성한 DataFrame 비교

data = {
    'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'],
    'style': ['cup', 'cup', 'cup', 'pack', 'pack'],
    'rating': [4, 4, 3.5, 15, 5]
}

df_v1 = pd.DataFrame(data)
df_v2 = pd.DataFrame(data)
print(df_v1.compare(df_v2))

동일한 데이터프레임을 비교했으므로 빈 데이터프레임을 반환한다.

 

2. 다른 데이터프레임 비교

df_v2['brand'] = 'Mania'
print(df_v1.compare(df_v2))

기본적으로 차이가 있는 셀만 출력한다.

df_v1.compare(df_v2, align_axis=0)

정렬 축을 인덱스로 지정하면 self, other을 세로로 출력한다.

 

3. 데이터 내용은 같지만 행 순서가 다른 경우

값이 같은 셀은 NaN으로 출력하는 것을 확인할 수 있다.

df_v2 = df_v1.reindex(index=[1, 0, 3, 2, 4]).reset_index(drop=True)
df_v1.compare(df_v2, keep_shape=True)

 

4. 값이 동일한 셀의 값 출력

df_v1.compare(df_v2, keep_shape=True, keep_equal=True)

 

 

참고 문서

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.compare.html

https://wikidocs.net/154558

 

728x90