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输出结果# 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'])
print("Multi-index...\n",multiIndex)
# get 0th level value
print("\nGet level value (0th level)...\n",multiIndex.get_level_values(0))
# get 1st level value
print("\nGet level value (1st level)...\n",multiIndex.get_level_values(1))
# dropping a level from the multiindex
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'])
以上是 Python Pandas - 从 Multiindex 中的特定级别获取值 的全部内容, 来源链接: utcz.com/z/345673.html