Python | Pandas Series.to_sparse ()

Python Methods and Functions

Series.to_sparse() Pandas Series.to_sparse() converts the given Series object to SparseSeries. Sparse Objects — they are mostly compressed objects. If some of the data in our Series object is missing, then those locations will be Sparsified. No memory will be wasted storing missing values.

Syntax: Series.to_sparse (kind = 'block', fill_value = None)

Parameter:
kind: {'block', 'integer'}
fill_value: float, defaults to NaN ( missing)

Returns: sp: SparseSeries

Example # 1: Use Series.to_sparse () to convert this series object to a SparseSeries object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 'New York ' , ' Chicago' , 'Toronto' , ' Lisbon' , 'Rio' , ' Moscow' ])

  
# Create date and time index

didx = pd.DatetimeIndex (start = '2014-08-01 10:00' , freq = 'W'

periods = 6 , tz = 'Europe / Berlin'

  
# set index

sr.index = didx

 
# Print series

print (sr)

Output:

We will now use Series.to_sparse () to convert this Series object to a SparseSeries object.

# convert to sparse object
sr.to_sparse ()

 

Output:


As we can see in the output, Series.to_sparse () has successfully converted the given series object to a sparseseries object.

Example # 2: Use Series.to_sparse () to convert this series object to a SparseSeries object.

# import pandas as pd

import pandas as pd

 
# Create series

sr = pd.Series ([ 19.5 , 16.8 , None , 22.78 , None , 20.124 , None , 18.1002 , None ])

 
# Print series

print (sr)

Output:

We will now use Series.to_sparse () to convert this Series object to a SparseSeries object.

# convert to sparse object
sr.to_sparse ()

Output:

As we can see in the output, Series.to_sparse () has successfully converted the given series object to a sparseseries object. If we look at the bottom two lines, it returned information about the location of the memory block and the number of values ​​contained in those blocks.





Tutorials