# NaN : 결측값
# deck 열의 NaN 개수 계산하기
# dropna = False : 결측값 포함
nan_deck = df['deck'].value_counts(dropna=False)
nan_deck
# isnull() : 누락 데이터 여부
# 모든 컬럼의 값이 누락 데이터인 경우 True, 누락 데이터가 아닌 경우 False
df.head().isnull()
# notnull() : 누락 데이터가 아닌 경우
# 모든 컬럼의 값이 누락 데이터인 경우 True, 누락 데이터가 아닌 경우 False
df.head().notnull()
# 누락 데이터의 갯수 조회하기
df.head().isnull().sum(axis=0)
df.isnull().sum(axis=0)
# 각 열의 NaN 개수 계산하기 (반복문 이용해서 계산, 간단하게 하려면 -> df.isnull().sum(axis=0))
missing_df = df.isnull()
# col = 컬럼명
for col in missing_df.columns:
missing_count = missing_df[col].value_counts()
# missing_count[True] : missing_count 해당 컬럼의 값의 건수
try :
print(col,':',missing_count[True])
except :
print(col,":",0)
# df.dropna 함수 : NaN 값이 500개 이상인 열을 모두 삭제
df_thresh = df.dropna(axis=1, thresh=500)
print(df_thresh.columns)
print(df_thresh.info())
# NaN 값을 가진 행을 삭제
df_age = df_thresh.dropna(subset=['age'],how='any',axis=0)
print(len(df_age))
print(df_age.info())
# 결측값을 치환
# df 데이터 : age 열의 NaN 값을 다른 나이 데이터의 평균으로 변경하기
print(df.info())
# age 열의 평균 계산 (NaN 값 제외)
mean_age = df['age'].mean(axis=0)
# fillna 함수 : 결측값을 지정한 값으로 변경
# inplace = True : 데이터프레임 객체 자체를 변경
df['age'].fillna(mean_age,inplace=True)
print(df.info())
# embark_town 컬럼의 결측값은 컬럼의 값 중 빈도수가 가장 많은
# 값으로 치환하기
# embark_town 컬럼에 저장된 값의 빈도수 출력
most_freq = df["embark_town"].value_counts(dropna=True).idxmax()
# dropna = True 결측값 X
# idxmax() = 가장 빈도수가 많은 값
print(most_freq)
df['embark_town'].fillna(most_freq,inplace=True)
print(df.info())
'Python' 카테고리의 다른 글
Python - 웹크롤링 (BeautifulSoup/ Selenium) (0) | 2021.07.06 |
---|---|
Python - 변수저장, 데이터프레임 필터(조회기능), 데이터프레임 병합 (0) | 2021.07.05 |
Python - 인구 구조가 비슷한 지역 그래프 그리기 (0) | 2021.07.02 |
Python - Numpy 연습문제 (0) | 2021.07.01 |
Python - 지도 (folium) 연습문제 (0) | 2021.06.30 |