Python Pandas Wide to Long Format Change with Column Titles Spliting

别等时光非礼了梦想. 提交于 2019-12-23 09:56:58

问题


I have a table with the following columns titles and a row example:

  Subject  Test1-Result1  Test1-Result2  Test2-Result1  Test2-Result2
0    John             10            0.5             20            0.3

I would like to transform it to:

  Subject level_1  Result1  Result2
0    John   Test1       10      0.5
1    John   Test2       20      0.3

With the subjects list repeated once for Test1 and then again for Test2.

I think I can do this using for loops, but it's there a more pythonic way?

For extra complexity, I need to add an extra column of information for each test. I suppose I can use a dictionary, but how can I insert the information about, say Test1, in each corresponding row?


回答1:


You can split your columns into a multi-index column and then reshape your data frame:

df.set_index('Subject', inplace=True)
df.columns = df.columns.str.split("-", expand=True)
df.stack(level=0).rename_axis(['Subject', 'Test']).reset_index()



来源:https://stackoverflow.com/questions/40643445/python-pandas-wide-to-long-format-change-with-column-titles-spliting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!