Programming/Python
Python - Pandas 예제2 (Apply,Map,Time)
wave35
2024. 9. 21. 00:18
1. Apply & Map
import pandas as pd
### ###
### 04 Apply & Map ###
### ###
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/pandas/main/BankChurnersUp.csv')
# Income_Category의 카테고리를 map 함수를 이용하여 다음과 같이 변경하여 newIncome 컬럼에 매핑하라
dic = {
'Unknown' : 'N',
'Less than $40K' : 'a',
'$40K - $60K' : 'b',
'$60K - $80K' : 'c',
'$80K - $120K' : 'd',
'$120K +' : 'e'
}
df.loc[:,'newIncome'] = df['Income_Category'].map(dic)
# Income_Category의 카테고리를 apply 함수를 이용하여 다음과 같이 변경하여 newIncome 컬럼에 매핑하라
def income_mapper(x):
return dic[x]
df['Income_Category'].apply(income_mapper)
# Education_Level의 값 중 Graduate단어가 포함되는 값은 1,
# 그렇지 않은 경우에는 0으로 변경하여 newEduLevel 컬럼을 정의하고 빈도수를 출력하라
df.loc[:,'newEduLevel'] = df['Education_Level'].map(lambda x: 1 if 'Graduate' in x else 0)
df['newEduLevel'].value_counts()
# Marital_Status 컬럼값이 Married 이고 Card_Category 컬럼의 값이 Platinum인 경우 1,
# 그외의 경우에는 모두 0으로 하는 newState컬럼을 정의하라.
def filter(x): # x는 series타입
return 1 if x['Marital_Status'] == 'Married' and x['Card_Category'] == 'Platinum' else 0
# axis = 0 : 열 / axis = 1 : 행
df.loc[:,'newEduLevel'] = df[['Marital_Status','Card_Category']].apply(filter, axis=1)
2. Time Series
import pandas as pd
### ###
### 05 Time Series ###
### ###
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/pandas/main/timeTest.csv')
#Yr_Mo_Dy을 판다스에서 인식할 수 있는 datetime64타입으로 변경하라
df.loc[:,'Yr_Mo_Dy'] = pd.to_datetime(df['Yr_Mo_Dy']) # dtype: datetime64
# Month 만 추출
pd.to_datetime(df['Yr_Mo_Dy']).dt.month
## 컬럼에 날짜 형식이나 잘못된 값이 섞여 있는 경우 ##
# errors='coerce' 옵션을 사용하여 잘못된 값이 있을 경우 NaT(Not a Time)으로 대체
df['Yr_Mo_Dy'] = pd.to_datetime(df['Yr_Mo_Dy'], errors='coerce')
# NaT 값이 있는 행 제거
df = df.dropna(subset=['Yr_Mo_Dy'])
df.loc[:,'Yr_Mo_Dy'] = pd.to_datetime(df['Yr_Mo_Dy'], errors='coerce')
df['Yr_Mo_Dy']
# Yr_Mo_Dy에 존재하는 년도의 유일값을 모두 출력하라
df['Yr_Mo_Dy'].dt.year.unique()
# 년도별 각컬럼의 평균값을 구하여라
df.groupby(df['Yr_Mo_Dy'].dt.year).mean()
# 년도 - 월을 기준으로 모든 컬럼의 평균값을 구하여라
df.groupby(df['Yr_Mo_Dy'].dt.strftime('%Y-%m')).mean()
# RPT 컬럼의 값을 일자별 기준으로 1차차분하라 ( 그 다음 행과 비교하여 차이 값을 출력 )
df.loc[:,'diff_1'] = df['RPT'].diff()