[Python] apply, map

JONGYOON JEON·2024년 2월 22일

Python

목록 보기
3/7

map(lambda x : dic[x])

선택된 income_category 값을 x로하여 매핑하라

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

나이대 구하기

df['AgeState'] = df.Customer_Age.map(lambda x: x//10 *10)
Ans = df['AgeState'].value_counts().sort_index()

values_counts 개수세기
sort_index 인덱스로 내림차순 정렬

if문 축약형

df['newEduLevel'] = df.Education_Level.map(lambda x : if 'Graduate' in x else 0)

np로도 가능하다. np.where(조건, true, false)
df['newEduLevel'] = np.where( df.Education_Level.str.contains('Graduate'), 1, 0)

두 조건을 만족하는 행을 세어라

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() 

df.칼럼.apply를 보통 쓰는데, 2개의 칼럼에 대한 조건문을 넣어야하여
전체 df를 사용하게 표현함. df.apply(check, axis=1) axis는 행/열 기준 정해줌

def changeGender(x):
    if x =='M':
        return 'male'
    else:
        return 'female'
df['Gender'] = df.Gender.apply(changeGender)
Ans = df['Gender'].value_counts()

여기서는 Gender 칼럼 한개에 대한 식이다보니, df.Gender.apply(changeGender)

profile
효율적인 걸 좋아해요

0개의 댓글