如何在数据帧中获得更高级别索引的子级索引?

2024-09-29 19:33:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究Pandas数据帧,在检索更高级别索引的子级索引时遇到了问题。你知道吗

此图显示了我的数据帧结构:

This image shows my Dataframe structure

例如,在上图中,我想检索只存在于“设备+标签”键'-444/0'的“DCSID”索引,它们是'-111111'、'-222222'和'-333333'。你知道吗

我想用测向位置['-444/0'].索引.级别[0]测向位置['-444/0']返回键'-444/0'的子数据帧,并使用索引.级别[0]检索我以后想要的结果。你知道吗

这是执行测向位置['-444/0']

This is the result of doing ***df.loc['-444/0']***

它不起作用,这是不合逻辑的,因为我认为测向位置['-444/0']返回新的数据帧。你知道吗

不管怎样,我发现测向指数水平[1] 相当于测向iloc['-444/0'].索引.级别[0]都返回“DCSID”中所有索引的列表:

Int64Index([-444444, -333333, -305500, -304445, -301064, -300015, -299069, -297188, -296241, -295295, ... -17132, -15622, -14112, -12602, -9596, -8086, -6576, -5066, -2060, -542], dtype='int64', name='DCSID', length=120)

这是我代码的一部分:

for i in df.index.levels[0]: #Choose from first level
    for j in df.loc[i].index.levels[0]: #Choose from second level going through the i-th first level
        for k in df.loc[i, j, slice(None)].index: #Choose from third level going through the j-th second level
            #Code here

Tags: 数据infromdfforindex级别level
2条回答

它们是奇怪的动物。如果您真的想从中提取值,请从reset_index开始:

df.loc['-444/0'].reset_index()['DCSID'].unique()

应该给出预期的结果array([-111111, -222222, -333333, -444444], dtype=int64)

我正在使用您的csv文件列您可以根据您的要求更改列名

使用get\ U值应用过滤器,并在isin列表中提供DSCID或equipmentKey

df = df[(df.index.get_level_values('EquipmentKey').isin(['-444']))]
df.reset_index(inplace=True)
unique_dscid = df['DSCID'].unique()

第二种方式:

df.reset_index(inplace=True)
df = df[(df['EquipmentKey']=='-444')]
unique_dscid =df['DSCID'].unique()

相关问题 更多 >

    热门问题