# Pandas稀疏數據

``````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.391926
1   -1.774880
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7         NaN
8    0.642988
9   -0.373698
dtype: float64
BlockIndex
Block locations: array([0, 8])
Block lengths: array([2, 2])``````

``````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``

``````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.275846
1    1.172722
2         NaN
3         NaN
4         NaN
5         NaN
6         NaN
7         NaN
8   -0.612009
9   -1.413996
dtype: float64``````

## 稀疏Dtypes

• `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)
print ("=============================")
s.to_sparse()
print (s)``````

``````0    1.0
1    NaN
2    NaN
dtype: float64
=============================
0    1.0
1    NaN
2    NaN
dtype: float64``````