-1

I have a huge pandas dataflame such as

    A   B   C   D   E
0:  a0  b0  c0  d0  e0
1:  a1  b1  c1  d1  e1
2:  a2  b2  c2  d2  e2

I want to change it into:

    A   B   C   X   Y
0:  a0  b0  c0  D   d0
0:  a0  b0  c0  E   e0
1:  a1  b1  c1  D   d1
1:  a1  b1  c1  E   e2
2:  a2  b2  c2  D   d1
2:  a2  b2  c2  E   e2

How can I do that?

So far I am creating a new dataFrame and populating it with a for-loop.

Chutlhu
  • 195
  • 2
  • 10

1 Answers1

1

You can do via set index, and stack:

df = (df.set_index(list('ABC'))
        .stack()
        .reset_index()
        .rename(columns={'level_3': 'X', 0: 'Y'})
)


    A   B   C  X   Y
0  a0  b0  c0  D  d0
1  a0  b0  c0  E  e0
2  a1  b1  c1  D  d1
3  a1  b1  c1  E  e1
4  a2  b2  c2  D  d2
5  a2  b2  c2  E  e2
manwithfewneeds
  • 1,137
  • 1
  • 7
  • 10