将MultiIndex转换为数据框

时间:2019-08-08 12:31:35

标签: python pandas multi-index

如何将MultiIndex转换为“常规”数据帧?

假设我有一个:

columns = pd.MultiIndex.from_product([['C1', 'C2'], ['CA', 'CO', 'MI']],
                                  names=['subject', 'type'])

data=np.array(list(string.ascii_lowercase))[:24].reshape((4, 6))

df = pd.DataFrame(
    columns=columns,
    data=data
)

我想转换成这样的东西(或类似想法的东西):

columns = ['name', 'subject', 'type']
agents_data = [
    (0, 'C1', 'CA', 'a'),
    (0, 'C1', 'CO', 'b'),
    ...
    (2, 'C2', 'CA', 'p'),
]
return pd.DataFrame.from_records(agents_data, columns=columns)

有没有办法做到这一点? (或类似的东西)

类似这样的东西:

enter image description here

对此:

enter image description here

谢谢!

1 个答案:

答案 0 :(得分:2)

DataFrame.unstackDataFrame.reset_indexrename一起使用:

df1 = df.unstack().reset_index(name='val').rename(columns={'level_2':'new'})
print (df1)
   subject type  new val
0       C1   CA    0   a
1       C1   CA    1   g
2       C1   CA    2   m
3       C1   CA    3   s
4       C1   CO    0   b
5       C1   CO    1   h
6       C1   CO    2   n
7       C1   CO    3   t
8       C1   MI    0   c
9       C1   MI    1   i
10      C1   MI    2   o
11      C1   MI    3   u
12      C2   CA    0   d
13      C2   CA    1   j
14      C2   CA    2   p
15      C2   CA    3   v
16      C2   CO    0   e
17      C2   CO    1   k
18      C2   CO    2   q
19      C2   CO    3   w
20      C2   MI    0   f
21      C2   MI    1   l
22      C2   MI    2   r
23      C2   MI    3   x

谢谢@Mark Wang在unstack之前使用DataFrame.rename_axis进行创意:

df1 = df.rename_axis('new').unstack().reset_index(name='val')
print (df1)
   subject type  new val
0       C1   CA    0   a
1       C1   CA    1   g
2       C1   CA    2   m
3       C1   CA    3   s
4       C1   CO    0   b
5       C1   CO    1   h
6       C1   CO    2   n
7       C1   CO    3   t
8       C1   MI    0   c
9       C1   MI    1   i
10      C1   MI    2   o
11      C1   MI    3   u
12      C2   CA    0   d
13      C2   CA    1   j
14      C2   CA    2   p
15      C2   CA    3   v
16      C2   CO    0   e
17      C2   CO    1   k
18      C2   CO    2   q
19      C2   CO    3   w
20      C2   MI    0   f
21      C2   MI    1   l
22      C2   MI    2   r
23      C2   MI    3   x