[Python] 04. Apply & Map

hhyun·2024년 6월 19일

[Python]

목록 보기
4/11

📖 Apply & Map

  • Map : dictionary로 mapping 할때 주로 사용
  • Apply : definition으로 함수를 사용자가 정의를 할때 주로 사용

🌟 newIncome 컬럼에 매핑

Unknown : N
Less than $40K : a
$40K - $60K : b
$60K - $80K : c
$80K - $120K : d
$120K +’ : e

💭 Income_Category의 카테고리를 map 함수를 이용

dic = {
    'Unknown'        : 'N',
    'Less than $40K' : 'a',
    '$40K - $60K'    : 'b',
    '$60K - $80K'    : 'c',
    '$80K - $120K'   : 'd',
    '$120K +'        : 'e'
}

df['newIncome'] = df.Income_Category.map(lambda x: dic[x])

Ans = df[['newIncome', 'Income_Category']]
Ans.head()

💭 Income_Category의 카테고리를 apply 함수를 이용

def changeCategory(x):
    if x =='Unknown':
        return 'N'
    elif x == 'Less than $40K':
        return 'a'
    elif x == '$40K - $60K':
        return 'b'
    elif x == '$60K - $80K':
        return 'c'
    elif x == '$80K - $120K':
        return 'd'
    elif x == '$120K +' :
        return 'e'

df['newIncome']  = df.Income_Category.apply(changeCategory)

Ans = df[['newIncome', 'Income_Category']]
Ans.head()

🌟 빈도수 출력

💭 Customer_Age의 값을 이용하여 나이 구간을 AgeState 컬럼으로 정의 후 각 구간의 빈도수를 출력

  • 구간 : 0-9: 0 , 10-19: 10 , 20-29: 20)...
  • // : 나누기 한 후의 몫
df['AgeState'] = df.Customer_Age.map(lambda x: x//10 *10)

Ans = df['AgeState'].value_counts().sort_index()
Ans

💭 Education_Level의 값중 아래의 조건을 변경하여 newEduLevel 컬럼을 정의하고 빈도수 출력

  • 조건 : Graduate단어가 포함되는 값은 1 / 그렇지 않은 경우에는 0
  • if else 문의 축약문 : 1 if 'Graduate' in x else 0
  • x : 앞의 변수
df['newEduLevel'] = df.Education_Level.map(lambda x : 1 if 'Graduate' in x else 0)

Ans = df['newEduLevel'].value_counts()
Ans
  • 다른 방법 : numpy
  • numpy : 조건에 맞다면 true값, 그렇지 않다면 false값
np.where(조건,true,False)
import numpy as np
df['newEduLevel'] = np.where( df.Education_Level.str.contains('Graduate'), 1, 0)

Ans = df['newEduLevel'].value_counts()
Ans

🌟 newLimit 각 값들의 빈도수를 출력

💭 Credit_Limit 컬럼값이 4500 이상인 경우 1 그외의 경우에는 모두 0으로 하는 newLimit 정의

  • map 방법
df['newLimit'] = df.Credit_Limit.map(lambda x : 1 if x>=4500 else 0)
Ans = df['newLimit'].value_counts()
Ans
  • apply 방법
df['newLimit'] = df.Credit_Limit.apply(lambda x : 1 if x>=4500 else 0)
Ans = df['newLimit'].value_counts()
Ans

💭 Marital_Status 컬럼값이 Married 이고 Card_Category 컬럼의 값이 Platinum인 경우 1 그외의 경우에는 모두 0으로 하는 newState컬럼을 정의

  • 고려햐야하는 컬럼이 2개, 축기준 axis=1
def check(x):
    if x.Marital_Status == 'Married' and x.Card_Category == 'Platinum':
        return 1
    else:
        return 0

df['newState'] = df.apply(check,axis=1)

Ans  = df['newState'].value_counts()
Ans

🌟 각 value의 빈도를 출력

💭 Gender 컬럼값 M인 경우 male F인 경우 female로 값을 변경하여 Gender 컬럼에 새롭게 정의

def changeGender(x)
	if x == 'M':
    	return 'Male'
    else:
    	return 'Female'

df['Gender'] = df['Gender'].apply(changeGenger)
Ans = df['Gender'].value_counts()
Ans

0개의 댓글