0

I have the following DataFrame:

Category score_1 score_2 score_3
A 0.23 0.14 0.19
B 0.50 0.55 0.60
C 0.21 0.34 0.30

I would like to transform the previous DataFrame into the following one:

Scores Category Value
score_1 A 0.23
score_1 B 0.14
score_1 C 0.19
score_2 A 0.50
score_2 B 0.55
score_2 C 0.60
score_3 A 0.21
score_3 B 0.34
score_3 C 0.30

Is there any method in pandas to perform this kind of operation?

Javier Monsalve
  • 326
  • 3
  • 14

1 Answers1

1

You can use pd.melt():

res = df.melt(id_vars='Category')

print(res)

  Category variable  value
0        A  score_1   0.23
1        B  score_1   0.50
2        C  score_1   0.21
3        A  score_2   0.14
4        B  score_2   0.55
5        C  score_2   0.34
6        A  score_3   0.19
7        B  score_3   0.60
8        C  score_3   0.30
sophocles
  • 13,593
  • 3
  • 14
  • 33