Python Pandas - 从 MultiIndex 获取每个级别长度的元组
要从MultiIndex获取具有每个级别长度的元组,请使用Pandas中的MultiIndex.levshape属性。
首先,导入所需的库-
import pandas as pd
MultiIndex是Pandas对象的多级或分层索引对象。创建数组-
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
“names”参数设置每个索引级别的名称。from_arrays()用于创建Multiindex的uis-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))获取每个级别长度的元组-
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape)示例
以下是代码-
import pandas as pd
#MultiIndexisamulti-level,orhierarchical,indexobjectforpandasobjects
#Createarrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
# The "names" parameter sets the names for each of the index levels
#Thefrom_arrays()uisusedtocreateaMultiindex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
#displaytheMultiindex
print("The Multi-index...\n",multiIndex)
#gettheintegernumberoflevelsinMultiindex
print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels)
#getthelevelsinMultiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
#getatuplewiththelengthofeachlevel
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape)输出结果这将产生以下输出-
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
The number of levels in Multi-index...
2
The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
The tuple with the length of each level in a Multi-index...
(5, 5)热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志