将一级行移至列,将列移至行

时间:2018-07-17 03:52:50

标签: python pandas

我有以下矩阵

c1st                1                   2          
c2nd                a         b         a         b
id1st id2nd                                        
bar   one    0.293321 -1.173014  0.045621  0.565526
      two    0.078300 -1.061078  0.332950 -0.563532
baz   one    0.578437  1.600270 -0.446242 -0.861848
      two    0.025128  1.189281 -1.487797 -1.044918
foo   one    1.791755  1.914113  0.334240 -0.698200
      two   -0.203376  0.321410 -0.445128  0.747344
qux   one   -1.375511  1.084954 -0.531304 -1.020195
      two   -0.094798 -1.066290  0.794430 -0.948802

生成
import numpy as np
arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
          np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
s = pd.Series(np.random.randn(8), index=arrays)

df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

df.index.names = ['id1st', 'id2nd']

iterables = [[1, 2], ['a', 'b']]
df.columns = \
    pd.MultiIndex.from_product(iterables, names=['c1st', 'c2nd'])
  • 如何将id2nd移至列的第三级?
  • 如何将c2nd移至行索引的第三级?

1 个答案:

答案 0 :(得分:1)

如何将id2nd移至列的第三级?

使用div { width: 100px; height: 100px; position: relative; -webkit-animation-name: example; /* Safari 4.0 - 8.0 */ -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */ animation-name: example; animation-duration: 4s; animation-timing-function: linear; /* Add this */ } @keyframes example { 0% { background-color: red; left: 0px; top: 0px; transform-origin: 0% 0%; /* Add this */ transform: scale(0.1,1); } 100% { background-color: yellow; left: 0px; top: 0px; transform-origin: 0% 0%; /* Add this */ transform: scale(1,1); } }

unstack

如何将c2nd移至行索引的第三级?

使用df.unstack() Out[482]: c1st 1 2 \ c2nd a b a b id2nd one two one two one two one id1st bar 0.041343 -0.752158 -0.711644 -1.577000 -0.454746 -1.889375 -0.644445 baz 1.684986 -0.423235 1.143991 -0.136017 -2.735571 -0.024267 0.393892 foo 0.618897 1.356303 -1.153296 0.624918 0.693133 -0.804281 0.772482 qux 1.722674 -1.025345 -0.406572 -0.207286 -0.030559 0.773167 -0.446558 c1st c2nd id2nd two id1st bar -0.287645 baz -0.998609 foo 0.679210 qux 0.012901

stack