0

I am new to python and can't seem to find a solution. Currently, my pandas dataframe is of format:

     841  818  813  800  788
399  3.0  4.0  3.0  NaN  NaN
400  NaN  NaN  NaN  3.0  3.0

Where 399 and 400 are unique ids. I am trying to make it so that unique ids will repeat until all columns are separated as rows. Like this:

399  841  3.0
399  818  4.0
...
400  841  NaN
400  818  NaN
...

Any help would be appreciated, thanks!

3
  • 1
    df.stack(dropna=False)? Commented Nov 10, 2020 at 16:28
  • It's just how it looks. Maybe df.stack(dropna=False).reset_index(). Commented Nov 10, 2020 at 16:31
  • Thanks, .stack is what I was looking for. However, since I need this exact format, I will search more on .stack, but this should be enough to figure it out! Commented Nov 10, 2020 at 16:39

1 Answer 1

1

Thanks, Quang Hoang, this solution does work! Here is a straight-forward answer for those who might search for this in the future if your pandas dataframe is named "data_df" then just do this:

data_df = data_df.stack(dropna=False).reset_index()

P.S.: when you print it to see the result, enumeration in the first column is not a part of the dataframe so don't worry. Also, "level_0", "level_1", "0" in the first row are just column names

Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.