当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python Pandas DataFrame.blocks用法及代码示例

Pandas DataFrame是带有标签轴(行和列)的二维大小可变的,可能是异构的表格数据结构。算术运算在行和列标签上对齐。可以将其视为Series对象的dict-like容器。这是 Pandas 的主要数据结构。

Pandas DataFrame.blocks属性是的同义词as_blocks()函数。它本质上将帧转换为dtype->构造器类型的字典,每个字典都具有同质dtype。

用法: DataFrame.blocks

参数:没有

返回:字典

范例1:采用DataFrame.blocks属性以返回包含单独数据类型块中的数据的字典。

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

输出:

现在我们将使用DataFrame.blocks属性以返回给定 DataFrame 的块表示形式。

# return a dictionary 
result = df.blocks 
  
# Print the result 
print(result)

输出:

正如我们在输出中看到的,DataFrame.blocks属性已成功返回包含 DataFrame 数据的字典。同类列是同一块中的位置。

范例2:采用DataFrame.blocks属性以返回包含单独数据类型块中的数据的字典。

# 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.blocks属性以返回给定 DataFrame 的块表示形式。

# return a dictionary 
result = df.blocks 
  
# Print the result 
print(result)

输出:

正如我们在输出中看到的,DataFrame.blocks属性已成功返回包含 DataFrame 数据的字典。同类列是同一块中的位置。



相关用法


注:本文由纯净天空筛选整理自Shubham__Ranjan大神的英文原创作品 Python | Pandas DataFrame.blocks。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。