按位置切片MultiIndex pandas DataFrame [英] Slice MultiIndex pandas DataFrame by position
问题描述
我目前正在尝试对按位置划分为三个级别的MuliIndex DataFrame进行切片. 我正在使用熊猫19.1
I am currently trying to to slice a MuliIndex DataFrame that has three levels by position. I am using pandas 19.1
Level0 Level1 Level2 Value
03-00368 A Item111 6.9
03-00368 A Item333 19.2
03-00368 B Item111 9.7
03-00368 B Item222 17.4
04-00176 C Item110 17.4
04-00176 C Item111 9.7
04-00246 D Item46 12.5
04-00246 D Item66 5.6
04-00246 D Item99 11.2
04-00247 E Item23 12.5
04-00247 E Item24 5.6
04-00247 E Item111 11.2
04-00247 F Item23 7.9
04-00247 F Item24 9.7
04-00247 F Item111 12.5
04-00247 G Item46 11.2
04-00247 G Item66 9.7
04-00247 G Item999 9.7
04-00247 H Item23 11.2
04-00247 H Item94 7.9
04-00247 H Item111 11.2
04-00247 I Item46 5.6
04-00247 I Item66 12.5
04-00247 I Item888 11.2
04-00353 J Item66 12.5
04-00353 J Item99 12.5
04-00354 K Item43 12.5
04-00354 K Item94 12.5
04-00355 L Item54 50
04-00355 L Item99 50
目前我可以实现:
df.loc[(slice('03-00368', '04-00361'), slice(None), slice(None)), :]
但是实际上,我不知道标签是什么.我只想选择前十个0级,所以我尝试了这个(以及许多其他类似的东西):
But in practice I won't know what the labels will be. I just want to select the first ten level 0's so I tried this(and many other things which are similar):
>>> df.iloc[(slice(0, 10), slice(None), slice(None)), :]
TypeError: unorderable types: int() >= NoneType()
最终目标是限制显示的最终行数,不破坏Level0索引
The end goal is to limit the final number of rows displayed, without breaking up the Level0 index
>>>df.iloc[(0,1,), :]
Level0 Level1 Level2 Value
03-00368 A Item111 6.9
03-00368 A Item333 19.2
请注意,它只返回了前两行,我希望结果是:
Notice that it only returned the first two rows, I would like the result to be:
Level0 Level1 Level2 Value
03-00368 A Item111 6.9
03-00368 A Item333 19.2
03-00368 B Item111 9.7
03-00368 B Item222 17.4
04-00176 C Item110 17.4
04-00176 C Item111 9.7
可以通过多种方式来实现此目的,但是我发布该帖子是因为我想知道自己在做错什么,或者为什么我不能指望能够以这种方式对MultiIndexes进行切片.
There are of hacky way to accomplish this but I'm posting because I want to know what I am doing wrong, or why I can't expect to be able to slice MultiIndexes this way.
推荐答案
方法1
groupby
+ head
method 1
groupby
+ head
df.groupby(level=0).head(10)
方法2
不必要的冗长
IndexSlice
method 2
Unnecessarily verbose
IndexSlice
df.sort_index().loc[pd.IndexSlice[df.index.levels[0][:10], :, :], :]
方法3
loc
method 3
loc
df.loc[df.index.levels[0][:10].tolist()]
这篇关于按位置切片MultiIndex pandas DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!