bill
bill

Reputation: 722

Convert pandas dataframe to series

Is there a way to convert pandas dataframe to series with multiindex? The dataframe's columns could be multi-indexed too.

Below works, but only for multiindex with labels.

In [163]: d
Out[163]:

a  0     1
b  0  1  0  1
a  0  0  0  0
b  1  2  3  4
c  2  4  6  8

In [164]: d.stack(d.columns.names)
Out[164]:

   a  b
a  0  0    0
      1    0
   1  0    0
      1    0
b  0  0    1
      1    2
   1  0    3
      1    4
c  0  0    2
      1    4
   1  0    6
      1    8
dtype: int64

Upvotes: 3

Views: 2164

Answers (1)

jezrael
jezrael

Reputation: 862396

I think you can use nlevels for find length of levels in MultiIndex, then create range with stack:

print (d.columns.nlevels)
2

#for python 3 add `list`
print (list(range(d.columns.nlevels)))
[0, 1]

print (d.stack(list(range(d.columns.nlevels))))
   a  b
a  0  0    0
      1    0
   1  0    0
      1    0
b  0  0    1
      1    2
   1  0    3
      1    4
c  0  0    2
      1    4
   1  0    6
      1    8
dtype: int64

Upvotes: 5

Related Questions