【问题标题】:How to use Pandas merge all columns' value into one column, and header names become a new column's field value?如何使用 Pandas 将所有列的值合并为一列,并且标题名称成为新列的字段值?
【发布时间】:2022-12-11 18:25:21
【问题描述】:
我有一个这样的数据框:
| Test A |
Test B |
Test C |
| 22 |
45 |
24 |
| 56 |
62 |
52 |
| 73 |
68 |
11 |
| 13 |
34 |
96 |
我想转变为:
| Test Name |
Result |
| Test A |
22 |
| Test A |
56 |
| Test A |
73 |
| Test A |
13 |
| Test B |
45 |
| Test B |
62 |
| Test B |
68 |
| Test B |
34 |
| Test C |
24 |
| Test C |
52 |
| Test C |
11 |
| Test C |
96 |
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
您可以使用 pandas.melt :
out = df.melt(var_name="Test Name", value_name="Result")
# 输出 :
print(out)
Test Name Result
0 Test A 22
1 Test A 56
2 Test A 73
3 Test A 13
4 Test B 45
.. ... ...
7 Test B 34
8 Test C 24
9 Test C 52
10 Test C 11
11 Test C 96
[12 rows x 2 columns]