Creating a Pandas Dataframe with Multi Column Index

Viewed 2782

I have a problem creating a Pandas Dataframe with multi indexing issue. In the data below, you will see that its the data for 2 banks, and each bank has 2 assets and each asset has 3 features. My data is similarly structured and I want to create a dataframe out of this.

Data = [[[2,4,5],[3,4,5]],[[6,7,8],[9,10,11]]]

Banks = ['Bank1', 'Bank2']

Assets = ['Asset1', 'Asset2']

Asset_feature = ['private','public','classified']

I have tried various ways to do this but I've always failed to create an accurate dataframe. The result should look something like this:

      Asset1                      Asset2
      private public classified   private public classified
Bank1   2       4       5           3       4       5
Bank2   6       7       8           9       10      11

Any help would be much appreciated.

1 Answers
import pandas as pd
import numpy as np
assets = ['Asset1', 'Asset2']
Asset_feature = ['private','public','classified']
Banks = ['Bank1', 'Bank2']
Data = [[[2,4,5],[3,4,5]],[[6,7,8],[9,10,11]]]
Data = np.array(Data).reshape(len(Banks),len(Asset_feature) * len(assets))


midx = pd.MultiIndex.from_product([assets, Asset_feature])
test = pd.DataFrame(Data, index=Banks, columns=midx)
test

which gives this output

       Asset1                    Asset2                  
      private public classified private public classified
Bank1       2      4          5       3      4          5
Bank2       6      7          8       9     10         11
Related