Python Pandas - 从 Multiindex 中的特定级别获取值
要从Multiindex中的特定级别获取值,请使用Pandas中的方法。multiIndex.get_level_values()
首先,导入所需的库-
import pandas as pd
创建多索引。names参数设置索引中级别的名称
multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]], names=['a', 'b', 'c', 'd'])
从特定值中获取值。获取第0级值-
print("\nGet level value (0th level)...\n",multiIndex.get_level_values(0))
获取1日电平值-
print("\nGet level value (1st level)...\n",multiIndex.get_level_values(1))
示例
以下是代码-
import pandas as pd #Createamulti-index #Thenamesparametersetsthenamesforthelevelsintheindex multiIndex = pd.MultiIndex.from_arrays([[5, 10], [15, 20], [25, 30], [35, 40]], names=['a', 'b', 'c', 'd']) print("Multi-index...\n",multiIndex) #get0thlevelvalue print("\nGet level value (0th level)...\n",multiIndex.get_level_values(0)) #get1stlevelvalue print("\nGet level value (1st level)...\n",multiIndex.get_level_values(1)) #droppingalevelfromthemultiindex print("\nDropping a level...\n",multiIndex.droplevel())输出结果
这将产生以下输出-
Multi-index... MultiIndex([( 5, 15, 25, 35), (10, 20, 30, 40)], names=['a', 'b', 'c', 'd']) Get level value (0th level)... Int64Index([5, 10], dtype='int64', name='a') Get level value (1st level)... Int64Index([15, 20], dtype='int64', name='b') Dropping a level... MultiIndex([(15, 25, 35), (20, 30, 40)], names=['b', 'c', 'd'])