[판다스] map에서 lambda 쓰기, apply 쓰기
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. (For simplicity, let's ignore the capitalized versions of these words.)
=> 문장 내에 "tropical" 또는 "fruity" 라고 평가한 와인은 몇개가 있냐? (대문자 신경쓰지 마=빼라는 뜻)
Solution:
n_trop = reviews.description.map(lambda desc: "tropical" in desc).sum()
n_fruity = reviews.description.map(lambda desc: "fruity" in desc).sum()
descriptor_counts = pd.Series([n_trop, n_fruity], index=['tropical', 'fruity'])
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.
def star_rate(df):
if df.country == 'Canada' or df.points >= 95:
return 3
elif df.points < 95 and df.points >= 85:
return 2
else : return 1
# 데이터프레임에 함수 적용할 때, axis로 적용방향 설정해주기
star_ratings = reviews.apply(star_rate, axis = 'columns')
참고
https://tykimos.github.io/2020/01/01/Python_Lambda_Map/
파이썬 람다(lambda)랑 맵(map) 케미 - 람다시리즈 3부
본격적으로 람다의 활용이 돋보이는 예제를 살펴보겠습니다. 람다와 맵이 케미를 이루면 아래와 같은 코드로 한 줄 구구단을 만들 수 있습니다. 아직 람다가 생소하신 분은 아래 링크를 먼저 봐
tykimos.github.io
데이터 프레임에 함수 적용: map, apply, applymap 완벽 정리
안녕하세요. 모두의 케빈입니다. 오늘은 map, apply, applymap의 정의와 각각의 차이점을 완벽하게 예제를 활용하여 설명해드리도록 하겠습니다. ■ 메서드 설명 [요약] map, apply 메서드의 차이는 거의
kevinitcoding.tistory.com
https://www.kaggle.com/code/residentmario/summary-functions-and-maps/tutorial
Summary Functions and Maps
Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources
www.kaggle.com