T0 기본형태
파일 로딩
import os
import re
workDIr = os.path.abspath('.')
file_list = []
for dirpath, _, filenames in os.walk(workDIr):
for filename in filenames:
file_list.append(f'{dirpath}\\{filename}')
file_list
file_list = file_list[3:]
file_list #몇 개 없어서 그냥 슬라이싱 함
import pandas as pd # 여러분의 친구 판다스
#각 변수에 때려박기
f = {}
for i in range(len(file_list)):
f[i] = pd.read_table(file_list[i], low_memory=False)
f[i] = f[i][['PERSON_ID','STND_Y','AGE_GROUP']]
f[list(f.keys())[-1]] # 마지막꺼 확인
전처리 (테이블 정리)
# 복붙용 코드 : 출력한거 복사해서 밑에 붙여넣으려고... 굳이 이거 안써도 됨
f_list = []
for i in range(len(f.keys())):
print(f'f[{i}],',end="")
# 테이블 합체
combined_t0 = pd.concat([f[0],f[1],f[2],f[3],f[4],f[5],f[6],f[7],f[8],f[9],f[10],f[11]])
# 컬럼 형 변환 (부동소수점 -> 정수)
combined_t0 = combined_t0.astype({'PERSON_ID':'int'})
combined_t0
combined_t0.drop_duplicates() # 중복있는지 확인. 없음
테이블 형태 재구조화 (개인 : 기준 년도별 연령그룹 형태)
df_pv = combined_t0.pivot('PERSON_ID',columns='STND_Y', values='AGE_GROUP')
df_pv
결측값 치환 NaN -> -1
df_pv = df_pv.fillna(-1)
df_pv
# 하나 기준으로 확인
list(df_pv.iloc[50000])
★한 명의 나이 구하는 함수★
def how_old_are_you(age_group):
temp_old = float()
counter = 0
for i in range(len(age_group)): #하나씩 읽어가기
#print(i)
#print(f'old:{temp_old} \t now:{age_group[i]}')
#print(f'counter:{counter}')
# 오측값 있을 시 pass
if age_group[i] == -1 :
next
# 해당년에 태어남
if age_group[i] == 0 :
return -i
# 이전과 같을 시 counter + 1
if temp_old == age_group[i] :
counter += 1
else :
counter = 0
temp_old = age_group[i]
#print('clear')
#print(f'counter:{counter}')
if counter == 4 and age_group[i]!=-1.0: #이번 포함 5회 같음
res = (age_group[i]*5) -i -1
#print(f'last pang. \t {age_group[i]}*5 -{i} -1 = {res}')
return res
#print()
return 'unknown'
# 테스트 1
test_age = list(df_pv.iloc[50000])
#test_age = [12.0, 13.0, 13.0, 13.0, 13.0, 13.0, 14.0, 14.0, 14.0, 14.0, 14.0, 15.0]
#test_age = [-1, -1, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]
how_old_are_you(test_age)
# 테스트 2
print(list(df_pv.iloc[0]))
how_old_are_you(list(df_pv.iloc[0]))
여기서부터는 여러 명의 나이를 구하는 함수 제작
df_pv.iloc[500000:500010]
## DataFrame 형태로 넘겨줬을 때 일괄처리 함수
def get_birth_list_from_df(df):
temp_pid_age = {}
pid_list = list(df.index)
for i in range(len(pid_list)):
age = how_old_are_you(list(df.iloc[i]))
temp_pid_age[pid_list[i]] = age
return temp_pid_age
get_birth_list_from_df(df_pv.iloc[500000:500010])
※오래걸림※ 전체 나이 구하기
dict_final = get_birth_list_from_df(df_pv)
df_final = pd.DataFrame(dict_final.items(), columns=['pid','age'])
df_final
제대로 되었는지 확인
# 전체 나이 결과값 확인
list(set(df_final.age))
# 극단값 확인
df_final[df_final.age == -11.0]
# 극단값 확인2
df_final[df_final.age == 85]
# 비식별값 확인
df_final[df_final.age == 'unknown']
# 최소
list(df_pv.loc[719514])
df_final[df_final.pid == 719514]
# 최대
list(df_pv.loc[98500685])
df_final[df_final.pid == 98500685]
# 미확인 (도중 사망자등)
list(df_pv.loc[99999591])
df_final[df_final.pid == 99999591]
식별 완료 된 수 확인
# 미확인자
len(df_final[df_final.age == 'unknown'])
# 확인자
len(df_final[df_final.age != 'unknown'])
# 전체
len(df_final)
# 최종 확인 비율
len(df_final[df_final.age != 'unknown'])/len(df_final)
# 최종 미확인 비율
len(df_final[df_final.age == 'unknown'])/len(df_final)
2013 년도 기준으로 나이 편집
df_ff=df_final[df_final.age != 'unknown']
df_ff
df_ff['age13'] = df_ff['age'].map(lambda x : x+11)
df_ff
히스토그램 & 도수분포표
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# unknown 제외
df_without_unknown = df_ff[df_ff.age != 'unknown']
plt.hist(df_without_unknown['age'],bins=len(list(set(df_final.age)))-1)
sns.countplot(df_without_unknown['age'])
sns.countplot(df_without_unknown['age13'])
pd.Series(df_without_unknown['age']).value_counts()
pd.Series(df_without_unknown['age13']).value_counts()
보너스 심화문제
## 보너스 // dictionary 형태로 넘겨줬을 때 일괄처리 함수
def get_birth_list_from_dict(person):
temp_pid_age = {}
for i in list(person.keys()):
age = how_old_are_you(person[i])
temp_pid_age[i] = age
# print(f'person_{i}\'s age : {age}') # 개인별 코드
return temp_pid_age