简体   繁体   中英

Convert Columns into rows DataFrame

I have the following DataFrame:

Name A B C D E
BTU 2 3 0 9 7
BTP 1 2 7 9 0

And I want this:

Name letter Value
BTU A 2
BTU B 3
BTU C 0
BTU D 9
BTU E 7
BTP A 1
BTP B 2
BTP C 7
BTP D 9
BTP E 0

How can I do it?

You can do this with melt :

pd.melt(df, id_vars=['Name'], value_vars=['A', 'B', 'C', 'D', 'E'], var_name='letter', value_name='Value').sort_values(by='Name', ascending=False)

Result:

Name letter Value
0 BTU A 2
2 BTU B 3
4 BTU C 0
6 BTU D 9
8 BTU E 7
1 BTP A 1
3 BTP B 2
5 BTP C 7
7 BTP D 9
9 BTP E 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM