如何在MultiIndex中添加级别?

时间:2017-03-05 18:27:10

标签: python pandas dataframe multi-index

index = [np.array(['foo', 'foo', 'qux']),
         np.array(['a', 'b', 'a'])]
data = np.random.randn(3, 2)
columns = ["X", "Y"]
df = pd.DataFrame(data, index=index, columns=columns)
df.index.names = ["Level0", "Level1"]
print df

                      X         Y
Level0 Level1                    
foo    a       0.418549  0.252685
       b      -1.307099  0.202833
qux    a       0.046095 -0.968976

新级别

我想获取df的索引并创建一个新的MultiIndex,现在有一个额外的级别。

new_level_name = "New level"
new_level_labels = ['p', 'q']
# new_multi-index 

所需的MultiIndex

Level0 Level1 Level2                    
foo    a      p       
              q       
       b      p      
              q       
qux    a      p      
              q      

2 个答案:

答案 0 :(得分:4)

最简单的方法是使用stackDataFrame新列级别的列:

df1 = pd.DataFrame(data=1,index=df.index, columns=new_level_labels).stack()
df1.index.names = ['Level0','Level1',new_level_name]
print (df1)
Level0  Level1  New level
foo     a       p            1
                q            1
        b       p            1
                q            1
qux     a       p            1
                q            1
dtype: int64

print (df1.index)
MultiIndex(levels=[['foo', 'qux'], ['a', 'b'], ['p', 'q']],
           labels=[[0, 0, 0, 0, 1, 1], [0, 0, 1, 1, 0, 0], [0, 1, 0, 1, 0, 1]],
           names=['Level0', 'Level1', 'New level'])

答案 1 :(得分:0)

不确定要在所需的DataFrame中包含哪些数据,但是对于类似的问题,我使用了df1 = df.reset_index() pd.melt(df1, id_vars=['Level0', 'Level1']) Level0 Level1 variable value 0 foo a X 0.678564 1 foo b X -0.609134 2 qux a X 0.505178 3 foo a Y -2.593380 4 foo b Y -0.232796 5 qux a Y -1.420875

 import SwiftUI

 struct ContentView: View {

@State var selection: Int?

var body: some View {
    #if targetEnvironment(macCatalyst)
    return theList.listStyle(SidebarListStyle())
    #else
    return theList.navigationViewStyle(DefaultNavigationViewStyle())
    #endif
}

 var theList: some View {
 HStack() {
   NavigationView {
     List () {
       NavigationLink(destination: FirstView(), tag: 0, selection: self.$selection) {
         Text("Click Me To Display The First View")
       } // End Navigation Link

       NavigationLink(destination: SecondView(), tag: 1, selection: self.$selection) {
         Text("Click Me To Display The Second View")
       } // End Navigation Link

     } // End list
     .frame(minWidth: 350, maxWidth: 350)
     .onAppear {
         self.selection = 0
     }

   } // End NavigationView
     .frame(maxWidth: .infinity, maxHeight: .infinity)

 } // End HStack
 } // End some View
 } // End ContentView
 }