执行分组后,我的新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 |
我喜欢在.loc中使用
axis
参数:输出:
你可以做:
另一种方式:
grouped.query("C == 'ZEBRA'").reset_index()
相关问题 更多 >
编程相关推荐