如何在 python 中重组我的数据框以满足特定视图 - T 和 melt 函数不起作用

How to restructure my data frame in python to meet a certain view - T & melt functions didn't work

我有以下数据要从中更改结构 it current format here

df = pd.DataFrame({'SESSION ID': [123456,789456,101112,131415],
                  'APP-F': [3,2,4,3],'APP-M':[3,3,3,3],
                  'COM-F':[3,3,3,3],'COM-M':[3,3,3,3],
                  'RTW-F':[3,2,3,3],'RTW-F':[3,3,3,3]  })


| SESSION ID| APP-F | APP-M | COM-F | COM-M | RTW-F | RTW-M |
| ---       | ---   | ---   | ---   | ---   | ---   | ---   |
| 123456    | 3     | 3     | 3     | 3     | 3     | 3     |
| 789456    | 2     | 3     | 3     | 3     | 2     | 3     |
| 101112    | 4     | 3     | 3     | 3     | 2     | 3     |
| 131415    | 4     | 3     | 3     | 3     | 2     | 3     |

在您上面看到的数据样本中,我测量了某些能力,例如 APP、COM 和 RTW,以比较不同培训课程中的男性 (M) 和女性 (F)。我尝试了 melt 和 transpose 函数来帮助我 achieve this final format 但没有运气。

df_transpose=df.T
df_transpose.head()

data after I used the above transpose command

我最接近的是当我将数据拆分为 F 和 M 时,我使用 iterrows

_list = []

for row_index,row in df.iterrows():
    r = row.to_dict()
    _list.append(r)

_list

输出看起来与我想要的非常相似,但如何将其导出到文件?

Here is how the output looks like

一个选项是 pandas' wide_to_long,您确实需要重新调整列的形状:

temp = df.set_index('SESSION ID')
temp.columns = temp.columns.str.split('-').str[::-1].str.join('-')
pd.wide_to_long(
    temp.reset_index(), 
    stubnames=['F','M'], 
    sep='-', 
    i='SESSION ID', 
    j='other', 
    suffix='.+').dropna()

                  F    M
SESSION ID other
123456     APP    3  3.0
789456     APP    2  3.0
101112     APP    4  3.0
131415     APP    3  3.0
123456     COM    3  3.0
789456     COM    3  3.0
101112     COM    3  3.0
131415     COM    3  3.0