按特定标签定位行,仅在上一个多重索引中找到

2024-07-07 07:56:03 发布

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

执行分组后,我的新df具有3级多指标。我需要访问所有带有“斑马”标签的行;包含在第三级索引中。我正在尝试使用df.loc,但无法使用。我曾想过遍历标签,但这必须是一个嵌套的循环才能在下面生成;这让我觉得我没有按照正确的思路思考,一定有一个更容易的方法

> indexlevel1_value1->indexlevel2_value1>indexlevel3_'stabilizer' 
> indexlevel1_value1->indexlevel2_value2>indexlevel3_'stabilizer' 
> indexlevel1_value1->indexlevel2_value3>indexlevel3_'stabilizer' 
> ................... 
> indexlevel2_value1->indexlevel2_value1>indexlevel3_'stabilizer'

这个问题看起来很接近,但主要集中在一级索引上

import pandas as pd
import numpy as np

df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                             'foo', 'bar', 'foo', 'foo',
                             'bar', 'foo', 'bar','foo', 
                              'bar','foo' ],
                         'B' : ['one', 'one', 'two', 'three',
                                'two', 'two', 'one', 'three',
                                'two', 'three','two', 'two', 
                                'one', 'three'],
                         'C' : ['MR', 'ZEBRA', 'KID', 'ZEBRA', 
                                'MOS', 'ALPHA', 'ZULU', 'ZEBRA',
                               'TREE','PLANT', 'JOOMLA','ZEBRA',
                               'MOS','ZULU'],
                           'D' : np.random.randn(14)})  

grouped = df.groupby(['A', 'B','C'])
grouped.count()


| A   | B     | C      | D |
|-----|-------|--------|---|
| bar | one   | MOS    | 1 |
|     |       | ZEBRA  | 1 |
|     | three | ZEBRA  | 1 |
|     | two   | ALPHA  | 1 |
|     |       | JOOMLA | 1 |
|     |       | TREE   | 1 |
| foo | one   | MR     | 1 |
|     |       | ZULU   | 1 |
|     | three | PLANT  | 1 |
|     |       | ZEBRA  | 1 |
|     |       | ZULU   | 1 |
|     | two   | KID    | 1 |
|     |       | MOS    | 1 |
|     |       | ZEBRA  | 1 |

newdf= grouped.count()

newdf.loc[('bar','three','ZEBRA')]
#1

期望的:

| A   | B     | C     | D |
|-----|-------|-------|---|
| bar | one   | ZEBRA | 1 |
| bar | three | ZEBRA | 1 |
| foo | three | ZEBRA | 1 |
| foo | two   | ZEBRA | 1 |

Tags: dffoobaronethreetwomosvalue1
2条回答

我喜欢在.loc中使用axis参数:

df_out.loc(axis=0)[:, :, 'ZEBRA'].reset_index()

输出:

     A      B      C  D
0  bar    one  ZEBRA  1
1  bar  three  ZEBRA  1
2  foo  three  ZEBRA  1
3  foo    two  ZEBRA  1

你可以做:

grouped[grouped.index.get_level_values(2) == 'ZEBRA'].reset_index()

     A      B      C  D
0  bar    one  ZEBRA  1
1  bar  three  ZEBRA  1
2  foo  three  ZEBRA  1
3  foo    two  ZEBRA  1

另一种方式:grouped.query("C == 'ZEBRA'").reset_index()

相关问题 更多 >