본문 바로가기

Programing Language/Python

Pandas에서 dataframe 메모리 초기화하기..!

반응형


pandas에서 대용량 데이터를 ram에 올리고 계산을 하다 보면 다음과 같은 상황을 목격하게 된다.

top으로 메모리 사용을 모니터링하다보면, 


   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND       

  3532 root      20   0 37.689g 0.026t   7624 R  88.7 95.8  33:13.73 python3                  

  1847 root      20   0 2763276   7656   2712 S   0.7  0.0   6:02.22 docker-containe         


음....? 메모리가... 넘치려 한다...!
이유는 메모리의 히스토리가 남아서...


pandas는 numpy를 기반으로 만들어져있는데, 


df = pd.read_csv("...")
df = pd.read_csv("...")

이렇게 두번 불러오면 처음에 있던 df가 지워지는 것이 아니라, 로그가 남아있게 된다.


이 때 해법 중 하나가 del을 이용해 df를 지워주는 것이다.


del df

하지만 이마저도 완벽한 해법이 아니다.

이런 경우 numpy가 사용한 메모리는 free가 되지만, 중간에 python 자체가 가져간 메모리는 반환을 하지 않는다는 부분..!!


좀 더 자세한 설명은 다음 영문 글을 참고. (링크)


링크 안에는 자세하게 이유를 설명해주고 마지막 답변에 명쾌한 해법이 숨어있었다.


del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()

핵심은 del[[]] 요 부분이다!!!

이유는 아래와 같이 설명하고 있다.


del df will not be deleted if there are any reference to the df at the time of deletion. So you need to to delete all the references to it with del df to release the memory.

So all the instances bound to df should be deleted to trigger garbage collection.

Use objgragh to check which is holding onto the objects.

100%이해는 안되지만, 직접 사용해본 결과 아주 잘 된다는 사실을 목격했다...!
앞으로도 대용량 계산은 pandas를 이용해서...!

[참고]

링크 : https://stackoverflow.com/questions/39100971/how-do-i-release-memory-used-by-a-pandas-dataframe

반응형