Python/Pandas&Numpy

pandas functions - cut, qcut

metamong 2022. 3. 23.

♠'cut' documentation

https://pandas.pydata.org/docs/reference/api/pandas.cut.html 

 

♠'qcut' documentation

https://pandas.pydata.org/docs/reference/api/pandas.qcut.html 

1. cut ✂️

 bin values into discrete intervals. Use cut when you need to segment and sort data values into bins. This function is also useful for going from a continuous variable to a categorical variable. For example, cut could convert ages to groups of age ranges. Supports binning into an equal number of bins, or a pre-specified array of bins.

- 동일 길이의 구간으로 나눠 각 data를 분포시킴

- 아니면 나누고 싶은 구간을 임의로 정해서 [] list로 만들고 인자에 집어넣을 수도 있다.

 

pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise', ordered=True)[source]

 

→ ex)

 

x = np.array([1,2,3,4,100,101,200])
pd.cut(x,3)

 

- 200을 동일한 간격의 세 구간 (0~67) (67~133) (133~200)으로 나눔 -

 

 

→ 주로 cut의 결과로 만들어진 data는 따로 한 column으로 만들어 기존 dataframe에 추가하는 형식인 case가 빈번..!

 

+

 

✌️ continuous data를 구간별로 나누는 categorical data로 바꾸기 위해 cut을 사용한다고 위 docu()에서 언급함!

(titanic data를 예를 들어 확인해보자)

 

pd.cut(titanic.age, bins=[0,18,25,99], labels = ['child', 'young adult', 'adult'])

 

≫ 'bins'를 통해 주어진 data를 원하는 구간대로 나눌 수 있고, 나눠진 bin 각각 이름을 'labels'라는 인자를  통해 설정이 가능하다

 

≫ 결과

 

- 나눠진 data는 모두 category로 바꼈으며 series 형태로 출력이 되었다 -

 

≫ 바뀐 Series를 기존 column에 대체할 수 있다. FE 과정에서 더 나은 modelling의 성능을 위해 categorical column으로 바꾸는 과정에서 cut을 빈번하게 사용할 수 있다.

2. qcut ✂️

 Quantile-based discretization function. Discretize variable into equal-sized buckets based on rank or based on sample quantiles. For example 1000 values for 10 quantiles would produce a Categorical object indicating quantile membership for each data point.

- 나뉜 구간에 각각 데이터의 개수가 최대한 동일하도록 분포

 

pandas.qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise')

 

→ ex)

 

x = np.array([1,2,3,4,100,101,200])
pd.qcut(x,3)

 

- 구간 길이는 다르지만 구간 내 data 개수가 거의 균일 - 

 

 

** 한마디로, cut) 나누는 간격길이 자체를 동일하게 나눔 (해당 간격 내에 몇 개의 자료가 들어있는 지는 상관하지 않음)

** 하지만, qcut) 나누는 간격이 서로 동일하지는 않더라도, 나뉜 간격 내의 자료 개수가 간격별로 동일하게 설정함

 

* cut 일부 출처) https://www.youtube.com/watch?v=RlIiVeig3hc 

댓글