소개
이 랩에서는 결측값을 포함할 수 있는 정수 데이터를 효율적으로 처리하는 방법인 pandas 의 nullable 정수 데이터 유형을 사용하는 방법을 살펴봅니다. 이 데이터 유형으로 배열을 구성하고, 연산을 수행하며, 결측값을 효과적으로 처리하는 방법을 배우게 됩니다.
VM 팁
VM 시작이 완료되면 왼쪽 상단을 클릭하여 Notebook 탭으로 전환하여 실습을 위해 Jupyter Notebook에 액세스하십시오.
때로는 Jupyter Notebook 이 로딩을 완료하는 데 몇 초 정도 기다려야 할 수 있습니다. Jupyter Notebook 의 제한 사항으로 인해 연산의 유효성 검사는 자동화할 수 없습니다.
학습 중에 문제가 발생하면 언제든지 Labby 에게 문의하십시오. 세션 후 피드백을 제공해주시면 문제를 신속하게 해결해 드리겠습니다.
Nullable 정수 배열 구성
Pandas 는 nullable 정수 배열을 생성하기 위해 IntegerArray 클래스를 제공합니다. IntegerArray를 생성하는 것부터 시작해 보겠습니다.
## Import necessary libraries
import pandas as pd
import numpy as np
## Create an IntegerArray with missing values
arr = pd.array([1, 2, None], dtype=pd.Int64Dtype())
## Output: <IntegerArray>
## [1, 2, <NA>]
## Length: 3, dtype: Int64
배열을 생성할 때 문자열 별칭 "Int64"를 사용하여 데이터 유형을 지정할 수도 있습니다. 모든 NA 와 유사한 값은 pandas.NA로 대체됩니다.
## Create an IntegerArray using the "Int64" string alias
arr = pd.array([1, 2, np.nan], dtype="Int64")
## Output: <IntegerArray>
## [1, 2, <NA>]
## Length: 3, dtype: Int64
IntegerArray 를 DataFrame 또는 Series 에 저장하기
IntegerArray를 생성했으면 DataFrame 또는 Series에 저장할 수 있습니다. 생성한 IntegerArray에서 Series를 만들어 보겠습니다.
## Create a Series from the IntegerArray
series = pd.Series(arr)
Nullable 정수 배열로 연산 수행하기
산술 연산, 비교 및 슬라이싱과 같은 다양한 연산을 nullable 정수 배열로 수행할 수 있습니다.
## Create a Series with nullable integer type
s = pd.Series([1, 2, None], dtype="Int64")
## Perform arithmetic operation
s_plus_one = s + 1 ## adds 1 to each element in the series
## Perform comparison
comparison = s == 1 ## checks if each element in the series is equal to 1
## Perform slicing operation
sliced = s.iloc[1:3] ## selects the second and third elements in the series
pandas.NA 로 결측값 처리하기
IntegerArray 클래스는 스칼라 결측값으로 pandas.NA를 사용합니다. 결측된 단일 요소를 슬라이싱하면 pandas.NA를 반환합니다.
## Create an IntegerArray with a missing value
a = pd.array([1, None], dtype="Int64")
## Slice the second element which is a missing value
missing_value = a[1]
## Output: <NA>
요약
이 랩에서는 pandas 에서 nullable 정수 데이터 유형으로 작업하는 방법을 보여주었습니다. 여기에는 배열 구성, DataFrame 또는 Series에 저장, 연산 수행 및 결측값 처리가 포함됩니다. nullable 정수 데이터 유형을 사용하면 결측값이 있는 정수 데이터를 보다 효율적으로 처리할 수 있습니다.