Pandas:如何在数据帧的行和列上拥有多索引?

时间:2017-05-20 14:43:23

标签: python pandas dataframe

有没有办法在行和列上创建具有多索引的数据框? (如下图所示)
注意:粗体单元格代表索引。

Multi-index on both rows and columns

1 个答案:

答案 0 :(得分:1)

您可以将索引名称放在元组中,然后使用pd.MultiIndex.from_tuples(),如:

import pandas as pd
import numpy as np


columns = [["A","B","C","D","E"],
           ["f8gh", "ht6k", "gf4h", "fs2e", "po9a"]
          ]

c_tuples = list(zip(*columns))
multi_columns = pd.MultiIndex.from_tuples(c_tuples)

index = [[11869, 14363, 29554, 34554, 52473, 62948], 
         [14414, 29806, 31109, 36081, 54936, 63887], 
         ["+", "-", "+", "-", "+", "+"],
         ["1L1", "7P", "02-11", "38A", "4P", "11P"]]

i_tuples = list(zip(*index))
multi_index = pd.MultiIndex.from_tuples(i_tuples)


data = [10, 9,2,7,7,2,7,8,6,5,1,7,2,9,10,6,2,4,10,7,4,6,4,4,3,2,6,9,7,5]

pd.DataFrame(np.array(data).reshape((len(multi_index),len(multi_columns))), 
             index=multi_index,
             columns=multi_columns)

Output