當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Pandas DataFrame.to_sparse用法及代碼示例

Pandas DataFrame是帶有標簽軸(行和列)的二維大小可變的,可能是異構的表格數據結構。算術運算在行和列標簽上對齊。可以將其視為Series對象的dict-like容器。這是 Pandas 的主要數據結構。

Pandas DataFrame.to_sparse()函數轉換為SparseDataFrame。該函數實現了DataFrame的稀疏版本,這意味著任何與特定值匹配的數據都將在表示中被省略。稀疏的DataFrame可以提高存儲效率。

用法: DataFrame.to_sparse(fill_value=None, kind=’block’)

參數:
fill_value:表示中應省略的特定值。
kind:{‘block’,‘integer’},默認為‘block’

返回:稀疏 DataFrame

範例1:采用DataFrame.to_sparse()函數將給定的數據幀轉換為SparseDataFrame以進行有效存儲。

# importing pandas as pd 
import pandas as pd 
  
# Creating the DataFrame 
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71], 
                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'], 
                   'Age':[14, 25, 55, 8, 21]}) 
  
# Create the index 
index_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H') 
  
# Set the index 
df.index = index_ 
  
# Print the DataFrame 
print(df)

輸出:

現在我們將使用DataFrame.to_sparse()函數將給定的數據幀轉換為SparseDataFrame。

# convert to SparseDataFrame 
result = df.to_sparse() 
  
# Print the result 
print(result) 
  
# Verify the result by checking the  
# type of the object. 
print(type(result))

輸出:

正如我們在輸出中看到的,DataFrame.to_sparse()函數已成功將給定的數據幀轉換為SparseDataFrame類型。

範例2:采用DataFrame.to_sparse()函數將給定的數據幀轉換為SparseDataFrame以進行有效存儲。

# importing pandas as pd 
import pandas as pd 
  
# Creating the DataFrame 
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 the index 
index_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5'] 
  
# Set the index 
df.index = index_ 
  
# Print the DataFrame 
print(df)

輸出:

現在我們將使用DataFrame.to_sparse()函數將給定的數據幀轉換為SparseDataFrame。

# convert to SparseDataFrame 
result = df.to_sparse() 
  
# Print the result 
print(result) 
  
# Verify the result by checking the  
# type of the object. 
print(type(result))

輸出:


正如我們在輸出中看到的,DataFrame.to_sparse()函數已成功將給定的數據幀轉換為SparseDataFrame類型。



相關用法


注:本文由純淨天空篩選整理自Shubham__Ranjan大神的英文原創作品 Python | Pandas DataFrame.to_sparse。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。