Pandas dataframe 객체끼리 == 연산자를 사용할 때의 동작
Pandas DataFrame.rename 메서드 실습을 진행하다가
DataFrame.rename 메서드에서 inplace 옵션을 True로 설정하지 않으면
새 df 객체를 반환한다는 것을 알게되었다.
확인을 위해 원본 dataframe과 inplace=False로 행,및 열을 교체한 dataframe을
== 연산자로 비교해보았다.
파이썬 기본 객체처럼 True나 False가 반환될 줄 알았지만
반환되는 것은 boolean 객체가 아니라 True, False를 원소로 가지고 있는 2차원 배열이었다.
id()를 통해 dataframe 자체는 다른 객체임을 확인했지만
==, eq 연산자가 예상한대로 작동하지 않아서
pandas의 DataFrame class에 대해 조금 파보았다.
pandas DataFrame 에서의 __eq__
def _flex_cmp_method(self, other, op, *, axis: Axis = "columns", level=None):
axis = self._get_axis_number(axis) if axis is not None else 1
self, other = self._align_for_op(other, axis, flex=True, level=level)
new_data = self._dispatch_frame_op(other, op, axis=axis)
return self._construct_result(new_data)
@Appender(ops.make_flex_doc("eq", "dataframe"))
def eq(self, other, axis: Axis = "columns", level=None) -> DataFrame:
return self._flex_cmp_method(other, operator.eq, axis=axis, level=level)
위는 진입점 코드를 복사해서 옮겨놓은 것.
_dispatch_frame_op 메서드로 right에 전달되는 instance가 DataFrame인 경우
_mgr.operate_blockwise 연산을 수행한다.
_construct_result 메서드로 산술, 비교, 논리 연산 결과를 wrapping하여 return한다.
operate_blockwise 메서드는
dataframe내 원소들을 돌면서 인수로 전달된 array_op 함수에 따라 연산을 수행한다.
좌, 우 데이터프레임의 Blockwise 연산이며
행, 열이 일치하는 dataframe객체에서 -> assert를 통해 일치하지 않으면 예외처리
원소끼리의 연산을 하는 함수이다.
DataFrame 레벨에서의 일치 여부를 계산하는 함수가 아니다.
정리
pandas DataFrame에서의 __eq__ 메서드는
python 객체의 __eq__와 작동방식이 다르기 때문에
dataframe a == dataframe b의 결과가 boolean으로 나오지 않는다.
댓글
댓글 쓰기