apply()와 def

Jungwoo Kim·2023년 11월 21일

np/pd

목록 보기
8/12

이전 포스팅과 마찬가지로 새로운 변수를 추가할 때, def 를 통해 데이터에 적합한 함수를 먼저 생성한 후, apply 함수를 이용해 mapping할 수 있다.

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)

데이터프레임에서 변수에 대한 조건이 2개 이상인 경우 다음과 같은 함수를 작성하면 된다.
*(axis = 1)

def marriedPlatinum(x):
    if x.Marital_Status == 'Married' and x.Card_Category == 'Platinum':
        return 1
    else:
        return 0
    
df['newState'] = df.apply(marriedPlatinum, axis = 1)

0개의 댓글