[실습] Python : 04. Apply, Map

yeppi1802·2024년 6월 22일

개념정리

Q56. 데이터를 로드하고 데이터 행과 열의 갯수를 출력하라

import pandas as pd
DriveUrl = 'DriveUrl_자료주소'
df = pd.read_csv(DriveUrl)
Ans = df.shape
# shape : 데이터의 행과 열을 출력
Ans
df.head()

Q57. Income_Category의 카테고리를 map 함수를 이용하여 다음과 같이 변경하여 newIncome 컬럼에 매핑하라

📌 Unknown : N
Less than $40K : a
$40K - $60K : b
$60K - $80K : c
$80K - $120K : d
$120K +’ : e
# 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])
# 'newIncome'이라는 새로운 컬럼 = 'Income_Category'의 변형
# lambda : 사용자 정의 함수
# lambda x: dic[x] : x = 앞에 있는 Income_Category의 데이터, x에 dic[x] 값 대입
# map : 맵핑 함수 

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

Q58. Income_Category의 카테고리를 apply 함수를 이용하여 다음과 같이 변경하여 newIncome 컬럼에 매핑하라

  • 다른 방법으로 맵핑 할 수 있다는 것 보여주는 목적
📌 Unknown : N
Less than $40K : a
$40K - $60K : b
$60K - $80K : c
$80K - $120K : d
$120K +’ : e
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)
# apply : def로 정의한 함수를 하나의 데이터 시리즈에 많이 사용 

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

Q59. Customer_Age의 값을 이용하여 나이 구간을 AgeState 컬럼으로 정의하라. (0-9: 0 , 10-19: 10 , 20-29: 20) … 각 구간의 빈도수를 출력하라

# 수식 구하기
49//10 * 10
df['AgeState']  = df.Customer_Age.map(lambda x: x//10 *10)

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

Q60. Education_Level의 값중 Graduate단어가 포함되는 값은 1 그렇지 않은 경우에는 0으로 변경하여 newEduLevel 컬럼을 정의하고 빈도수를 출력하라

df['newEduLevel'] = df.Education_Level.map(lambda x : 1 if 'Graduate' in x else 0)
# 1 if 'Graduate' in x else 0 : if 축약형 문법
Ans = df['newEduLevel'].value_counts()
Ans
# 다르게 표현 
import numpy as np
df['newEduLevel'] = np.where( df.Education_Level.str.contains('Graduate'), 1, 0)
# np.where(조건, a, b) : 조건이 맞으면 a, 틀리면 b
Ans = df['newEduLevel'].value_counts()
Ans

Q61. Credit_Limit 컬럼값이 4500 이상인 경우 1 그외의 경우에는 모두 0으로 하는 newLimit 정의하라. newLimit 각 값들의 빈도수를 출력하라

df['newLimit'] = df.Credit_Limit.map(lambda x : 1 if x>=4500 else 0)
Ans = df['newLimit'].value_counts()
Ans
# 다른표현 
df['newLimit'] = df.Credit_Limit.apply(lambda x : 1 if x>=4500 else 0)
Ans = df['newLimit'].value_counts()
Ans

Q62. Marital_Status 컬럼값이 Married 이고 Card_Category 컬럼의 값이 Platinum인 경우 1 그외의 경우에는 모두 0으로 하는 newState컬럼을 정의하라. newState의 각 값들의 빈도수를 출력하라

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)
# apply 앞에 컬럼없는 이유 : 조건으로 2가지 컬럼을 제시해서 하나의 컬럼을 x값으로 못둔다. 
# axis=1 : 행기준? 열기준? 이것은 열기준!
Ans  = df['newState'].value_counts()
Ans

Q63. Gender 컬럼값 M인 경우 male F인 경우 female로 값을 변경하여 Gender 컬럼에 새롭게 정의하라. 각 value의 빈도를 출력하라

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

0개의 댓글