파이썬

[판다스] groupby 활용법

suky_da 2024. 1. 30. 14:53

groupby는 말 그대로 그룹으로 묶어주는 것. 

그래서 groupby 그 자체로는 거의 쓸모가 없다. 

그룹을 한 다음에 거기서 뭘 할건지를 정해줘야 한다. 

 

# 'taster_twitter_handle'로 그룹화 한 뒤, taster_twitter_handle 별로 값을 세주기
reviews.groupby(['taster_twitter_handle']).taster_twitter_handle.value_counts()
reviews.groupby('taster_twitter_handle').size()
reviews.groupby('taster_twitter_handle').taster_twitter_handle.count()
>> 셋 다 같은 결과가 나옴, series형식

#price 컬럼으로 그룹화 한 뒤, 각 그룹의 points 컬럼에서 가장 큰 값 구하기
reviews.groupby(['price']).points.max()
>> series 형식

#agg 이용하면 그룹화 한 뒤에 여러개의 함수도 적용 가능
reviews.groupby('variety')['price'].agg([min,max])

#sort_values() 이용하면 컬럼의 값 기준으로 정렬 가능
reviews.groupby('variety').price.agg([min, max]).sort_values(by=['min','max'], ascending=False)

#groupby 안에 컬럼을 여러개 하면 멀티인덱스 설정됨
reviews.groupby(['country','variety']).title.count().sort_values(ascending=False)

 

 


 

참고

https://www.kaggle.com/code/residentmario/grouping-and-sorting

 

Grouping and Sorting

Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources

www.kaggle.com

https://pandas.pydata.org/docs/reference/api/pandas.Series.sort_values.html

 

pandas.Series.sort_values — pandas 2.2.0 documentation

If not None, apply the key function to the series values before sorting. This is similar to the key argument in the builtin sorted() function, with the notable difference that this key function should be vectorized. It should expect a Series and return an

pandas.pydata.org