列和行上的MultiIndex

时间:2017-08-30 08:17:37

标签: python pandas

我尝试使用pd.MultiIndex,但它只显示类似screen cap

的内容

还有其他方法可以获得此结果吗?这是我使用的代码:

df1 = pd.DataFrame.merge(sad,das, how='outer')
df1.set_index(['parent_category','category','name'], inplace= True)
df1.fillna(value=0)
df1

header = pd.MultiIndex.from_product([['January','February','March','April','May','June','July'],['Purchased','Sold','Inventory']], names = ['months','header'])
df2 = pd.DataFrame(df1,columns=header)
df2

1 个答案:

答案 0 :(得分:0)

您可以将新列名称分配给df1 columns,但必须使用相同长度的原始列和Multiindex:

df1 = pd.merge(sad,das, how='outer') \
        .set_index(['parent_category','category','name']) \
        .fillna(value=0)

months = ['January','February','March','April','May','June','July']
items = ['Purchased','Sold','Inventory']

len(pd.MultiIndex.from_product([months,items], names = ['months','header']))
21

len(df1.columns)

df1.columns = pd.MultiIndex.from_product([months,items], names = ['months','header'])

df1