我在创建带有多索引问题的Pandas Dataframe时遇到问题。在下面的数据中,您将看到其2个银行的数据,每个银行有2个资产,每个资产有3个功能。 我的数据具有类似的结构,因此我想据此创建一个数据框。
Data = [[[2,4,5],[3,4,5]],[[6,7,8],[9,10,11]]]
Banks = ['Bank1', 'Bank2']
Assets = ['Asset1', 'Asset2']
Asset_feature = ['private','public','classified']
我尝试了多种方法来执行此操作,但始终无法创建准确的数据框。结果应如下所示:
Asset1 Asset2
private public classified private public classified
Bank1 2 4 5 3 4 5
Bank2 6 7 8 9 10 11
任何帮助将不胜感激。
答案 0 :(得分:2)
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
给出此输出
Asset1 Asset2
private public classified private public classified
Bank1 2 4 5 3 4 5
Bank2 6 7 8 9 10 11