English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Pandas 희소 데이터操作 예제
특정 값(NaN)을 생략하면 /데이터가 선택된 값(NaN)과 일치하면, 희소 객체는 "압축"됩니다. 데이터가 "분산"된 위치를 추적하는 특별한 SparseIndex 객체가 있습니다. 예시에서 이는 더 의미가 있습니다. 모든 기본적인 Pandas 데이터 구조는 to_sparse 메서드를 적용합니다:
import pandas as pd import numpy as np ts = pd.Series(np.random.randn(10)) ts[2:-2] = np.nan sts = ts.to_sparse() print sts
결과를 다음과 같이 출력합니다:
0 -0.810497 1 -1.419954 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 0.439240 9 -1.095910 dtype: float64 BlockIndex Block locations: array([0, 8], dtype=int32) Block lengths: array([2, 2], dtype=int32)
메모리 효율성의 이유로 희소 객체가 존재합니다.
지금부터 큰 NA DataFrame이 있을 것이라고 가정하고 다음 코드를 실행해 보겠습니다}}-
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10000, 4)) df.ix[:9998] = np.nan sdf = df.to_sparse() print sdf.density
결과를 다음과 같이 출력합니다:
0.0001
모든 희소 객체를 표준 밀집형으로 변환할 수 있습니다. to_dense() 호출하여
import pandas as pd import numpy as np ts = pd.Series(np.random.randn(10)) ts[2:-2] = np.nan sts = ts.to_sparse() print sts.to_dense()
결과를 다음과 같이 출력합니다:
0 -0.810497 1 -1.419954 2 NaN 3 NaN 4 NaN 5 NaN 6 NaN 7 NaN 8 0.439240 9 -1.095910 dtype: float64
희소 데이터는 밀집된 표현과 동일한 dtype를 가지べき입니다. 현재 float을 지원합니다64,int64booldtypes와 함께 결정됩니다. 원래 dtype에 따라 fill_value 기본 값이 변경됩니다-
float64 − np.nan int64 − 0 bool − False
다음과 같은 코드를 실행하여 이들을 이해해 보겠습니다:
import pandas as pd import numpy as np s = pd.Series([1, np.nan, np.nan]) print s s.to_sparse() print s
결과를 다음과 같이 출력합니다:
0 1.0 1 NaN 2 NaN dtype: float64 0 1.0 1 NaN 2 NaN dtype: float64