0

I have a MultiIndex dataframe from (made with pivot_table) that looks like

          col1 col2 col3
item 1 a  0    0    0
       b  1    1    1
item 2 a  0    0    0
       c  1    2    3

Where the first 2 columns are an index. I'd like to iterate over each row and get the sub-table i.e. for 'item 1'

  col1 col2 col3
a  0    0    0
b  1    1    1

and possibly divide again into

  col1 col2 col3
a  0    0    0

These values are originally getting transformed into cards in a GUI

I've tried various combinations of changing indexes, iterrows, xs, but I always seem to only be able to get things using (index1,index2) like (item 1, a, 0,0,0) where I'd like to split them apart like (item 1, {a:[0,0,0], b:[0,0,0]})

1 Answer 1

2

Use

In [4482]: for i, g in df.groupby(level=0):
      ...:     print g.loc[i]
      ...:
   col1  col2  col3
a     0     0     0
b     1     1     1
   col1  col2  col3
a     0     0     0
c     1     2     3

One more level

In [4488]: for i, g in df.groupby(level=0):
      ...:     print '--------Parent--------', i
      ...:     print g.loc[i]
      ...:     for ii, gg in g.loc[i].groupby(level=0):
      ...:         print '----------child--------', ii
      ...:         print gg
      ...:
--------Parent-------- item 1
   col1  col2  col3
a     0     0     0
b     1     1     1
----------child-------- a
   col1  col2  col3
a     0     0     0
----------child-------- b
   col1  col2  col3
b     1     1     1
--------Parent-------- item 2
   col1  col2  col3
a     0     0     0
c     1     2     3
----------child-------- a
   col1  col2  col3
a     0     0     0
----------child-------- c
   col1  col2  col3
c     1     2     3
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.