English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Pandas 데이터가 잃어버리는 작업 예제
현실 세계에서 데이터가 잃어버리는 것은 항상 문제입니다. 기계 학습과 데이터 마이닝 등의 분야에서는 모델 예측의 정확성에 대한 심각한 문제를 겪고 있으며, 빈 값은 데이터 품질이 좋지 않게 만들어 모델의 정확성과 효과를 저해합니다. 이러한 분야에서 빈 값 처리는 모델을 더 정확하고 효과적으로 만드는 주요 포인트입니다
온라인 설문조사를 고려해 보겠습니다. 많은 사람들은与他们 관련된 모든 정보를 공유하지 않습니다. 경험을 공유하는 사람들은 많지 않지만, 사용한 시간을 공유하지 않습니다; 사용한 시간을 공유하는 사람들은 경험보다 연락처 정보를 공유하지 않습니다. 따라서 일부 데이터는 어떤 방식으로든 잃어버리게 됩니다. 이는 실시간 상황에서 매우 일반적입니다
지금 판다스를 사용하여 빈 값 처리하는 방법을 살펴보겠습니다(예: NA나 NaN)
# import the pandas library import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) df = df.reindex(['a', 'b', 'c']))
실행 결과는 다음과 같습니다:
NaN을 '0'으로 대체: one two three -0.576991 -0.741695 0.553172 print(df.fillna(0)) b 0.000000 0.000000 0.000000744328 -1.735166 1.749580 b NaN NaN NaN NaN을 '0'으로 대체: one two three -0.576991 -0.741695 0.553172 a b 0.000000 0.000000 0.000000744328 -1.735166 1.749580
재인덱싱을 사용하여 빈 값이 있는 DataFrame을 생성했습니다. 출력에서 NaN은 숫자가 아님을 나타냅니다
의미가 있는 값이 더 쉽게(그리고 다른 배열 dtypes) 검출되도록 판다스는 ISNULL()와 NOTNULL() 기능을 제공하며, 이는 시리즈와 데이터프레임 객체의 메서드로도 사용됩니다-
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df['one'].isnull())
실행 결과는 다음과 같습니다:
a False b True c False d True e False f False g True h False Name: one, dtype: bool
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df['one'].notnull())
실행 결과는 다음과 같습니다:
a True b False c True d False e True f True g False h True Name: one, dtype: bool
데이터를 요약할 때, NA는 0으로 간주됩니다 데이터가 모두 불용하면 결과도 불용됩니다
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df['one'].sum())
실행 결과는 다음과 같습니다:
2.02357685917
import pandas as pd import numpy as np df = pd.DataFrame(index=[0,1,2,3,4,5],columns=['one','two']) print(df['one'].sum(),
실행 결과는 다음과 같습니다:
nan
Pandas는 누락된 값을 다양한 방법으로 제거할 수 있는 기능을 제공합니다. fillna 함수는 다음과 같은 방법으로 NA 값을 비어 있는 데이터로 채울 수 있습니다.
다음 프로그램은 'NaN'을 '0'으로 대체하는 방법을 보여줍니다.
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(3, 3) column=['two', 'three']) index=['a', 'c', 'e'],columns=['one', df = df.reindex(['a', 'b', 'c'])) print(df) print(("NaN을 '0'으로 대체:"))
실행 결과는 다음과 같습니다:
NaN을 '0'으로 대체: one two three -0.576991 -0.741695 0.553172 print(df.fillna(0)) b 0.000000 0.000000 0.000000744328 -1.735166 1.749580 b NaN NaN NaN NaN을 '0'으로 대체: one two three -0.576991 -0.741695 0.553172 a b 0.000000 0.000000 0.000000744328 -1.735166 1.749580
c 0.
NA를 전후로 채우기
“재인덱싱” 장에서 논의된 채우기 개념을 사용하여, 누락된 값을 채우겠습니다. | 메서드 |
操作/pad | fill |
bfill/backfill | backfill |
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df.fillna(method='pad'))
실행 결과는 다음과 같습니다:
one two three a 0.077988 0.476149 0.965836 b 0.077988 0.476149 0.965836 c -0.390208 -0.551605 -2.301950 d -0.390208 -0.551605 -2.301950 e -2.000303 -0.788201 1.510072 f -0.930230 -0.670473 1.146615 g -0.930230 -0.670473 1.146615 h 0.085100 0.532791 0.887415
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df.fillna(method='backfill'))
실행 결과는 다음과 같습니다:
one two three a 0.077988 0.476149 0.965836 b -0.390208 -0.551605 -2.301950 c -0.390208 -0.551605 -2.301950 d -2.000303 -0.788201 1.510072 e -2.000303 -0.788201 1.510072 f -0.930230 -0.670473 1.146615 g 0.085100 0.532791 0.887415 h 0.085100 0.532791 0.887415
만약 누락된 값만 제거하고 싶다면 dropna 함수와 axis 매개변수를 함께 사용합니다. 기본적으로 axis = 0으로 설정되어 있으며, 이는 행을 의미합니다. 따라서 한 행의 어떤 값이 NA인 경우, 전체 행이 제거됩니다.
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df.dropna())
실행 결과는 다음과 같습니다:
one two three a 0.077988 0.476149 0.965836 c -0.390208 -0.551605 -2.301950 e -2.000303 -0.788201 1.510072 f -0.930230 -0.670473 1.146615 h 0.085100 0.532791 0.887415
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', ,'h'], columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print(df.dropna(axis=1))
실행 결과는 다음과 같습니다:
Empty DataFrame Columns: [] Index: [a, b, c, d, e, f, g, h]
많은 경우, 특정 값으로 일반 값을 대체해야 합니다. replace 메서드를 적용하여 이를 할 수 있습니다.
NA를 스칼라 값으로 대체하는 것은 fillna() 함수의等效 행동입니다.
import pandas as pd import numpy as np df = pd.DataFrame({'one': [10,20,30,40,50,2000], 'two': [1000,0,30,40,50,60]}) print(df.replace({1000:10,2000:60}))
실행 결과는 다음과 같습니다:
one two 0 10 10 1 20 0 2 30 30 3 40 40 4 50 50 5 60 60
import pandas as pd import numpy as np df = pd.DataFrame({'one': [10,20,30,40,50,2000], 'two': [1000,0,30,40,50,60]}) print(df.replace({1000:10,2000:60)
실행 결과는 다음과 같습니다:
one two 0 10 10 1 20 0 2 30 30 3 40 40 4 50 50 5 60 60