The Pandas class SparseDtype used to create a Dtype for data stored in SparseArray. It implements the pandas ExtensionDtype interface.
1 class pandas.SparseDtype(dtype = <class 'numpy.float64'>, fill_value = None)
dtype : It can be string, ExtensionDtype, numpy.dtype, type that specifies the dtype of the underlying array storing the non-fill value values. If not specified, the default value will be numpy.float64.
fill_value : It is scalar that specifies the scalar value not stored in the SparseArray. If not specified, the default value depends on dtype.
1 import pandas as pd
2 import numpy as np
3 from pandas.arrays import SparseArray
4
5 sdtype = pd.SparseDtype(dtype = np.float64, fill_value = 0)
6
7 arr = SparseArray([0, 1, 0, 2], dtype = sdtype)
8 print('The SparseArray object ')
9 print(arr)
10
11 print('The dtype of SparseArray is :')
12 print(sdtype._dtype)
In the above example, a SparseDtype object is created by passing a dtype and fill_value. A SparseArray object is created by passing an array and custom dtype. The result is assign to the variable that will be printed on console.
1 The SparseArray object
2 [0, 1.0, 0, 2.0]
3 Fill: 0
4 IntIndex
5 Indices: array([1, 3])
6
7 The dtype of SparseArray is :
8 float64
Example 2
1 import pandas as pd
2 import numpy as np
3 from pandas.arrays import SparseArray
4
5 sdtype = pd.SparseDtype(dtype = np.int32, fill_value = 0)
6
7 arr = SparseArray([0, 1, 2, 3], dtype = sdtype)
8 print('The SparseArray object ')
9 print(arr)
10
11 print('The dtype of SparseArray is :')
12 print(sdtype._dtype)
In the above example, a SparseDtype object is created by passing a dtype and fill_value. A SparseArray object is created by passing an array and custom dtype. The result is assign to the variable that will be print.
1 The SparseArray object
2 [0, 1, 2, 3]
3 Fill: 0
4 IntIndex
5 Indices: array([1, 2, 3], dtype=int32)
6
7 The dtype of SparseArray is :
8 int32
Example 3 without zero
1 import pandas as pd
2 import numpy as np
3 from pandas.arrays import SparseArray
4
5 sdtype = pd.SparseDtype(dtype = np.uint16, fill_value = 0)
6
7 arr = SparseArray([1, 2, 3, 4], dtype = sdtype)
8 print('The SparseArray object ')
9 print(arr)
10
11 print('The dtype of SparseArray is :')
12 print(sdtype._dtype)
In the above example, a SparseDtype object is created by passing a dtype and fill_value. A SparseArray object is created by passing an array and custom dtype. The result is assign to the variable that will be print.
1 The SparseArray object
2 [1, 2, 3, 4]
3 Fill: 0
4 IntIndex
5 Indices: array([0, 1, 2, 3], dtype=int32)
6
7 The dtype of SparseArray is :
8 uint16
Related options for your search