Python | Pandas DataFrame.to_sparse

Python Methods and Functions

DataFrame.to_sparse() Pandas DataFrame.to_sparse() converts to SparseDataFrame. The function implements a sparse version of the DataFrame, meaning that any data that matches a specific value is omitted from the view. A sparse DataFrame provides more efficient storage.

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

Parameter:
fill_value: The specific value that should be omitted in the representation.
kind: {'block', 'integer '}, default' block '

Returns: SparseDataFrame

Example # 1: Use DataFrame.to_sparse () to convert this Dataframe to SparseDataFrame for efficient storage.

# import pandas as pd

import pandas as pd

  
# Create DataFrame

df =   pd.DataFrame ({ 'Weight' : [ 45 , 88 , 56 , 15 , 71 ],

'Name' : [ ' Sam' , 'Andrea' , ' Alex' , 'Robin' , ' Kia' ],

'Age' : [ 14 , 25 , 55 , 8 , 21 ]})

 
# Create Index

index_ = pd.date_range ( '2010-10-09 08:45' , periods = 5 , freq = 'H' )

 
# Set index

df.index = index_

 
# Print set DataFrame

print (df)

Output:

We will now use DataFrame.to_sparse () to convert the specified dataframe to a SparseDataFrame.

# convert to SparseDataFrame

result = df.to_sparse ()

 
# Print the result

print (result)

 
# Check the result by checking
# type object.

print ( type (result))

Output:

As we can see in the output, DataFrame.to_sparse () successfully converted this data frame to the SparseDataFrame type.

Example # 2: Use DataFrame.to_sparse () to convert this Dataframe to SparseDataFrame for efficient storage.

# import pandas as pd

import pandas as pd

 
# С DataFrame creation

df = pd.DataFrame ({ "A" : [ 12 , 4 , 5 , None , 1 ], 

"B" : [ 7 , 2 , 54 , 3 , None ], 

"C" : [ 20 , 16 , 11 , 3 , 8 ], 

"D" : [ 14 , 3 , None , 2 , 6 ]}) 

 
# Create index

index_ = [ 'Row_1' , ' Row_2' , 'Row_3' , ' Row_4' , ' Row_5' ]

 
# Set index

df.index = index_

 
# Print DataFrame

print (df)

Output:

We will now use DataFrame.to_sparse () to convert the specified dataframe to a SparseDataFrame.

# convert to SparseDataFrame

result = df.to_sparse ()

  
# Print result

print (result)

  
# Check the result by checking
# object type.

print ( type (result))

Output:


As we can see in the output, DataFrame.to_sparse () successfully converted this data frame to the SparseD type ataFrame.