꺼내먹는지식 준

groupby, size, reset_index 조합 본문

카테고리 없음

groupby, size, reset_index 조합

알 수 없는 사용자 2023. 10. 27. 11:47

groupby 메소드 자체는 그룹을 생성하기만 하고, 실제로 어떤 연산을 수행하지는 않는다.

 

그래서 groupby만 단독으로 사용하면 그 자체로는 큰 의미가 없다.

 

일반적으로 groupby 뒤에 다른 연산 메소드(예: sum, mean, size, max, min 등)를 붙여서 그룹별로 어떤 계산을 할지 지정한다.

 

예를 들어, df.groupby(['date', 'positive']).size().

 

data_df.groupby(['date', 'positive', 'free']).size()

 

 

size() 를 붙여서 지정한 각 그룹에 대한 개수를 얻어올 수 있다. free 라는 column 이 추가 되자 더 세분화된 것을 알 수 있다. 

 

 

data_df.groupby(['date', 'positive']).size().reset_index()

 

다음과 같이 index 가 새로운 column 이 되고, index 는 초기화 된다. 기존에 size() 없이 reset_index() 를 한다면, 앞단의 index 가 새로운 column 이 되고 index가 초기화 된다. 보통 drop = True 를 파라미터로 주어 초기화 되도록 많이 사용한다. 

 

data_df.groupby(['date', 'positive']).size().reset_index(name='count')

 

 

다음과 같이 name 을 설정하는 경우가 많다. 

 

간단하게 자주 사용하는 groupby size count 에 관한 용례를 정리해봤다. 

Comments