Python Pandas - 使用多级索引的层级作为列创建 DataFrame 并替换索引层级名称
要创建将多级索引的层级作为列的 DataFrame,请使用 **MultiIndex.to_frame()** 方法。使用 **name** 参数替换索引层级名称。
首先,导入所需的库 -
import pandas as pd
多级索引是 pandas 对象的多级或分层索引对象。创建数组 -
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
“names” 参数为每个索引层级设置名称。from_arrays() 用于创建多级索引 -
multiIndex = pd.MultiIndex.from_arrays(arrays)
使用 to_frame() 创建一个将多级索引的层级作为列的 DataFrame。使用“name” 参数并传递名称以替换索引层级名称 -
dataFrame = multiIndex.to_frame(name=['One', 'Two'])
示例
以下是代码 -
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() is used to create a MultiIndex
multiIndex = pd.MultiIndex.from_arrays(arrays)
# display the MultiIndex
print("The Multi-index...\n",multiIndex)
# get the levels in MultiIndex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# Create a DataFrame with the levels of the MultiIndex as columns using to_frame()
# Use the "name" parameter and pass the names to substitute index level names
dataFrame = multiIndex.to_frame(name=['One', 'Two'])
# Display the DataFrame
print("\nThe DataFrame...\n",dataFrame)输出
这将产生以下输出 -
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], ) The levels in Multi-index... [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']] The DataFrame... One Two 1 John 1 John 2 Tim 2 Tim 3 Jacob 3 Jacob 4 Chris 4 Chris
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP