简体   繁体   中英

Iterate over Pandas dataframe rows

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 ie 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]})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM