Python Pandas从宽到长格式更改(带有列标题拆分) [英] Python Pandas Wide to Long Format Change with Column Titles Spliting
问题描述
我有一个表,其中包含以下列标题和一个行示例:
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
我想将其转换为:
Subject level_1 Result1 Result2
0 John Test1 10 0.5
1 John Test2 20 0.3
对于Test1,重复一次主题列表,然后对于Test2,再次重复主题列表.
With the subjects list repeated once for Test1 and then again for Test2.
我想我可以使用for循环来做到这一点,但是还有更多的Python方式吗?
I think I can do this using for loops, but it's there a more pythonic way?
对于额外的复杂性,我需要为每个测试添加一列额外的信息.我想我可以使用字典,但是如何在每个对应的行中插入有关Test1的信息?
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?
推荐答案
您可以将列拆分为多索引列,然后重塑数据框架:
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()
这篇关于Python Pandas从宽到长格式更改(带有列标题拆分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!