[kaggle] Pandas Tutorial - 4
4. Grouping and Sorting
Introduction
Map을 사용하면 DataFrame 또는 Series에서 전체열에 대해 한 번에 한 값씩 데이터를 변환할 수 있다. 그러나 우리는 종종 데이터를 그룹화한 다음 데이터가 속한 그룹에 특정한 작업을 수행한다.
아시 겠지만 group by 작업으로 수행을 한다. 또한 데이터를 정렬하는 방법과 더불어 DataFrame을 인덱싱하는 보다 복잡한 방법과 같으 ㄴ몇가지 추가 항목도 다룰 예정입니다.
Groupwise analysis
우리가 지금까지 많이 사용한 함수는 value_counts()함수이다. 우리는 아래와 같은 코드를 작성해서 value_counts()와 동일한 동작을 하도록 할 수 있다.
print(reviews.groupby('points').points.count()
groupby() 함수는 주어진 그룹에 동일한 point 값을 갖는 값들을 묶어서 reviews 그룹을 만든다. 그런 다음 그룹의 각 원소에 대해 points() 열을 잡고 몇 번이나 나타났는지 센다. value_counts()는 groupby() 연산을 줄인 표현일 뿐이다.
우리는 이 데이터에 이전에 배웠던 요약 함수를 적용할 수도 있다. 예를 들어, 각 points값 범주에서 가장 싼 와인을 고르기 위해 우리는 아래와 같이 한다.
reviews.groupby('points').price.min()
생성하는 각그룹은 값이 일치하는 데이터만 포함하는 DataFrame의 슬라이스라고 생각하면 됩니다.이 DataFrame은 apply()방법을 사용하여 직접 액세스할 수 있으며, 우리가 적합하다고 생각하는 방식으로 데이터를 조작할 수 있다. 예를 들어, 데이터 세트의 각 와이너리에서 검토한 첫 번째 와인 이름을 선택하는 한 가지 방법은 다음과 같습니다.
reviews.groupby('winery').apply(lambda df: df.title.iloc[0])
보다 세밀한 제어를 위해 두 개 이상의 열로 그룹화할 수도 있다. 예를 들어 국가별, 도별로 최고의 와인을 선택하는 방법은 다음과 같다.
reviews.groupby(['country', 'province']).apply(lambda df: df.loc[df.points.idxmax()])
언급할 가치가 있는 또 다른 메소드 agg()는 DataFrame에서 여러 개의 다른 함수들을 동시에 실행할 수 있다. 예를 들어 다음과 같이 데이터 집합의 간단한 통계 요약을 생성할 수 있다.
reviews.groupby(['country']).price.agg([len, min, max])
Multi-indexes
지금까지 살펴본 예에서 우리는 단일 레이블인덱스로 DataFrame 또는 Series 객체를 작업해 왔다. groupby()는 우리가 실행하는 연산에 따라 다중 인덱스라고 불리는 결과를 가져온다는 점에서 약간의 차이가 존재한다.
countries_reviewed = reviews.groupby(['country', 'province']).description.agg([len])
countries_reviewed
다중 인덱스는 단일 레벨 인덱스에는 없는 계층 구조를 처리하는 몇가지 방법이 있다. 또한 값을 검색하기 위해 2가지 레벨의 레이블이 필요하다. 다중 인덱스 출력을 처리하는 것은 입문자가 주의해야 하는 부분이다.
countries_reviewed.reset_index()
Sorting
다시 countries_reviewed를 살펴보면, 우리는 그룹화가 값 순서가 아닌 인덱스 순서대로 데이터를 반환한다는 것을 알 수 있다. 즉, groupby의 결과를 출력할 때 행의 순서는 데이터가 아니라 인덱스의 값에 따라 달라진다.
원하는 순서대로 데이터를 얻기 위해서 우리는 데이터를 정렬할 수 있다. sort_values()는 이러할 때 사용하기 편리하다.
countries_reviewed = countries_reviewed.reset_index()
countries_reviewed.sort_values(by='len')
sort_values는 기본적으로 가장 낮은 값이 가장 먼저 나오는 오름차순 정렬로 설정된다.
그러나 대부분의 경우 더 높은 숫자가 먼저 나오는 내림차순을 원한다. 그럴때는
countries_reviewed.sort_values(by='len', ascending=False)
로 사용한다.
인덱스 값을 기준으로 정렬하려면 sort_index()메서드를 사용하면 된다.
countries_reviewed.sort_index()
마지막으로 한 번에 두개 이상의 열을 정렬할 수 있다.
countries_reviewed.sort_values(by=['country', 'len'])
Exercise
1.
Who are the most common wine reviewers in the dataset? Create a Series
whose index is the taster_twitter_handle
category from the dataset, and whose values count how many reviews each person wrote.
# Your code here
reviews_written = ____
# Check your answer
q1.check()
//answer
pd.Series(reviews.groupby("taster_twitter_handle").taster_twitter_handle.count())
2.
What is the best wine I can buy for a given amount of money? Create a Series
whose index is wine prices and whose values is the maximum number of points a wine costing that much was given in a review. Sort the values by price, ascending (so that 4.0
dollars is at the top and 3300.0
dollars is at the bottom).
best_rating_per_price = ____
# Check your answer
q2.check()
reviews.groupby('price').points.max()
3.
What are the minimum and maximum prices for each variety
of wine? Create a DataFrame
whose index is the variety
category from the dataset and whose values are the min
and max
values thereof.
price_extremes = ____
# Check your answer
q3.check()
reviews.groupby("variety").price.agg([min, max])
4.
What are the most expensive wine varieties? Create a variable sorted_varieties
containing a copy of the dataframe from the previous question where varieties are sorted in descending order based on minimum price, then on maximum price (to break ties).
sorted_varieties = ____
# Check your answer
q4.check()
price_extremes.sort_values(by=['min', 'max'], ascending=False)
5.
Create a Series
whose index is reviewers and whose values is the average review score given out by that reviewer. Hint: you will need the taster_name
and points
columns.
reviewer_mean_ratings = ____
# Check your answer
q5.check()
reviews.groupby('taster_name').points.mean()
6.
What combination of countries and varieties are most common? Create a Series
whose index is a MultiIndex
of {country, variety}
pairs. For example, a pinot noir produced in the US should map to {"US", "Pinot Noir"}
. Sort the values in the Series
in descending order based on wine count.
country_variety_counts = ____
# Check your answer
q6.check()
reviews.groupby(['country', 'variety']).size().sort_values(ascending=False)