0

Given the following dataframe:

Number    Color1    Color2
 1         Red      Yellow
 2         Green    Blue

How can I reshape this dataframe around the "Number" column?

Expected output

Number    Color
  1        Red
  1        Yellow
  2        Green
  2        Blue

Note: The column names may not always be similar (Color1 and Color2 could be anything and aren't related)

MaxB
  • 428
  • 1
  • 8
  • 24

2 Answers2

0

For that you can use the stack method from pandas. Here's a link to the pandas doc, and for its inverse, unstack https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html#pandas.DataFrame.stack https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html

Jack Hanson
  • 336
  • 1
  • 2
  • 11
0

df.set_index('Number').stack().reset_index(drop=True, level=1)?

hd1
  • 33,938
  • 5
  • 80
  • 91
  • Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review). – Trenton McKinney Sep 24 '19 at 00:46