Pandas行的多级索引

时间:2017-05-04 17:30:09

标签: pandas multi-index

这应该是一件简单的事情,但经过几个小时的搜索后,我仍然因为我做错了而感到茫然。

我尝试过使用MultiIndexing.from_和其他多种方法的不同方法,但我无法做到这一点。

我需要这样的东西:
enter image description here

但我得到了:
enter image description here 我做错了什么?

import pandas as pd

list_of_customers = ['Client1', 'Client2', 'Client3']
stat_index = ['max', 'current', 'min']
list_of_historic_timeframes = ['16:10', '16:20', '16:30']

timeblock = pd.DataFrame(index=([list_of_customers, stat_index]), columns=list_of_historic_timeframes)
timeblock.fillna(0, inplace=True)

print(timeblock)

1 个答案:

答案 0 :(得分:3)

list_of_customers = ['Client1', 'Client2', 'Client3']
stat_index = ['max', 'current', 'min']
list_of_historic_timeframes = ['16:10', '16:20', '16:30']


timeblock = pd.DataFrame(
    0,
    pd.MultiIndex.from_product(
        [list_of_customers, stat_index],
        names=['Customer', 'Stat']
    ),
    list_of_historic_timeframes
)

print(timeblock)

                  16:10  16:20  16:30
Customer Stat                        
Client1  max          0      0      0
         current      0      0      0
         min          0      0      0
Client2  max          0      0      0
         current      0      0      0
         min          0      0      0
Client3  max          0      0      0
         current      0      0      0
         min          0      0      0