Python Pandas - 获取请求标签/级别的位置和切片索引,但不删除级别


为了在多级索引中获取请求标签/级别的位置和切片索引,请在 Pandas 中使用 **get_loc_level()** 方法。使用 **drop_level** 参数并将其设置为 **False** 以避免删除级别。

首先,导入所需的库 -

import pandas as pd

多级索引是 Pandas 对象的多级或分层索引对象 -

multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])

显示多级索引 -

print("The MultiIndex...\n",multiIndex)

获取位置和切片索引。为了避免删除级别,我们使用了值为“False”的“drop_level”参数 -

print("\nGet the location and sliced index (avoid dropping the level)...\n",multiIndex.get_loc_level('r', drop_level=False))

示例

以下是代码 -

import pandas as pd

# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
multiIndex = pd.MultiIndex.from_arrays([list('pqrrss'), list('strvwx')],names=['One', 'Two'])

# display the MultiIndex
print("The MultiIndex...\n",multiIndex)

# get the levels in MultiIndex
print("\nThe levels in MultiIndex...\n",multiIndex.levels)

# Get the location and sliced index
# To avoid dropping a level, we have used the "drop_level" parameter with value "False"
print("\nGet the location and sliced index (avoid dropping the level)...\n",multiIndex.get_loc_level('r', drop_level=False))

输出

这将产生以下输出 -

The MultiIndex...
MultiIndex([('p', 's'),
            ('q', 't'),
            ('r', 'r'),
            ('r', 'v'),
            ('s', 'w'),
            ('s', 'x')],
            names=['One', 'Two'])

The levels in MultiIndex...
   [['p', 'q', 'r', 's'], ['r', 's', 't', 'v', 'w', 'x']]

Get the location and sliced index (avoid dropping the level)...
(slice(2, 4, None), MultiIndex([('r', 'r'),('r', 'v')],names=['One', 'Two']))

更新于: 2021-10-19

84 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.