0

I am unsure how to word this question.

I have data that looks like the following:

     |type1|type2|type3|
------------------------
var1 |  N1 |  N2 |  N3
var2 |  N4 |  N5 |  N6
.    |  .  |  .  |  .
.    |  .  |  .  |  .
.    |  .  |  .  |  .

I want to turn it into this:

     | type | val |
-------------------
var1 | type1| N1  |
var1 | type2| N2  |
var1 | type3| N3  |
var2 | type1| N4  | 
var2 | type2| N5  | 
var2 | type3| N6  |
.    |  .   |  .  |
.    |  .   |  .  |
.    |  .   |  .  |

How can I go about this?

DudeWah
  • 359
  • 3
  • 20

1 Answers1

1

DataFrame.melt() should do what you want.

df = pd.DataFrame({"abc": [3, 2, 1], "def": ["a", "b", "c"], "ghi": [3, 4, 5]})
df

Yields:

abc def ghi
0   3   a   3
1   2   b   4
2   1   c   5

Then

df.melt(id_vars=["abc"], value_vars=["def", "ghi"])

Yields:

abc variable    value
0   3   def a
1   2   def b
2   1   def c
3   3   ghi 3
4   2   ghi 4
5   1   ghi 5
Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31