问题
I have a data frame as follows:
ID Date ColA1 ColB1 ColA2 ColB2 ColA3 ColB3
id1 date1 1 2 3 4 5 6
id2 date2 7 8 9 10 11 12
How can I split the columns ColA2, ColB2, ColA3, ColB3 and merge them again to the dataset as rows (considering the ID and Date columns)?
Expected output:
ID Date ColA ColB
id1 date1 1 2
id1 date1 3 4
id1 date1 5 6
id2 date2 7 8
id2 date2 9 10
id2 date2 11 12
Thank you!
回答1:
you need wide_to_long
pd.wide_to_long(df.reset_index(), stubnames = ['ColA', 'ColB'], i = 'index', j = 'value').reset_index(drop = True)
ColA ColB
0 1 2
1 7 8
2 3 4
3 9 10
4 5 6
5 11 12
Edit
Output without reset_index()
pd.wide_to_long(df.reset_index(), stubnames = ['ColA', 'ColB'], i = 'index', j = 'value')
ColA ColB
index value
0 1 1 2
1 1 7 8
0 2 3 4
1 2 9 10
0 3 5 6
1 3 11 12
Edit2
With the new data sample provide by OP:
pd.wide_to_long(df, stubnames = ['ColA', 'ColB'], i = ['ID', 'Date'], j = 'value').reset_index([0,1])
ID Date ColA ColB
value
1 id1 date1 1 2
2 id1 date1 3 4
3 id1 date1 5 6
1 id2 date2 7 8
2 id2 date2 9 10
3 id2 date2 11 12
来源:https://stackoverflow.com/questions/55943641/how-to-split-columns-and-merge-them-as-rows