English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Pandas sparse data operation example
When omitted, any value (NaN /Missing values, although any value can be chosen, will match any data. Sparse objects will be 'compressed'. A special SparseIndex object tracks the 'dispersed' positions of the data. In an example, this will be more meaningful. All standard Pandas data structures apply the to_sparse method:
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
Die Ergebnisse des Laufens sind wie folgt:
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)
Due to memory efficiency reasons, sparse objects exist.
Nun nehmen wir an, dass Sie eine sehr große NA DataFrame haben und führen folgenden Code aus-
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
Die Ergebnisse des Laufens sind wie folgt:
0.0001
Jegliche dünne Instanz kann in den Standarddichten Formaten umgewandelt werden, indem to_dense aufgerufen wird
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()
Die Ergebnisse des Laufens sind wie folgt:
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
Dünne Daten sollten die gleiche dtype wie ihre dichte Darstellung haben. Derzeit wird float unterstützt64,int64und booldtypes. Abhängig vom ursprünglichen dtype wird der Standardwert fill_value geändert-
float64 − np.nan int64 − 0 bool − False
Wir führen nun folgenden Code aus, um sie zu verstehen:
import pandas as pd import numpy as np s = pd.Series([1, np.nan, np.nan]) print s s.to_sparse() print s
Die Ergebnisse des Laufens sind wie folgt:
0 1.0 1 NaN 2 NaN dtype: float64 0 1.0 1 NaN 2 NaN dtype: float64