首页 > 解决方案 > 将 Pandas DataFrame 转换为单行 DataFrame,将一列的值保存为标题

问题描述

我有第一个数据框,我想将其转换为所需的数据框。我见过类似的问题,我的问题有点复杂。

# My data frame
F,A,B,C,D,E
---------
 Fo,1,2,3,4,5
 Foo,6,7,8,9,10
 Fooo,11,12,13,14,15


# my desirable data frame
A_Fo,B_Fo,C_Fo,D_Fo,E_Fo,A_Foo,B_Foo,C_Foo,D_Foo,E_Foo,A_Fooo,B_Fooo,C_Fooo,D_Fooo,E_Fooo
--------------------------
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15


标签: pythonpandas

解决方案


Let us try this:

stacked = df.stack()

new_idx = list()
for l in stacked.index.levels[1]:
    for f in stacked.index.levels[0]:
        new_idx.append(l + '_' + f)

stacked.reset_index(drop=True, inplace=True)
stacked.index = new_idx
print(stacked.to_frame())

Output:

    A_fo    A_foo   A_fooo  B_fo    B_foo   B_fooo  C_fo    C_foo   C_fooo  D_fo    D_foo   D_fooo  E_fo    E_foo   E_fooo
0   1         2       3       4       5       6       7       8       9      10       11     12      13      14     15

推荐阅读