Reference
- DataManim (https://www.datamanim.com/dataset/99_pandas/pandasMain.html#)
- <파이썬 한권으로 끝내기>, 데싸라면▪빨간색 물고기▪자투리코드, 시대고시기획 시대교육
DataSet
카드이용데이터 : https://www.kaggle.com/sakshigoyal7/credit-card-customers
DataUrl = ‘https://raw.githubusercontent.com/Datamanim/pandas/main/BankChurnersUp.csv%E2%80%99
Question
✔ 데이터를 로드하고 데이터 행과 열의 갯수를 출력하라
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/pandas/main/BankChurnersUp.csv',index_col=0)
Ans = df.shape
Ans
(10127, 18)
✔ Income_Category의 카테고리를 map 함수를 이용하여 다음과 같이 변경하여 newIncome 컬럼에 매핑하라
Unknown : N Less than $40K : a $40K - $60K : b $60K - $80K : c $80K - $120K : d $120K +’ : e
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']
Ans
0 c
1 a
2 d
3 a
4 c
..
10122 b
10123 b
10124 a
10125 b
10126 a
Name: newIncome, Length: 10127, dtype: object
+ map(function, sequence)
function: 각 요소에 적용할 함수 지정. 보통은 함수 이름이나 람다 함수(lambda function) 형태로 작성
sequence: 함수를 적용할 시퀀스(예: 리스트, 튜플, 시리즈)를 지정
+ lambda arguments: expression
arguments: 람다 함수의 인수를 지정, 필요에 따라 여러 개를 지정할 수 있으며, 쉼표로 구분
expression: 람다 함수의 실행할 단일 표현식을 지정, 함수의 반환 값
+ map(lambda x:dic[x]) : dic 딕셔너리에서 x 값을 참조하여 해당 값을 반환하는 람다 함수가 사용. 시퀀스의 각 요소를 dic 딕셔너리의 값으로 매핑하여 새로운 시퀀스를 생성
✔ 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)
Ans = df['newIncome']
Ans
0 c
1 a
2 d
3 a
4 c
..
10122 b
10123 b
10124 a
10125 b
10126 a
Name: newIncome, Length: 10127, dtype: object
+ apply(func, axis=0) : 열 또는 행에 함수를 적용
func: 적용할 함수 또는 람다 함수
axis: 함수를 적용할 축 지정, axis=0인 경우 열(컬럼)에 함수를 적용하고, axis=1인 경우 행에 함수 적용. 기본값은 0(열)
✔ 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
AgeState
20 195
30 1841
40 4561
50 2998
60 530
70 2
Name: count, dtype: int64
✔ Education_Level의 값중 Graduate단어가 포함되는 값은 1 그렇지 않은 경우에는 0으로 변경하여 newEduLevel 컬럼을 정의하고 빈도수를 출력하라
df['newEduLevel'] = df.Education_Level.map(lambda x :
1 if 'Graduate' in x
else 0)
Ans = df['newEduLevel'].value_counts()
Ans
newEduLevel
0 6483
1 3644
Name: count, dtype: int64
+ lambda 매개변수 : 표현식 if 조건식 else 표현식
표현식: 조건식이 참일 때 또는 거짓일 때 반환될 값.
조건식: 조건을 나타내는 표현식. 조건식이 참이면 첫 번째 표현식이 반환되고, 거짓이면 두 번째 표현식이 반환
✔ 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
newLimit
1 5096
0 5031
Name: count, dtype: int64
✔ 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)
Ans = df['newState'].value_counts()
Ans
newState
0 10120
1 7
Name: count, dtype: int64
✔ 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
Gender
female 5358
male 4769
Name: count, dtype: int64
'🥇 certification logbook' 카테고리의 다른 글
[python 데이터 전처리] 데이터 스케일링 (data scaling) (0) | 2023.06.15 |
---|---|
[python 데이터 핸들링] 판다스 연습 튜토리얼 - 07_Merge , Concat (0) | 2023.06.15 |
[python 데이터 핸들링] 판다스 연습 튜토리얼 - 06_Pivot (0) | 2023.06.15 |
[python 데이터 핸들링] 판다스 연습 튜토리얼 - 05_Time_Series (0) | 2023.06.13 |
[python 데이터 핸들링] 판다스 연습 튜토리얼 - 03_Grouping (0) | 2023.06.13 |
[python 데이터 핸들링] 판다스 연습 튜토리얼 - 02 Filtering & Sorting (0) | 2023.06.09 |
[python 데이터 핸들링] 판다스 연습 튜토리얼 - 01 Getting & Knowing Data (0) | 2023.06.08 |
[ADsP] 비지도학습 - 자기조직화지도(SOM) & 다차원척도법(MDS) (0) | 2023.06.08 |