오늘 할 일: 끝내주게 숨쉬기

파이썬에서 tabular 형식으로 갖춰진 데이터를 다룰 때 보통 판다스를 가장 먼저 사용하죠. 판다스는 칼럼이 가질 수 있는 자료형으로 숫자, 문자, 날짜, boolen(True or False) 등을 지원합니다. 판다스로 데이터프레임을 다뤄보다가 문득 object 형식과 category 형식이 정확히 어떤 차이인지 궁금해졌어요. 그래서 이 포스팅에서는 두 형식의 개념과 차이에 대해 알아보고자 합니다.

 

판다스에서 자료형으로 사용되는 object와 category의 개념은 다음과 같이 이해할 수 있습니다.

 

object

판다스에서는 문자열을 object라는 자료형으로 나타냅니다. 파이썬에서는 문자열을 string이라고 하지만, 판다스는 object라고 합니다. pd.DataFrame을 사용하여 데이터프레임을 만들때 dtype(형식)을 지정해주는게 아니라면 일반적으로 데이터를 받아들일 때 숫자형을 제외한 나머지는 object로 받아들이는 것 같아요. (경험상 그랬던 것 같습니다)

 

category

category 형식은 가능한 값들의 범위가 고정되어있고, 한정적일 때 매우 사용한다고 합니다. 공식문서에 따르만 다음과 같은 경우에 유용하다고 하니 참고하세요.

  • A string variable consisting of only a few different values. Converting such a string variable to a categorical variable will save some memory, see here.
  • The lexical order of a variable is not the same as the logical order (“one”, “two”, “three”). By converting to a categorical and specifying an order on the categories, sorting and min/max will use the logical order instead of the lexical order, see here.
  • As a signal to other Python libraries that this column should be treated as a categorical variable (e.g. to use suitable statistical methods or plot types).

 

와! 이제 object와 category가 분명 차이가 있다는 걸 이해했습니다.

요약하자면 일반적인 문자열을 갖는 칼럼은 object로 사용하고, 값이 종류가 제한적일 때 category를 사용하면 되겠네요.

예를 들어, 아침식사 여부에 대한 칼럼이라면 값을 0=먹지않음, 1=먹음 으로 두 종류만 갖게 되겠죠. 반대로 아침식사 종류에 대한 칼럼이라면 샐러드, 소고기, 바나나 하나, 샌드위치, 어제 먹다 남은 마라탕(?) 등 다양한 값을 가질 수 있게 됩니다. 이 경우 아침식사 여부는 category, 아침식사 종류는 object로 지정해주면 효율적으로 데이터 프레임을 관리할 수 있겠죠.

 

데이터 형식에 따라 가질 수 있는 값의 범위가 다르고, 메모리 사용공간에도 차이가 있다고 합니다. 불필요한 메모리 사용량을 줄이기 위해 데이터를 잘 파악하고 알맞은 형식을 지정해주는 습관을 들입시다. 끝!

 

참고

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html

 

Categorical data — pandas 1.2.4 documentation

Constructing a Series from a Categorical will not copy the input Categorical. This means that changes to the Series will in most cases change the original Categorical: Note This also happens in some cases when you supply a NumPy array instead of a Categori

pandas.pydata.org

https://stackoverflow.com/questions/30601830/when-to-use-category-rather-than-object

 

When to use Category rather than Object?

I have a CSV dataset with 40 features that I am handling with Pandas. 7 features are continuous (int32) and the rest of them are categorical. My question is : Should I use the dtype('category') of

stackoverflow.com