3.Summary Functions and Maps
Introduction
이때동안은 관련 데이터를 선택하는 방법을 다뤘다. 하지만 데이터는 항상 우리가 원하는 형식대로 나타나지 않는다. 때로는 데이터 포맷을 바꾸기 위해 직접 몇가지 작업을 더 해야한다. 이번에는 데이터에 적용할 수 있는 다양한 작업에 대해 설명한다.
Summary functions
Pandas는 데이터를 유용한 방식으로 재구성하는 많은 요약기능을 제공한다.
print(reviews.points.describe())
describe() 메소드는 지정된 열의 속성에 대한 높은 수준의 요약을 생성한다. 입력의 데이터 유형에 따라 출력이 변경된다는 의미인 유형 인식이다. 위의 출력은 숫자 데이터에 대해서만 적합하여 문자열 데이터의 경우 다음과같이 얻을 수 있다.
print(reviews.taster_name.describe())
DataFrame이나 Series의 특정 통계 값들만을 알고 싶다면 이를 위한 함수또한 지원한다. 예를 들어 points의 평균을 알고 싶다면 mean()함수를 사용한다.
print(reviews.points.mean())
고유값 목록을 보고 싶다면 unique()함수를 사용한다.
print(reviews.taster_name.unique())
고유한 값의 목록과 데이터 집합에서 발생하는 빈도를 보려면 value_counts()방법을 사용한다.
print(reviews.taster_name.value_counts())
Maps
수학에서 차용한 용어로, 한 집합의 값을 다른 값의 집합에 매핑하는 함수.
데이터 과학에서는 기존 데이터로 새로운 표현을 만들거나 현재 형식에서 나중에 원하는 형식으로 데이터를 변환해야하는 경우가 많다. map은 이러한 작업을 할때 매우 중요하다.
map을 사용할 때 우리가 자주 사용하는 방법은 2가지이다.
map()이 첫번째 방법이다. 예를 들어 와인의 points의 평균을 0으로 만들고 싶으면 다음과 같다.
review_points_mean = reviews.points.mean()
print(reviews.points.map(lambda p: p - review_points_mean))
map()의 인자로 전달되는 함수는 Series에서 단일값을 받아 그 값의 변형된 버전을 리턴하는 함수여야 한다.
map()은 전달된 함수에 의해 바뀐 값들을 가진 새로운 Series를 리턴한다.
apply()는 만약 우리가 DataFrame의 각 행에 함수를 적용하고 싶다면 map과 동일하게 사용할 수 있다.
def remean_points(row):
row.points = row.points - review_points_mean
return row
reviews.apply(remean_points, axis='columns')
apply with axis='index'를 호출 했다면 각 행을 변환하는 함수를 전달하는 대신 각 열을 변환하는 함수를 제공해야 한다.
map()과 apply()는 각각 변환된 새로운 Series 및 DataFrame을 반환한다. 원본객체를 수정하는 것은 아니니 주의해서 사용할 필요가 있다.
Pandas는 일반적인 지도 제작 기능을 내장하고 있다. 예를 들어 포인트 열을 재측정하는 더 빠른 방법은 다음과 같다.
review_points_mean = reviews.points.mean()
print(reviews.points - review_points_mean)
왼쪽의 전체의 값과 오른쪽의 평균값 사이의 연산을 수행한다. pandas는 이 식을 보고 우리가 전체 데이터 셋에서 평균값을 뺄려는 것을 알 수 있다.
Pandas는 같은 길이의 Series 사이에서 이러한 작업을 수행할 경우 어떻게 해야하는지도 알고 있다. 예를 들어 데이터 셋의 country와 region_1 열의 데이터를 쉽게 결합하는 방법은 아래와 같다.
reviews.country + " - " + reviews.region_1
이러한 연산은 판다스 내부의 연산이므로 map과 apply보다 더 빠르다.
그러나 조건부 논리를 적용하는 등 덧셈과 뺄셈만으로 하지 못하는 복잡한 연산은 map과 apply가 더 유연하다.
Exercise
1.
What is the median of the points
column in the reviews
DataFrame?
median_points = ____
# Check your answer
q1.check()
//answer
reviews.points.median()
2.
What countries are represented in the dataset? (Your answer should not include any duplicates.)
countries = ____
# Check your answer
q2.check()
//answer
reviews.country.unique()
3.
How often does each country appear in the dataset? Create a Series reviews_per_country
mapping countries to the count of reviews of wines from that country.
reviews_per_country = ____
# Check your answer
q3.check()
reviews.country.value_counts()
4.
Create variable centered_price
containing a version of the price
column with the mean price subtracted.
(Note: this 'centering' transformation is a common preprocessing step before applying various machine learning algorithms.)
centered_price = ____
# Check your answer
q4.check()
//answer
reviews.price - reviews.price.mean()
5.
5.
I'm an economical wine buyer. Which wine is the "best bargain"? Create a variable bargain_wine
with the title of the wine with the highest points-to-price ratio in the dataset.
bargain_wine = ____
# Check your answer
q5.check()
//answer
reviews.loc[(reviews.points/reviews.price).idxmax(),'title']
6.There are only so many words you can use when describing a bottle of wine. Is a wine more likely to be "tropical" or "fruity"? Create a Series descriptor_counts
counting how many times each of these two words appears in the description
column in the dataset.
descriptor_counts = ____
# Check your answer
q6.check()
//answer
descriptor = ['tropical','fruity']
n_trop = reviews.description.map(lambda desc: 'tropical' in desc).sum()
n_fruit = reviews.description.map(lambda desc: 'fruity' in desc).sum()
descriptor_counts = pd.Series([n_trop,n_fruit],index=descriptor,name='Descriptor')
7.
We'd like to host these wine reviews on our website, but a rating system ranging from 80 to 100 points is too hard to understand - we'd like to translate them into simple star ratings. A score of 95 or higher counts as 3 stars, a score of at least 85 but less than 95 is 2 stars. Any other score is 1 star.
Also, the Canadian Vintners Association bought a lot of ads on the site, so any wines from Canada should automatically get 3 stars, regardless of points.
Create a series star_ratings
with the number of stars corresponding to each review in the dataset.
star_ratings = ____
# Check your answer
q7.check()
//answer
def stars(row):
if row.country == 'Canada':
return 3
elif row.points >= 95:
return 3
elif row.points >= 85:
return 2
else:
return 1
star_ratings = reviews.apply(stars,axis='columns')
'MachineLearning' 카테고리의 다른 글
[kaggle] Pandas Tutorial - 6 (0) | 2022.05.27 |
---|---|
[kaggle] Pandas Tutorial - 5 (0) | 2022.05.27 |
[kaggle] Pandas Tutorial - 4 (0) | 2022.05.27 |
[kaggle] Pandas Tutorial - 2 (0) | 2022.05.27 |
[kaggle] Pandas Tutorial - 1 (0) | 2022.05.27 |