[英]Convert Columns into rows DataFrame
我有以下數據幀:
姓名 | 一種 | 乙 | C | D | 乙 |
---|---|---|---|---|---|
英熱單位 | 2 | 3 | 0 | 9 | 7 |
BTP | 1 | 2 | 7 | 9 | 0 |
我想要這個:
姓名 | 信 | 價值 |
---|---|---|
英熱單位 | 一種 | 2 |
英熱單位 | 乙 | 3 |
英熱單位 | C | 0 |
英熱單位 | D | 9 |
英熱單位 | 乙 | 7 |
BTP | 一種 | 1 |
BTP | 乙 | 2 |
BTP | C | 7 |
BTP | D | 9 |
BTP | 乙 | 0 |
我該怎么做?
你可以用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)
結果:
姓名 | 信 | 價值 | |
---|---|---|---|
0 | 英熱單位 | 一種 | 2 |
2 | 英熱單位 | 乙 | 3 |
4 | 英熱單位 | C | 0 |
6 | 英熱單位 | D | 9 |
8 | 英熱單位 | 乙 | 7 |
1 | BTP | 一種 | 1 |
3 | BTP | 乙 | 2 |
5 | BTP | C | 7 |
7 | BTP | D | 9 |
9 | BTP | 乙 | 0 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.