Python - 返回已移除特定级别的索引
要用 Pandas 返回已移除特定级别的索引,请使用 multiIndex.droplevel() 方法。首先,导入所需的库 -
import pandas as pd
创建一个多级索引。names 参数设置索引中各级别名称
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]], names=['a', 'b', 'c', 'd'])
移除一个级别。我们将要移除的级别的位置作为参数传递 -
print("\nDropping a level...\n",multiIndex.droplevel(3))
实例
以下是代码 -
import pandas as pd # Create a multi-index # The names parameter sets the names for the levels in the index multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]], names=['a', 'b', 'c', 'd']) # display the multi-index print("Multindex...\n",multiIndex) # Dropping a level # We have passed the position of the level to be removed as a parameter print("\nDropping a level...\n",multiIndex.droplevel(3))
输出
这将生成以下输出 -
Multindex... MultiIndex([( 5, 15, 25, 35),(10, 20, 30, 40)],names=['a', 'b', 'c', 'd']) Dropping a level... MultiIndex([( 5, 15, 25),(10, 20, 30)],names=['a', 'b', 'c'])
广告