Integer (K, N) indexing of multi-index data frames

Let's say I have a sorted multi-index framework:

color  food      one        two
green  ham   0.565738  1.545659
       eggs -0.974236 -0.070345
red    eggs  1.033801 -2.400454
       ham  -0.785435  0.462060
       pork  0.704228  0.523508

...

How to get all the elements associated with the Kth value for the 1st level . For example, if K=2, we would get:

red    eggs  1.033801 -2.400454
       ham  -0.785435  0.462060
       pork  0.704228  0.523508

In general, what is the syntax for ilocfor multi-level DataFrames?

Update:

Check out this GitHub ticket to continue with the topic: "Awkward" Integer Indexing in DataFrames MultiIndex

+4
source share
2 answers

, , Kth Nth:

df.xs(df.index.levels[N][K], level=N)
+2

, :

In [18]: df.loc[['green']]
Out[18]: 
                 one       two
green ham   0.261355  0.182691
      eggs  0.243253 -0.360223

[2 rows x 2 columns]

iloc,

In [24]: df.iloc[0:2]
Out[24]: 
                 one       two
green ham   0.261355  0.182691
      eggs  0.243253 -0.360223

[2 rows x 2 columns]

k- ( 2) = 0

In [35]: df.groupby(level=0).head(2)
Out[35]: 
                 one       two
green ham   0.261355  0.182691
      eggs  0.243253 -0.360223
red   eggs -0.147635  0.555402
      ham   1.815182  0.158497

[4 rows x 2 columns]

n- (k-1); ,

In [36]: df.groupby(level=0).nth(2)
Out[36]: 
               one       two
red pork -0.158261 -0.963434

[1 rows x 2 columns]

In [37]: df.groupby(level=0).nth(1)
Out[37]: 
                 one       two
green eggs  0.243253 -0.360223
red   ham   1.815182  0.158497

[2 rows x 2 columns]
+3

Source: https://habr.com/ru/post/1531417/


All Articles