우선 비어있는 값인 Null 이 포함된 데이터 프레임을 생성합니다.

df = pd.DataFrame({'col1':[0,1,2,3,6],'col2':pd.Series([1,2,3],index=[1,2,3]), 
		'col3': ['A','B','C','D','E'],'col4':pd.Series([1,3],index=[0,2])},index=[0,1,2,3,4])
df

우선 NaN값에 대해서 drop하는 방법은 따로 설명하지않고 이전 포스팅의 링크를 올립니다.

 

Pandas - DataFrame (2) 삭제

우선 데이터프레임을 생성합니다. my_dictionary = {"col1":[0,1,2,3], "col2": pd.Series([1,2,3],index=[1,2,3])} df=pd.DataFrame(data=my_dictionary, index=[0,1,2,3]) df Drop 명령어를 사용해서 행,열을..

itpori.tistory.com

 

이제 남은 방식은 dropna()와 fillna()를 사용하는 방법입니다.

1. dropna()

간단하게 NaN값이 들어있는 행이나 열을 제거시킵니다. 기본적으로 행을 삭제하며, axis=1 를 사용하면 열도 가능합니다.

df.dropna()

df.dropna(axis=1)

 

 

2.fillna()

기본적인 구조는 다음과 같습니다.

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)

사용 예시들입니다.

0으로 채우고 싶다면 괄호안에 0을 넣으면됩니다.

df.fillna(0)

null값의 앞이나 뒤의 값으로 채우고싶다면 method를 설정해주어야합니다.

- 앞의 값으로 채우기

df.fillna(method='ffill')

- 뒤의 값으로 채우기

df.fillna(method='backfill')

※ 앞 뒤에 값이 없는 경우 채워지지 않습니다.

 

참고.

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.fillna.html

 

pandas.DataFrame.fillna — pandas 1.4.3 documentation

If method is specified, this is the maximum number of consecutive NaN values to forward/backward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. If method is not specified, this is t

pandas.pydata.org


scikit learn의 SimpleImputer를 사용하는 방법도 있습니다. 이 방법은 수치형 데이터에만 사용가능합니다.

기본 구성은 다음과 같습니다.

class sklearn.impute.SimpleImputer(*, missing_values=nan, strategy='mean', fill_value=None, verbose='deprecated', copy=True, add_indicator=False)

strategy의 값을 변경하면 되는데, 'mean','median','most_frequent', 'constant' 의 값을 적용 가능합니다.

'mean' 값으로 치환하는 예제 코드입니다.

우선 앞의 데이터프레임에서 문자 데이터인 'col3' 를 제거하고 수치형 데이터만 남기겠습니다.

df.drop('col3',inplace=True,axis=1)
df

그다음 SimpleImputer를 설정,학습합니다.

Im = SimpleImputer(strategy= "mean")
Im.fit(df)

계산된 값들을 살펴보기 위해 다음과 같이 작성합니다.

Im.statistics_

계산한 값들을 토대로 원래의 데이터프레임 형식으로 되돌립니다.

X=Im.transform(df)
pd.DataFrame(X,columns=df.columns,index=df.index)

결과

 

'Others > Data Science' 카테고리의 다른 글

Preprocessing (4) Scaling  (0) 2022.07.19
Preprocessing (3) Encoding  (0) 2022.07.18
Pandas - DataFrame (3) 조회(loc/iloc)  (0) 2022.07.15
Pandas - DataFrame (2) 삭제  (0) 2022.07.14
Preprocessing (1) train_test_split  (0) 2022.07.14

+ Recent posts