728x90
lambda()
lambda 함수는 함수의 선언과 함수 내의 처리를 한 줄로 변환하는 식
lambda_square = lambda x : x ** 2
lambde_square(6)
--------------------------------------
#result
36
map()
lambda 식을 이용할 때, 인자 값이 여러개일 경우 map()함수를 결합하여 사용
a = [1, 2, 3, 4, 5, 6]
squares = map(lambda x : x ** 2, a)
list(squares)
---------------------------------------
# result
[1, 4, 9, 16, 25]
apply()
행 단위로 연산할 때, apply() 함수 사용
예시) titanic 데이터에서 Name 데이터의 Name 길이를 계산하여 Name_len이라는 칼럼 추가
titanic_df['Name_len'] = titanic_df['Name'].apply(lambda x : len(x))
titanic_df.head(3)
예시 ) 나이에 따라 카테고리 분류 하기
나이별로 카테고리 구분하는 함수 생성
def get_category(age):
cat = ''
if age <= 5: cat = 'Baby'
elif age <= 12: cat = 'Child'
elif age <= 18: cat = 'Teenager'
elif age <= 25: cat = 'Student'
elif age <= 35: cat = 'Young Adult'
elif age <= 60: cat = 'Adult'
else : cat = 'Elderly'
return cat
titanic_df의 Age 칼럼에 위의 함수 apply
titanic_df['Age_cat'] = titanic_df['Age'].apply(lambda x : get_category(x))
titanic_df.head(3)
728x90
'Python > Python 기초문법' 카테고리의 다른 글
[Python] 문자열 포매팅 (0) | 2024.02.01 |
---|---|
파이썬에서 if __name__ == "__main__": 구문 쓰는 이유 (0) | 2024.01.29 |
Python - VScode에서 가상환경 만들기 (0) | 2024.01.21 |
Python - Pandas excel 파일 입출력 및 데이터 불러오기 (0) | 2024.01.08 |
Python - Pandas 데이터 통합하기 (concat, join, merge) (1) | 2024.01.08 |