简体   繁体   中英

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

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

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