1. 程式人生 > >pandas中行列轉換

pandas中行列轉換

In [31]: import pandas as pd
    ...: import numpy as np
    ...: df = pd.DataFrame(np.arange(8).reshape(2,4),index=['AA','BB'],columns=
    ...: [['two','two','one','one'],['A','B','C','D']])
    ...: df
    ...:
Out[31]:
   two    one
     A  B   C  D
AA   0  1   2  3
BB   4  5   6  7

In [32]: df.stack()
Out[32]:
      one  two
AA A  NaN  0.0
   B  NaN  1.0
   C  2.0  NaN
   D  3.0  NaN
BB A  NaN  4.0
   B  NaN  5.0
   C  6.0  NaN
   D  7.0  NaN

In [33]: df.stack(level=0)
Out[33]:
          A    B    C    D
AA one  NaN  NaN  2.0  3.0
   two  0.0  1.0  NaN  NaN
BB one  NaN  NaN  6.0  7.0
   two  4.0  5.0  NaN  NaN

In [34]: df.stack(level=1)
Out[34]:
      one  two
AA A  NaN  0.0
   B  NaN  1.0
   C  2.0  NaN
   D  3.0  NaN
BB A  NaN  4.0
   B  NaN  5.0
   C  6.0  NaN
   D  7.0  NaN

In [35]: df.stack(level=-1)
Out[35]:
      one  two
AA A  NaN  0.0
   B  NaN  1.0
   C  2.0  NaN
   D  3.0  NaN
BB A  NaN  4.0
   B  NaN  5.0
   C  6.0  NaN
   D  7.0  NaN

In [36]: df.stack(level=[0,1])
Out[36]:
AA  one  C    2.0
         D    3.0
    two  A    0.0
         B    1.0
BB  one  C    6.0
         D    7.0
    two  A    4.0
         B    5.0
dtype: float64