Python Pandas - 在 MultiIndex 中仅设置一个单一的特定新级别
若要仅在 MultiIndex 中设置一个单一的特定新级别,请将MultiIndex.set_levels()方法与参数 level 结合使用。首先,导入所需的库 -
import pandas as pd
MultiIndex 是一个用于 pandas 对象的多级或层次化索引对象。创建数组 -
arrays = [[1, 2, 3, 4], ['John', 'Tim', 'Jacob', 'Chris']]
“names”参数为每个索引级别设置名称。from_arrays()用于创建 MultiIndex -
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
我们使用“level”参数设置了一个新的特定级别 -
print("\nSet a new level in Multi-index...\n",multiIndex.set_levels(['p', 'q', 'r', 's'], level = 0))
范例
代码如下 -
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, names=('ranks', 'student')) # display the MultiIndex print("The Multi-index...\n",multiIndex) # get the levels in MultiIndex print("\nThe levels in Multi-index...\n",multiIndex.levels) # set the level in MultiIndex # We have set a new single specific level using the "level" parameter print("\nSet a new level in Multi-index...\n",multiIndex.set_levels(['p', 'q', 'r', 's'], level = 0))
输出
这将产生以下输出 -
The Multi-index... MultiIndex([(1, 'John'), (2, 'Tim'), (3, 'Jacob'), (4, 'Chris')], names=['ranks', 'student']) The levels in Multi-index... [[1, 2, 3, 4], ['Chris', 'Jacob', 'John', 'Tim']] Set a new level in Multi-index... MultiIndex([('p', 'John'), ('q', 'Tim'), ('r', 'Jacob'), ('s', 'Chris')], names=['ranks', 'student'])
广告